text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Deploy different WCF .svc files based on configuration I have a Service1.svc file that is a normal WCF service. If I deploy the WCF project it will happily copy the Service1.svc file along with the binaries and the other files. So far, so good. What I want is, based on the selected build configuration, or some other trick, to publish different contents for the Service1.svc file.
Let's say I have a Service1.Conf1.svc file and a Service1.Conf2.svc file and two configurations (like Debug or Release) that are named Conf1 and Conf2. When I click publish and have the Conf1 configuration selected, I want the publish folder to have a virtually created Service1.svc file whose contents are from Service1.Conf1.svc. When I click publish and have the Conf2 configuration selected, I want the publish folder to have a virtually created Service1.svc file whose contents are from Service1.Conf2.svc.
I would like to have this for the publish action, not the build action (which could be achievable by a post-build or pre-build event). The main purpose is to adjust the contents of the Service1.svc file according to the publish environment.
Any ideas?
A: We took a different approach and generate all required config/svc files for all possible installs (using TT file generation) and let the installer copy the correct configs/svc files (based on user selection during install).
The names of the files are constructed by inserting the target platform name into the standard name e.g web.local.config, web.dev.config, web.test.config etc
This way you can give one installer to anyone from any department. They just choose the platform.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Gsoap undefined references I'm trying to use and web service with gsoap. I've already generated all *.h and *.cpp using wsdl2h and soapcpp2, included all libraries, at least I think so, but when I build the project it gives me the message of undefined references to a lot of methods. The thing is all methods are declared in soapH.h (the prototype) and in soapC.cpp (the implementation).
Any help will be appreciated.
A: It seems that you included some generated header files in your build, which should not. (e.g. the .h file generated from wsdl) There are descriptions in the comment section in each generated files, and you'd better read them to get familiar how to use them.
Also, if you use openssl, the library should also be included during linking process(-lssl)
A: Solved, All I need was the original header file, I was getting one from the wsdl.
A: In case anyone encounteres this problem: you do not have to include all the .cpp files in your makefile - some of them are included by the other. What you need also depends on whether you are building a client or a server.
Consult the documentation here to see which files are needed and for what.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can jsp .tag files be included via a tld file like Java TagSupport classes? Most of my tags are done with .tag files, as its much easier to work with html that way. However, my web applications expect these tags in the web.xml/tags directory, which is a pain when a tag is shared among multiple web apps.
If i understand correct, a java tag class that extends TagSupport can include the tld in the source code, and the tag can be imported easily. Can I do something like that for my .tag files so I can keep them in a shared parent project and not worry about copying them to individual tag folders in my web applications? Is there a way for a tld to point to a .tag file on the classpath?
A: This page says:
Tag files can be placed in one of two locations: in the /WEB-INF/tags/
directory or subdirectory of a web application or in a JAR file (see
Packaged Tag Files) in the /WEB-INF/lib/ directory of a web
application. Packaged tag files require a tag library descriptor (see
Tag Library Descriptors), an XML document that contains information
about a library as a whole and about each tag contained in the
library.
and
Tag files can be packaged in the /META-INF/tags/ directory in a JAR
file installed in the /WEB-INF/lib/ directory of the web application.
Tags placed here are typically part of a reusable library of tags that
can be used easily in any web application.
Tag files bundled in a JAR require a tag library descriptor. Tag files
that appear in a JAR but are not defined in a TLD are ignored by the
web container.
When used in a JAR file, the path subelement of the tag-file element
specifies the full path of the tag file from the root of the JAR.
Therefore, it must always begin with /META-INF/tags/.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Want to add notes in a PowerPoint slides using VB.NET I want to add notes in the PowerPoint slides notes part under the PowerPoint slide using Microsoft.Office.Interop.PowerPoint.
I'm using VB.NET code. Now it is creating the PPT file, and I can add text, comments, and images in the slide. But I need to add notes in the PowerPoint slide, in the bottom part of the slide.
Here is the code I'm using for creating slides.
Dim oApp As Microsoft.Office.Interop.PowerPoint.Application
Dim oPres As Microsoft.Office.Interop.PowerPoint.Presentation
Dim oSlide As Microsoft.Office.Interop.PowerPoint.Slide
Dim bAssistantOn As Boolean
Const sTemplate = "C:\Program Files\Microsoft Office\Templates\Presentation Designs\ContemporaryPhotoAlbum.potx"
Const sPic = "C:\WINDOWS\Soap Bubbles.bmp"
oApp = New Microsoft.Office.Interop.PowerPoint.Application()
oApp.Visible = True
oApp.WindowState = Microsoft.Office.Interop.PowerPoint.PpWindowState.ppWindowMaximized
oApp.Visible = True
oPres = oApp.Presentations.Open(sTemplate, , , True)
oPres = oApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoCTrue)
oSlide = oPres.Slides.Add(1, PpSlideLayout.ppLayoutVerticalTitleAndText)
oSlide.Comments.Add(1, 1, "f", "sf", "sdfgdfg")
With (oSlide.Shapes.Item(1).TextFrame.TextRange)
.Text = "Aspire Software Consultancy"
.Font.Name = "Comic Sans MS"
.Font.Size = 48
End With
oSlide.Shapes.AddPicture(sPic, False, True, 150, 150, 500, 350)
oSlide = oPres.Slides.Add(2, Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutTitleOnly)
With oSlide.Shapes.Item(1).TextFrame.TextRange
.Text = "My Chart"
.Font.Name = "Comic Sans MS"
.Font.Size = 48
End With
oSlide.NotesPage.Comments.Add(4, 4, "asd", "a", "gooooooood")
oSlide = oPres.Slides.Add(3, Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutBlank)
oSlide.FollowMasterBackground = False
Dim oShape As Microsoft.Office.Interop.PowerPoint.Shape
oShape = oSlide.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect27,
"The End", "Impact", 96, False, False, 230, 200)
oShape.Shadow.ForeColor.SchemeColor = Microsoft.Office.Interop.PowerPoint.PpColorSchemeIndex.ppForeground
oShape.Shadow.Visible = True
oShape.Shadow.OffsetX = 3
oShape.Shadow.OffsetY = 3
oShape = Nothing
oSlide = Nothing
Dim SlideIdx(3) As Integer
SlideIdx(0) = 1
SlideIdx(1) = 2
SlideIdx(2) = 3
With oPres.Slides.Range(SlideIdx).SlideShowTransition
.AdvanceOnTime = True
.AdvanceTime = 3
.EntryEffect = Microsoft.Office.Interop.PowerPoint.PpEntryEffect.ppEffectBoxOut
End With
Dim oSettings As Microsoft.Office.Interop.PowerPoint.SlideShowSettings
oSettings = oPres.SlideShowSettings
oSettings.StartingSlide = 1
oSettings.EndingSlide = 3
bAssistantOn = oApp.Assistant.On
oApp.Assistant.On = False
oSettings.Run()
Do While oApp.SlideShowWindows.Count >= 1
System.Windows.Forms.Application.DoEvents()
Loop
oSettings = Nothing
If bAssistantOn Then
oApp.Assistant.On = True
oApp.Assistant.Visible = False
End If
oPres.Save()
oPres.SaveAs("c:\aspire", PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue)
oPres.Saved = True
oPres.Close()
oPres = Nothing
oApp.Quit()
oApp = Nothing
A: I found the following solution and it works for me:
if (slide.NotesPage.Shapes.Count == 0)
{
slide.NotesPage.Shapes.AddShape(MsoAutoShapeType.msoShapeRectangle, 0, 0, 0, 0);
var footerShape = slide.NotesPage.Shapes[1];
footerShape.TextFrame.TextRange.Text = "your note text";
}
else
{
foreach (PowerPoint.Shape shape in slide.NotesPage.Shapes)
{
if (shape.HasTextFrame == MsoTriState.msoTrue)
if (shape.TextFrame.HasText == MsoTriState.msoTrue)
shape.TextFrame.TextRange.Text = "yout note text";
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Establish relationship between managed objects in two different contexts I am parsing JSON string to create new managed objects in a separate thread and in a separate managed object context. Later I want to merge the changes in the main thread by listening to NSManagedObjectContextObjectsDidChangeNotification.
The problem is that I want to establish the relationships between the newly parsed objects and the other objects in the main moc. However I know it is illegal to make relationships between objects in different contexts.
What's the best practice to accomplish this task?
A: If the objects on the main thread are saved they will be available to the new context on a secondary thread because the new context shares access to the persistent store.
If you are creating new objects simultaneously on both threads, you will need to merge the context with each other before each will be aware of the objects created on the other.
Merging essentially makes the context copies of each other at the time of the merge.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dynamic Types of fields in .NET Is it possible to dynamically change the type of the object in a class?
say, I have a Filter class, that specifies a filtering condition for a list of objects of a specific ObjType
Public Class PropertyFilter
Public Property ObjectType as MyObjectsTypeEnum
Public Property MainObjectProperty As ??? OBJECT
End Class
Say, when I change the object type, I would like to change also the type of the MainObjectProperty
say, for a Person the main property could be Name (String type) but for a Shpere the main object could be Radius (double type).
I understand that I could use the generic class, but this is not what I want.
Say in the real class I have more that a property that should change when a ObjectType changes, and the user that will use the Filter should have no worry about the MainObjectProperty type, just it should change the Object type - it's all.
A: That may be a solution for generics. This allows you to have type parameters. Something like this:
Public Class PropertyFilter(Of T)
Public Property ObjectType
Public Property MainObjectProperty As T
End Class
That way, when you create a PropertyFilter, you can specify what MainObjectProperty is, like so:
Dim propWithDecimal As New PropertyFilter(Of Decimal)()
Dim propWithString As New PropertyFilter(Of String)()
This isn't dynamic because the type is still known at compile time. You can learn more about generics at MSDN.
EDIT:
Based on the asker's edits:
That sounds like a bit of a quirky design to me. You can't really change the type of a field at runtime - but there are plenty of ways to make it seem like that behavior exists.
You might be able to achieve what you are looking for with dynamic and implementing your own DynamicOjbect, but that'll be some work as well.
The class should decide itself its property type basing of the ObjectType, if you know what I mean.
If that is the case, you will likely have to store it as an object, and make a decision based on which type the object is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: retrieving rows in reverse direction from table using sql limit I am implementing pagination using SQL limit in MySQL db.Records are needed to get
retrieved from the last row backwards. There are several thousands records in table
and I want to retrieve say 500 records at a time to show up in a page.
SELECT * FROM tbl_name ORDER BY some_col DESC
will retrieve all records.
But I do not want all records, as they are thousands in number.
If I use
SELECT * FROM tbl_name ORDER BY some_col DESC LIMIT 500
it will return last 500 records in descending order.
but I could not find a way to retrieve next block of 500 in reverse direction, starting from a point where first block have left up.
A: SELECT
<column list since I never use *>
FROM
My_Table
ORDER BY
some_column DESC
LIMIT 500, 500
EDIT: Regarding your comment to Robert's answer... Performance will degrade as the offset gets larger, but the point where the degradation is noticeable is usually pretty large. From an answer that I gave to a similar question on paging a day or two ago:
I am of the strong opinion that a UI should NEVER allow a user to
retrieve a set of records that let them go to (for example) page 5000.
That's simply too much data for a human mind to find useful all at
once and should require further filtering. Maybe let them see the
first 100 pages (or some other number), but otherwise they have to
constrain the results better. Just my opinion though.
A: The answer is confusing with your hypothetical numbers, so let me make my own:
Let's say we want to display page 3 with 10 records per page. We want to offset by 20 records (the ones on pages 1 & 2), then find 10 records. The format is:
> SELECT * FROM tbl_name ORDER BY some_col DESC LIMIT 20, 10;
In other words, it's
LIMIT <offset>, <max results>
read more: http://php.about.com/od/mysqlcommands/g/Limit_sql.htm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Initializing object properties - how to do it properly
Possible Duplicate:
Initializing Class Fields at the Field Definition or in Class Contructor
Setting variables on Constructor VS on the class definition
What is the difference (if any) between the following 2 examples, and what is the proper way to initialize object properties?
Please note that the content of $fields in this case is something predefined, it will not change in runtime.
Example 1:
class User
{
$fields = array('username', 'password', 'email');
function __construct()
{
}
}
Example 2:
class User {
$fields;
function __construct()
{
$this->fields = array('username', 'password', 'email');
}
}
A: The first example... It is more explicit and obvious to the reader what the intention of $fields is... "something predefined"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Call multiple HttpWebRequest I need to do several HttpWebRequest requests in a single moment, but when I make the request several times will cost a lot of time. I plan on doing each request in a separate thread and then get all the returns and put it all together when all calls are completed is it possible?
A: Absolutely.
Take a look at the msdn docs on HttpWebRequest.BeginGetResponse Method
I couldn't write a better example than in the docs.
A: I don't know much about Threading, but as they run asynchronously, getting a return value isn't an option. However, this thread : http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/c43c0cce-491a-4ddb-9012-69929fab8e5e/ does point towards the ThreadPool class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook comments generating javascript error I'm having a javascript error in every browsers in local AND online when using Facebook comments. Trying to retreive 0 or multiple comments doesn't seems to change anything.Anyone have an idea?
Error message
Message : 'this._count.value.0' is Null or not an Object.
All.js, Line: 48, Code: 0
URI : http://connect.facebook.net/en_US/all.js#xfbml=1
Code in the page
<fb:comments-count href="<%= WebTools.Permalink %>"></fb:comments-count>
<fb:comments href="<%= WebTools.Permalink %>" num_posts="2" width="839"></fb:comments>
Thanks in advance
A: I've successfully diagnosed and resolved this issue.
Here was my code that was asynchronously loading the Facebook JavaScript SDK:
(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'));
Here was my code that was initializing it:
FB.init({
appId: {APP_ID},
status: true,
cookie: true,
xfbml: true,
oauth: true
});
Note that I've actually requested XFBML parsing twice: once when loading the JavaScript SDK (#xfbml=1), and once when initializing it (xfbml: true).
This causes the error that prevents comment-count tags from rendering.
The resolution is to eliminate one of those two declarations; I would suggest deleting #xfbml=1 from the end of the JavaScript SDK URL, as requesting XFBML parsing at load time seems to be deprecated.
My loader now looks like this:
(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";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
And everything works perfectly.
Synchronous loading
If you load the JavaScript SDK synchronously, change this:
<script src="//connect.facebook.net/en_US/all.js#xfbml=1"></script>
To this:
<script src="//connect.facebook.net/en_US/all.js"></script>
A: I actually found out that this is an issue on Facebook’s end.
The same code work in dev and prod, but not in local or staging...
For more informations
There is a site explaining it in details: http://www.codepreneur.com/2011/07/facebook-like-button-not-working-or-resets-itself/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mysql deliberate slowdown I have an Java application that connects to database. In the production environment, the dataset is very large, so the application very slow and I want to simulate (the slowness) in development environment. Is there a way, how to slowdown mysql, so the response time is bigger?
I know, that I could enlarge my test dataset, but the proccessing of the large dataset would eat processor cycles, I'm rather searching for something that would do "cheap" sleeps in MySQL.
A: MySQL has a SLEEP(duration) miscellaneous function, where duration is the number of seconds.
source: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_sleep
A: You can copy MySQL database files to (slow, old) usb key and set MySQL's setting datadir to point to usb. I copied MySQL data directory to usb key and set datadir variable to usb.
#Path to the database root
#datadir="C:/Program Files (x86)/MySQL/MySQL Server 5.0/Data/"
datadir = "E:/data"
I suppose it's important to set innodb_flush_log_at_trx_commit to 1.
# If set to 1, InnoDB will flush (fsync) the transaction logs to the
# disk at each commit, which offers full ACID behavior. If you are
# willing to compromise this safety, and you are running small
# transactions, you may set this to 0 or 2 to reduce disk I/O to the
# logs. Value 0 means that the log is only written to the log file and
# the log file flushed to disk approximately once per second. Value 2
# means the log is written to the log file at each commit, but the log
# file is only flushed to disk approximately once per second.
innodb_flush_log_at_trx_commit=1
This way each update, delete, insert statement results I/O flush.
A: To add to the SLEEP() function comment, here's an easy way to integrate a sleep into any SQL query when you can't run it as separate statement:
LEFT JOIN (SELECT SLEEP(30)) as `sleep` ON 1=1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SQL:Query to check if a column meets certain criteria, if it does perform one action if it doesn't perform another I have found it quite hard to word what I want to do in the title so I will try my best to explain now!
I have two tables which I am using:
Master_Tab and Parts_Tab
Parts_Tab has the following information:
Order_Number | Completed| Part_Number|
| 1 | Y | 64 |
| 2 | N | 32 |
| 3 | Y | 42 |
| 1 | N | 32 |
| 1 | N | 5 |
Master_Tab has the following information:
Order_Number|
1 |
2 |
3 |
4 |
5 |
I want to generate a query which will return ALL of the Order_Numbers listed in the Master_Tab on the following conditions...
For each Order_Number I want to check the Parts_Tab table to see if there are any parts which aren't complete (Completed = 'N'). For each Order_Number I then want to count the number of uncompleted parts an order has against it. If an Order_Number does not have uncompleted parts or it is not in the Parts_Table then I want the count value to be 0.
So the table that would be generated would look like this:
Order_Number | Count_of_Non_Complete_Parts|
1 | 2 |
2 | 1 |
3 | 0 |
4 | 0 |
5 | 0 |
I was hoping that using a different kind of join on the tables would do this but I am clearly missing the trick!
Any help is much appreciated!
Thanks.
A: I have used COALESCE to convert NULL to zero where necessary. Depending on your database platform, you may need to use another method, e.g. ISNULL or CASE.
select mt.Order_Number,
coalesce(ptc.Count, 0) as Count_of_Non_Complete_Parts
from Master_Tab mt
left outer join (
select Order_Number, count(*) as Count
from Parts_Tab
where Completed = 'N'
group by Order_Number
) ptc on mt.Order_Number = ptc.Order_Number
order by mt.Order_Number
A: You are looking for a LEFT JOIN.
SELECT mt.order_number, count(part_number) AS count_noncomplete_parts
FROM master_tab mt LEFT JOIN parts_tab pt
ON mt.order_number=pt.order_number AND pt.completed='N'
GROUP BY mt.order_number;
It is also possible to put pt.completed='N' into a WHERE clause, but you have to be careful of NULLs. Instead of the AND you can have
WHERE pt.completed='N' OR pr.completed IS NULL
A: SELECT mt.Order_Number SUM(tbl.Incomplete) Count_of_Non_Complete_Parts
FROM Master_Tab mt
LEFT JOIN (
SELECT Order_Number, CASE WHEN Completed = 'N' THEN 1 ELSE 0 END Incomplete
FROM Parts_Tab
) tbl on mt.Order_Number = tbl.Order_Number
GROUP BY mt.Order_Number
Add a WHERE clause to the outer query if you need to filter for specific order numbers.
A: I think it's easiest to get a subquery in there. I think this should be self-explanitory, if not feel free to ask any questions.
CREATE TABLE #Parts
(
Order_Number int,
Completed char(1),
Part_Number int
)
CREATE TABLE #Master
(
Order_Number int
)
INSERT INTO #Parts
SELECT 1, 'Y', 64 UNION ALL
SELECT 2, 'N', 32 UNION ALL
SELECT 3, 'Y', 42 UNION ALL
SELECT 1, 'N', 32 UNION ALL
SELECT 1, 'N', 5
INSERT INTO #Master
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6
SELECT M.Order_Number, ISNULL(Totals.NonCompletedCount, 0) FROM #Master M
LEFT JOIN (SELECT P.Order_Number, COUNT(*) AS NonCompletedCount FROM #Parts P
WHERE P.Completed = 'N'
GROUP BY P.Order_Number) Totals ON Totals.Order_Number = M.Order_Number
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java regex from Perl-type regex I'm trying to extract hours, minutes, seconds, and nanoseconds from a string time stamp in a log file.Here is the input string I am testing with:
SOME_TEXT,+09:30:01.040910105,SOME_TEXT,SOME_TEXT,SOME_TEXT
In Perl/Python, I would use the following regex to group the fields I am interested in:
(\d\d)\:(\d\d)\:(\d\d)\.(\d{9})
You can verify that the regex works with the test string at http://regexpal.com if you're curious.
So I tried to write a simple Java program that can extract the fields:
import java.util.regex.*;
public class Driver
{
static public void main(String[] args)
{
String t = new String("SOME_TEXT,+09:30:01.040910105,SOME_TEXT,SOME_TEXT,SOME_TEXT");
Pattern regex = Pattern.compile("(\\d\\d):(\\d\\d):(\\d\\d)\\.(\\d{9})");
Matcher matches = regex.matcher(t);
for (int i=1; i<matches.groupCount(); ++i)
{
System.out.println(matches.group(i));
}
}
}
My regex did not translate correctly, however. The following exception shows that it did not find any matches:
Exception in thread "main" java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:485)
at Driver.main(Driver.java:12)
How would I properly translate the regex from Perl/Python style to Java?
A: The regex itself is fine. There are, however, two problems with the code:
*
*you need to call Matcher.find();
*you need to fix the for loop (it should use <= instead of <).
Here is the corrected version:
public class Driver
{
static public void main(String[] args)
{
String t = new String("SOME_TEXT,+09:30:01.040910105,SOME_TEXT,SOME_TEXT,SOME_TEXT");
Pattern regex = Pattern.compile("(\\d\\d):(\\d\\d):(\\d\\d)\\.(\\d{9})");
Matcher matcher = regex.matcher(t);
while (matcher.find()) {
for (int i=1; i<=matcher.groupCount(); ++i)
{
System.out.println(matcher.group(i));
}
}
}
}
This prints out:
09
30
01
040910105
A: Java breaks the perl-style, introducing complexity where it need not be. If you want to do regular expressions in Java the right way, take a look on MentaRegex. Below some examples:
The method matches returns a boolean saying whether we have a regex match or not.
matches("Sergio Oliveira Jr.", "/oliveira/i" ) => true
The method match returns an array with the groups matched. So it not only tells you whether you have a match or not but it also returns the groups matched in case you have a match.
match("aa11bb22", "/(\\d+)/g" ) => ["11", "22"]
The method sub allows you perform substitutions with regex.
sub("aa11bb22", "s/\\d+/00/g" ) => "aa00bb00"
Support global and case-insensitive regex.
match("aa11bb22", "/(\\d+)/" ) => ["11"]
match("aa11bb22", "/(\\d+)/g" ) => ["11", "22"]
matches("Sergio Oliveira Jr.", "/oliveira/" ) => false
matches("Sergio Oliveira Jr.", "/oliveira/i" ) => true
Allows you to change the escape character in case you don't like to see so many '\'.
match("aa11bb22", "/(\\d+)/g" ) => ["11", "22"]
match("aa11bb22", "/(#d+)/g", '#' ) => ["11", "22"]
A: By default java regexs match against the whole string, you have to add .* to the beginning and end:
Pattern regex = Pattern.compile(".*(\\d\\d):(\\d\\d):(\\d\\d)\\.(\\d{9}).*");
and that should work, with the other corrections to your for loop as necessary :-)
A: oh,no!
I copied your codes and wrapped with if (matches.find()) { ...} then worked. you need this.
and nanoseconds was missing. you should do this change:
for (int i = 1; i <= matches.groupCount(); ++i)
-------------------^
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Qt. get part of QString I want to get QString from another QString, when I know necessary indexes.
For example:
Main string: "This is a string".
I want to create new QString from first 5 symbols and get "This ".
input : first and last char number.
output : new QString.
How to create it ?
P.S. Not only first several letters, also from the middle of the line, for example from 5 till 8.
A: Use the left function:
QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "
Also have a look at mid() if you want more control.
A: If you do not need to modify the substring, then you can use QStringRef. The QStringRef class is a read only wrapper around an existing QString that references a substring within the existing string. This gives much better performance than creating a new QString object to contain the sub-string. E.g.
QString myString("This is a string");
QStringRef subString(&myString, 5, 2); // subString contains "is"
If you do need to modify the substring, then left(), mid() and right() will do what you need...
QString myString("This is a string");
QString subString = myString.mid(5,2); // subString contains "is"
subString.append("n't"); // subString contains "isn't"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
}
|
Q: Listbox Data Virtualization and Multi-select I have a listbox that can potentially have a large number of items with backing data. In order to handle data virtualization, I have tied into WPF's UI virtualization by writing a collection that implements the same interfaces as ObservableCollection and can spin up our backing data as needed.
This works fine. The problem comes when I introduce multi-select with the listbox. Because listbox manages selected items by object rather than index (SelectedItems), selecting all of the items causes all of the backing data to be spun up and held in memory by the listbox, defeating the data virtualization...
Is there a way to prevent this from happening other than re-writing ListBox to manage selection by index instead of object?
Thanks!
Eric
A: Why don't you use the Virtualizing option on the UI control? This will only load the data that is to be displayed on the screen.
http://www.kirupa.com/net/ui_virtualization_pg1.htm
A: We were using UI virtualization to control our data virtualization, but were having problems with listbox holding onto selection, so our data was not being unloaded.
What I ended up doing was tieing into the item generator for the virtualizing stack panel and listening to the data context changed event for the generated containers. When this happened, I either unloaded the real data from our wrapper.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: iOS app crashes on device with no crash info My app is crashing on the device after I repeat a certain sequence of actions a few times, generally it occurs after a memory level of one is triggered, and always occurs when one of the view is being loaded. This problem cannot be reproduced in the Simulator.
There are minor memory leaks upon each execution, but memory usage is quite low (as shown in Allocations and Leaks). I have stripped down the code, but the problem persists.
The issue is debugging the problem as there is no message in the console and no crash log.
Any suggestions?
A: Searching for memory leaks is discussed here - Memory leak detection tools in Xcode.
Memory leaks can be hard to find since they can cause unpredictable effects. Use the Leak tool in xcode and go through your code. It may be worth looking through the programming guide on memory management as you may be releasing something when you shouldn't be (or the other way around). The problem may not necessarily be where you think.
I think it's going to take you meticulously going through your code and checking everything, even if you think something is working the way it should be, just check to be sure - you may be surprised to find that it's not.
A: OpenGL can cause obscure crashes.
I had a retain cycle in my OpenGL code.
This happened in my custom UIView, where I had a GLKView subview. This subview could never be released, leading to a crash. Solution was to use weak instead of strong.
@property (strong, nonatomic) GLKView* glkView; // Crash, no crash report, no errors
@property (weak, nonatomic) GLKView* glkView; // this works
There was no errors in the log. No crash report. I have exceptions enabled to break on throw, but no exceptions were thrown. I had inserted NSLog's everywhere, but it didn't reveal anything useful. I had zombies enabled, but didn't notice anything unusual.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Flex: createPopUp -> Make everything modal except scrollbars I made this simple application to demonstrate my problem. It has:
*
*An image
*A button that launchess a popup window
*Scroll bars on the side
<mx:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
verticalScrollPolicy="on"
horizontalScrollPolicy="on"
layout="vertical">
<fx:Script>
<![CDATA[
import mx.managers.PopUpManager;
public function buttonClick():void {
PopUpManager.createPopUp(this,JakePanel,true);
}
]]>
</fx:Script>
<mx:Image width="2000"
source="@Embed(source='assets/image.jpg')"/>
<mx:Button click="{buttonClick()}" label="Launch"/>
</mx:Application>
When the launch button is pressed it launches this popup window:
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
layout="vertical"
width="400" height="300"
title="Popup"
>
<fx:Script>
<![CDATA[
import mx.managers.PopUpManager;
public function close():void {
PopUpManager.removePopUp(this);
}
]]>
</fx:Script>
<s:TextArea text="Enter more text here: " width="100%" height="200"/>
<s:Button label="OK" click="{close()}" width="100%" height="30" />
</mx:Panel>
These are my requirements
*
*When the popup is open I need to be able to disable everything except the popup. To do this I am using: PopUpManager.createPopUp(this,JakePanel,true);. The last parameter specifies that the popup is "modal" and that it should capture all mouse events.
*I also need to allow the main scroll bars to be enabled while the popup is open. Often my users will have the app open in a very small screen and will not be able to resize the app. For example:
This is a problem when the app is too small to click the ok button:
Is there a way to make everything "modal" except the main scroll bars? I know that I could put a scrollbar on the Panel but I would prefer to avoid this.
A: I think that the best way to do this is to:
*
*Wrap everything in the main application in a <mx:hgroup id="allYourStuff"> tag.
*When you add the Popup to the screen call: allYourStuff.enabled = false
*When you remove the Popup from the screen call: allYourStuff.enabled = true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: django filter depeding on character count of the item I have two models such that
class Employer(models.Model):
code = models.CharField(null=False,blank=False,default="")
class JobTitle(models.Model):
employer = models.ForeignKey(Employer,unique=False,null=False,default=0)
name = models.CharField(max_length=1000,null=False,default="")
and I would like to get all employers whose jobtitle name is less than X chracters.
How can I achive this in Django ?
Thanks
A: Use extra:
Emp.objects.extra(select={'name_length': 'LENGTH(`name`)'},
where=['name_length < 24'])
or raw:
Emp.objects.raw('SELECT * FROM myapp_emp WHERE LENGTH(`name`) < 24')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I add facebook and google plus share code to HTML5Boilerplate? HTML5Boilerplate has some conditional code for outputting the open < HTML > tag. I'm working on adding the xfbml and google plus sharing code on my site, but not sure where to add the required code to the < HTML > tag.
On Paul Irish's github I see this comment thread which says facebook only needs the code in the open < html > tag for IE browsers:
https://github.com/paulirish/html5-boilerplate/pull/395,
so I could just add that to the conditional IE statements in html5boilerplate.
However I'm not sure about the google plus code. At this page http://www.google.com/webmasters/+1/button/index.html it tells us to add this to the < HTML > tag:
<!-- Update your html tag to include the itemscope and itemtype attributes -->
<html itemscope itemtype="http://schema.org/">
I could use some guidance on how to include the < html > tag by default so I can append information to it for the social sharing tools.
Thanks,
Stacey
A: Don’t use XFBML. Use this instead: http://www.phpied.com/social-button-bffs/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to print toast every 10 seconds in Java? I want to print toast for every 10 seconds that is Toast.makeText(current location,latitude,longitude).
public class SimpleService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Toast.makeText(this, "current location, latitude,longitude", 0);
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}
}
public class SimpleServiceController extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start = (Button)findViewById(R.id.serviceButton);
Button stop = (Button)findViewById(R.id.cancelButton);
start.setOnClickListener(startListener);
stop.setOnClickListener(stopListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v){
startService(new Intent(SimpleServiceController.this,SimpleService.class));
}
};
private OnClickListener stopListener = new OnClickListener() {
public void onClick(View v){
stopService(new Intent(SimpleServiceController.this,SimpleService.class));
}
};
}
A: while(true){
try{
Thread.sleep(10000);
catch(Exception ex){}
Toast.makeText(this, "current location, latitude,longitude", 0).show();
}
Answered in the same vagueness as the question
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting an optimization report from GCC I would like to know if there is an option I can use with GCC to get a detailed report on the optimization actually chosen and performed by the compiler. This is possible with the Intel C compiler using the -opt-report. I do not want to look at the assembly file and figure out the optimization. I am specifically looking for the loop unrolling and loop tiling factors chosen by the compiler.
A: The reports from GCC is not that straight forward as like intel, but we can prefer. here is the detailed options use for optimization done by GCC.
-fopt-info
-fopt-info-options
-fopt-info-options=filename
Controls optimization dumps from various optimization passes. If the ‘-options’ form is used, options is a list of ‘-’ separated option keywords to select the dump details and optimizations.
The options can be divided into three groups:
options describing what kinds of messages should be emitted,
options describing the verbosity of the dump, and
options describing which optimizations should be included.
The options from each group can be freely mixed as they are non-overlapping. However, in case of any conflicts, the later options override the earlier options on the command line.
The following options control which kinds of messages should be emitted:
‘optimized’
Print information when an optimization is successfully applied. It is up to a pass to decide which information is relevant. For example, the vectorizer passes print the source location of loops which are successfully vectorized.
‘missed’
Print information about missed optimizations. Individual passes control which information to include in the output.
‘note’
Print verbose information about optimizations, such as certain transformations, more detailed messages about decisions etc.
‘all’
Print detailed optimization information. This includes ‘optimized’, ‘missed’, and ‘note’.
The following option controls the dump verbosity:
‘internals’
By default, only “high-level” messages are emitted. This option enables additional, more detailed, messages, which are likely to only be of interest to GCC developers.
One or more of the following option keywords can be used to describe a group of optimizations:
‘ipa’
Enable dumps from all interprocedural optimizations.
‘loop’
Enable dumps from all loop optimizations.
‘inline’
Enable dumps from all inlining optimizations.
‘omp’
Enable dumps from all OMP (Offloading and Multi Processing) optimizations.
‘vec’
Enable dumps from all vectorization optimizations.
‘optall’
Enable dumps from all optimizations. This is a superset of the optimization groups listed above.
If options is omitted, it defaults to ‘optimized-optall’, which means to dump messages about successful optimizations from all the passes, omitting messages that are treated as “internals”.
If the filename is provided, then the dumps from all the applicable optimizations are concatenated into the filename. Otherwise the dump is output onto stderr. Though multiple -fopt-info options are accepted, only one of them can include a filename. If other filenames are provided then all but the first such option are ignored.
Note that the output filename is overwritten in case of multiple translation units. If a combined output from multiple translation units is desired, stderr should be used instead.
In the following example, the optimization info is output to stderr:
gcc -O3 -fopt-info
This example:
gcc -O3 -fopt-info-missed=missed.all
outputs missed optimization report from all the passes into missed.all, and this one:
gcc -O2 -ftree-vectorize -fopt-info-vec-missed
prints information about missed optimization opportunities from vectorization passes on stderr. Note that -fopt-info-vec-missed is equivalent to -fopt-info-missed-vec. The order of the optimization group names and message types listed after -fopt-info does not matter.
As another example,
gcc -O3 -fopt-info-inline-optimized-missed=inline.txt
outputs information about missed optimizations as well as optimized locations from all the inlining passes into inline.txt.
Finally, consider:
gcc -fopt-info-vec-missed=vec.miss -fopt-info-loop-optimized=loop.opt
Here the two output filenames vec.miss and loop.opt are in conflict since only one output file is allowed. In this case, only the first option takes effect and the subsequent options are ignored. Thus only vec.miss is produced which contains dumps from the vectorizer about missed opportunities.
A: Although it's not a report in the sense of aggregated information, you might try the -fdump-ipa-all option which makes gcc produce dump files which at least keep you from having to analyse assembler code on what happened.
Regarding loop optimization the -fdump-rtl-loop2 option might be of interest.
For details on all this please see the section Options for Debugging Your Program or GCC of the manual.
A: You may also consider fsave-optimization-record option
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
}
|
Q: Why Rails doesn't include the Javascript files at the bottom of the HTML page by default? I read here that it is better to include Javascript files at the bottom of the HTML page.
Why Ruby on Rails doesn't do so by default ?
A: I would guess that Rails includes your application.js in the <head> by default because it assumes you'll be minimizing things via the asset pipeline. There's no need to worry about where your script is included if it's a single external file being loaded in parallel by a single HTTP request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: SQL Auto-Increment in Oracle APEX occasionally skips a chunk of numbers when incrementing? I have created a table in APEX that has a PK that is incremented by a SQL sequence:
CREATE SEQUENCE seq_increment
MINVALUE 1
START WITH 880
INCREMENT BY 1
CACHE 10
This seems to work perfectly. The issue is that sometimes, usually when I get on in the morning and run a process to enter a new row, it skips a bunch of numbers. I only care because these numbers are being used as the ID# of documents in my company and losing/skipping blocks of numbers is not going to be acceptable when this tool goes live.
It does seem to jump to the next '10' number. i.e. yesterday my last test assigned 883 and this morning it assigned 890 as the next number. Looking at my code for creation of the sequence I notice that I have set it up to cache 10 values so that it will process quicker. Is it possible that this cache is getting dumped over night and that it is pulling 890 because it had 880-889 in cache and it was dumped?
Are there other potential causes and solutions?
A: Sequences will not and can not generate gap-free values. So you'd expect that numbers will occasionally be skipped. That's perfectly normal when you're using sequences.
As you've surmised, the most likely scenario is that the sequence cache is aging out of the shared pool overnight when the APEX application isn't being used. You can reduce the frequency of gaps by declaring your sequence NOCACHE but that will decrease performance and it will not eliminate gaps it will just make them less frequent.
A: Oracle sequences are never guaranteed to be contiguous. If you need an absolutely contiguous set of values, you'll need to implement a custom solution.
Odds are that CACHE 10 is why you're losing numbers in this case. The cache value is how many sequence values are stored in memory for future use. Rebooting will clear the cache and cause 10 new values to be retrieved. Similarly, if the sequence is not used for long enough, the current set of values may be flushed out of the shared pool, also causing a new set of values to be retrieved.
This is clearly not the case in your instance, but sequence numbers can also be lost due to rollbacks. A rolled back transaction involving one or more sequences discards the sequence value(s).
A: Some sequence numbers have been aged out of one of the in-memory structures (shared pool I think?). This is expected behaviour for sequences. The only guarantee that you have is that they are unique. If you need to present gap-free sequences you'll have to do this at reporting time using e.g. rownum pseudo-column. It is made this way deliberately otherwise you would have to serialise all inserts i.e. lock table. And even that wouldn't work properly if an insert was rolled back!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Interested in learning struts 1.x I am working on a struts project which I am new to. I have the background in jsp, servlets and understanding of j2ee.
Is there any good sample struts sample project I can download and learn?
A: Forget learning from samples. I've seen Struts samples ranging from incomplete to complete, from very bad to very good. If you are new to Struts, chances are you will end up learning lots of bad practices that you will introduce in the project later to see that you did it wrong.
My suggestion would be to learn from a book. One that I personally liked was Jakarta-Struts Live:
It's relatively small (~270 pages, as opposed to your average IT book at ~700) and introduces you to most of the components you will use in day to day. Explanations are good and to the point.
Check it out if you can. If I'm not mistaken, it's freely available online.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Send intent for screen on from shell How can send intent in the console for start the screen on ?
I know the action for turning the screen on it is Intent.ACTION_SCREEN_ON, but I have hard time sending the intent from console.
A: I found the solution
adb shell am broadcast -a android.intent.action.SCREEN_ON
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Does require in PHP slow the site down? What I mean is whether writing something code in a file and then writing a require to it somewhere else is slower than writing the code in the file itself? (What about a require to a file that only has a require?)
A: Yes, it's slower, but not by any magnitude of which you should care unless you encounter problems. This is called premature optimization. It's bad. Instead, spend your time making a great app and use all the tools at your disposition. If one day it runs a bit slow, you can start looking for the bottleneck and speed it up, but until then, don't worry about it.
A: It will take time to stream the file in, but its very trivial.
A: Its negligible. But it doesn't slow down the code to a reasonable amount. Unless you're using require_once which can significantly slow down a large scale app
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to upload mp3 file using Facebook Graph API [PHP SDK] I am using PHP SDK to upload/publish mp3 file on facebook page. I have a wordpress blog and using cron jobs to schedule post. Cron job has no issue and everything seems to be working great except uploading these mp3 files.
I want to publish these mp3 files with those posts on my facebook page.
Currently i am using the following code. Please suggest where am i going wrong while attaching mp3 files.
I have already tried removing "media" from attachment parameter.
$args = array(
'access_token' => $post_access_token,
'uid' => $fb_page_id,
'message' => $post->post_title,
'name' => $post->post_title,
'caption' => get_bloginfo('name'),
'link' => get_permalink($post_id),
'picture' => urldecode(get_post_meta($post_id, 'image_value', true)),
'description' => $this->auto_make_excerpt($post->post_content),
'attachment' => json_encode(array(
"media" =>
array(
'type' => 'mp3',
"src" => urlencode("http://www.looptvandfilm.com/blog/Radiohead%20-%20In%20Rainbows/01%20-%20Radiohead%20-%2015%20Step.MP3"),
"title" => "15 Step",
"artist" => "Radiohead",
"album" => "In Rainbows"
)
)),
'actions' => json_encode(array(
array(
'name' => 'Share',
'link' => 'http://www.facebook.com/sharer.php?u='.urlencode(get_permalink($post_id)).'&t='.$post->post_title
)
))
);$responseId = $this->facebook->api('/'.$fb_page_id.'/feed', 'POST', $args);
A: "src" => urlencode("http://www.looptvandfilm.com/blog/Radiohead%20-%20In%20Rainbows/01%20-%20Radiohead%20-%2015%20Step.MP3"),
the url is already encoded. Again you try to encode the url ... can you change that and try again?
Try the following code to post File in FB
$attachment = array('type' => 'mp3',
"src" => "http://www.looptvandfilm.com/blog/Radiohead%20-%20In%20Rainbows/01%20-%20Radiohead%20-%2015%20Step.MP3",
"title" => "15 Step",
"artist" => "Radiohead",
"album" => "In Rainbows"
$result = $facebook->api('/'. $fb_id . '/feed/',
'post',
$attachment);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sql Server - Selecting Logical Results in a Query Suppose I have a table: ACCOUNT
It has columns: ID, NAME, BALANCE
I want to determine if the SUM of balances of people who has balance more than $ 2,000 is greater than $ 50,000. It means I want to select a logical value. Because I don't want to get specific sum, I only need comparison result. I want to be able to write something like:
SELECT SUM(BALANCE) > 50000
FROM ACCOUNT
WHERE BALANCE > 2000
Sql Server says it is syntax error. So I have to do:
SELECT SUM(BALANCE)
FROM ACCOUNT
WHERE BALANCE > 2000
Then compare the result to 50000. But taking sum of all the items after reaching 50000 is redundant since I only compare it to 50000.
So how can I write this query in a way to stop after reaching comparison value and give me the logical result?
A: You don't.
How does SQL Server know you have only positive values? If you have 10 values, and the 8th one gets you over 50,000, but 9 and 10 are both -10,000, wouldn't that be an issue?
A: Look at the HAVING keyword.
SELECT sum(balance)
FROM account
WHERE balance > 2000
HAVING sum(balance) > 50000
Edit: This likely doesn't shortcut like the original question asked. It might if the the SQL Server query engine realized the where/having clauses can be shortcut (as Martin Smith said in a comment). I would think writing your own shortcut-er would be overly complicated, and if you're hitting performance issues there would likely be better approaches.
If you need a true/false answer via a query, then Jim Dagg's answer looks good to me.
A: This question was asked in 2011. In versions prior to 2012 there isn't really a clean way of doing this and getting SQL Server to short circuit the scan as soon as the total is reached.
You could use a recursive CTE to add up the balances instead. The exit condition for this could be once the balance running total exceeds 50,000. Dependant on table cardinality and indexes this could be either more or less efficient.
You could also have a custom CLR aggregate that terminated processing by throwing an error if 50,000 was reached but quite a horrible solution!
For versions since 2012 see my answer here
A: You can't stop the query unless you create a procedure with a cursor, which will stop fetching after reaching 50000 (don't know if it's worthing, but it's the only way, maybe you have millions of rows):
DECLARE @bal int
DECLARE @bal_tot int
DECLARE cur CURSOR FOR
SELECT sum(balance)
FROM account
WHERE balance > 2000
ORDER BY balance DESC;
OPEN cur;
FETCH NEXT FROM cur
INTO @bal
WHILE @@FETCH_STATUS = 0 AND @bal_tot < 50000
BEGIN
@bal_tot = @bal_tot + @bal
END
CLOSE cur;
if @bal_tot > 50000 etc...
A: I wouldn't go the route of trying to write a complicated procedure to short-circuit the query. -- that's overengineering the problem. Honestly, just pulling the sum and doing the comparison the way you're doing now is the most straightforward method.
If you want to select the result of the comparison for use in other SQL processing, you could try this:
SELECT CASE WHEN
(SELECT SUM(AmtCurrent)
FROM [SisMaster].[dbo].[Loan]
WHERE AmtCurrent > 2000) > 50000
THEN 1
ELSE 0
END
A: SELECT CASE WHEN TotalAmtCurrent > 50000 THEN 1 ELSE 0 END
FROM
(SELECT SUM(AmtCurrent) as TotalAmtCurrent
FROM [SisMaster].[dbo].[Loan]
WHERE AmtCurrent > 2000) a
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: VBA How to solve two equations with two unknowns I am trying to calculate point on a line.
I got the points of the edges and one distance between one edge to the point I want to find (which is B).
A(2,4)
B(x,y)
C(4,32)
The distance between A to B is 5.
How can I calculate Bx and By? using the following equations:
d = Math.Sqr((Bx-Ax)^2 + (By-Ay)^2)
d = Math.Sqr((Cx-Bx)^2 + (Cy-By)^2)
and than compare the equations above.
Here is the equations with the points placed:
5 = Math.Sqr((Bx-2)^2 + (By-4)^2)
23.0713366 = Math.Sqr((4-Bx)^2 + (32-By)^2)
or
Math.Sqr((Bx-2)^2 + (By-4)^2) - 5 = Math.Sqr((4-Bx)^2 + (32-By)^2) - 23.0713377
How can I solve this using VBA?
Thank you!
A: I won't solve your equations above because they are an unnecessarily complex way to state the problem (and the existence of a solution is questionable in the presence of rounding), but all the points on the line A=(Ax,Ay) to C=(Cx,Cy) can be described as B=(Ax,Ay) + t*(Cx-Ax,Cy-Ay) with t between 0 and 1.
The distance between B and A is then given by d=t*Sqrt((Cx-Ax)^2+(Cy-Ay)^2), which you can invert to get the proper t for a given d - t=d/Sqrt((Cx-Ax)^2+(Cy-Ay)^2)
In your case, B(t) = (2,4) + t*(2,28), t=5/Sqrt(2^2+28^2) ~ 0.178 -> B ~ (2,4) + 0.178 * (2,28) ~ (2.356, 8.987).
A: VBA has no Symbolic Language capability. To solve this problem, there are different approach :
*
*Transform the equations to isolate one of the unknowns, most likely to use substitution, and compute it (I recommend this for your problem.)
*Transform your functions and derive them to use Newton's methods (don't do this, it's overkill.)
*Use a "brute force" convergence methods : Fix a min/max for each variable and use bisection methods to find what you want (I don't recommend this because you'll most likely "fall" into a local minimum/maximum in your case.)
So basically, I'd say you go with the first way. It requires 15mins of tinkering with mathematical equations, then you're set to go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Delayed_job - job failing - need error message I am using delayed_job to run background processes. It works fine but then suddenly fails a job for no apparent reason (the job suddenly disappears from the jobs queue). There is nothing printed in the delayed_job log other than failure. Is there a way to get better logging or at least print out an error message?
s
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# WinForms Process Encoding problem I am writing a windows forms application in C#
I have a Process Object which runs a cmd command and returns it's output.
Process Pro = new Process();
Pro.StartInfo.FileName = "cmd.exe";
Pro.StartInfo.Arguments = "<Dos Command here>";
Pro.StartInfo.CreateNoWindow = true;
Pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Pro.StartInfo.RedirectStandardOutput = true;
Pro.StartInfo.UseShellExecute = false;
Pro.Start();
Which works fine! However if the output of the command is not ASCII(in my case Greek), the Output are random symbols. Surely an encoding problem.
If i run the same code on a console application everything runs smoothly.
I tried reading the Base stream as UTF-8, but no luck!
System.IO.StreamReader Rdr = new System.IO.StreamReader(Pro.StandardOutput.BaseStream, Encoding.UTF8);
Is there any way to read the output properly in a winform application?
Thnx!
A: The real solution is base on this:
unicode-characters-in-windows-command-line-how
check here:
Wiki code page
for the code page you need.
you can also do an ugly hack, writing the command to a batch file (f.e foo.bat)
then running it as foo.bat > log.txt
then you can read the output from log.txt.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SOLR: Is it it possible to index multiple timestamp:value pairs per document? Is it possible in solr to index key-value pairs for a single document, like:
Document ID: 100
2011-05-01,20
2011-08-23,200
2011-08-30,1000
Document ID: 200
2011-04-23,10
2011-04-24,100
and then querying for documents with a specific value aggregation in a specific time range, i.e. "give me documents with sum(value) > 0 between 2011-08-01 and 2011-09-01" would return the document with id 100 in the example data above.
A: Here is a post from the Solr User Mailing List where a couple of approaches for dealing with fields as key/value pairs are discussed.
1) encode the "id" and the "label" in the field value; facet on it;
require clients to know how to decode. This works really well for simple
things where the the id=>label mappings don't ever change, and are
easy to encode (ie "01234:Chris Hostetter"). This is a horrible approach
when id=>label mappings do change with any frequency.
2) have a seperate type of "metadata" document, one per "thing" that you
are faceting on containing fields for id and the label (and probably a
doc_type field so you can tell it apart from your main docs) then once
you've done your main query and gotten the results back facetied on id,
you can query for those ids to get the corrisponding labels. this works
realy well if the labels ever change (just reindex the corrisponding
metadata document) and has the added bonus that you can store additional
metadata in each of those docs, and in many use cases for presenting an
initial "browse" interface, you can sometimes get away with a cheap
search for all metadata docs (or all metadata docs meeting a certain
criteria) instead of an expensive facet query across all of your main
documents.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I use most of my code in an ASP.NET MVC3 app? I wrote a simple WPF Application as an example:
Model:
public class User
{
public String FirstName { get; set; }
public String LastName { get; set; }
}
ViewModel:
//ViewModelBase contains base code for INotifyPropertyChanged
public class UserViewModel : ViewModelBase
{
public UserViewModel(User user)
{
_user = user ?? new User();
}
private User _user;
public String FirstName
{
get { return _user.FirstName; }
set
{
if (_user.FirstName != value)
{
_user.FirstName = value;
RaisePropertyChanged("FirstName", "Full Name");
}
}
}
public String LastName
{
get { return _user.LastName; }
set
{
if (_user.LastName!= value)
{
_user.LastName= value;
RaisePropertyChanged("LastName", "Full Name");
}
}
}
public String FullName
{
get { return String.Format("{0}, {1}", LastName, FirstName); }
}
}
Can I reuse my code in an MVC3 app? I figure the INotifyPropertyChanged stuff won't work, but can't I still reuse the ViewModel somehow?
A: No, not really. ViewModels and Controllers are governed by completely different design patterns.
Where MVVM and MVC shine is that they help break out business logic from your codebehind. You quite possibly can share your support code (code that you call from your VMs and Controllers but that isn't touched by any platform-centric designs) and models (depending on how they are coded).
I'm currently working on an app that combines an MVC website and a WPF application, and I do share models between them, and as much code as I can squeeze from my VMs and Controllers. But there is too much different between the two to use your VMs as Controllers and vice versa.
A: Your 'firstname' and 'lastname' method would just move into the model, as they aren't too much more than slightly more fancy getters and setters.
You're FullName method I'd be tempted to put in the controller as it's dealing with formatting but it does kind of have a basic and testable logic behind it.
As you say, I'm not sure you could use the NotifyProperty gubbins, but the methods in general should port over happily.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google App Engine JDO Query using Alternate logic for 'NOT IN' I'm developing a Google App Engine Java app where users can search business objects from database based on search criteria.
The search results (a list of records) should not include any of the records (certain number of records, say 100) from their past searches. I'm storing the past results in the User Profile for this reason.
Any suggestions on efficiently implementing this logic (without using multiple collection iterations). I'm using JDO and there are restrictions in using 'NOT IN' condition in the queries.
A: Here's a solution, assuming your goal is to get 200 keys that are not in the history already.
I will attempt to estimate the number of operations used as a proxy for "efficiency", since this is how we will be charged in the new pricing model
*
*Fetch the User object and "history keys" (1 read operation)
*Do a keys only query and fetch 300 records. (300 small operations)
*In your code, subtract any of the history keys from the 300 records. (0 operations)
*If you end up with less than 200 records after step 3, fetch another 100.(repeat if necessary) (100 small operations).
*Once you have 200 keys not seen before, you can fetch the full business object entities if you need them, or display the keys to the user. (200 read operations if you fetch the entire objects)
If the datastore supported a native "NOT IN" operator, then we could shave off 100 small operations from step 2, and skip step 4. The largest cost here will be fetching the actual 200 entities, which would have to happen with or without the NOT IN operator. Ultimately, this method is not that inefficient compared to what a native NOT IN operator would do.
Further optimizations:
*
*If you don't need to display 200 keys all at once, then you can use cursors to only get N results at a time.
*I am simply guessing when I suggest that you get 300 keys at first. You may need to get more or less. You can also probably get less than 100 on the second attempt.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Separated login config for JBoss? I'm trying to create an RPM-packaged Ear file that should be installable together with other RPM-packagesd Ear files in a JBoss container. (I could probably create a separate container within JBoss, but that's a lot of overhead for one Ear.) This works fine, except for one issue.
My problem is that this Ear file expose web services that use their own authentication policy (login-config.xml policy/application-policy/authentication/login-module). Now that multiple RPMs want to supply authentication information through this file, we get into conflict with the RPM spec rule that no file can be owned by more than one RPM package (and anyway whichever RPM goes last would clobber the previous).
Is there any way that the application-policy/authentication block can be declared in a separate file or in some manner that places it outside login-config.xml? For example, is it possible to declare additional security mbeans (in separate files) that refer to a separate login XML definition?
This is JBoss v4.2, but I would be willing to consider later if it solved this issue.
Update:
Lukasz rules. Below is working config!
<?xml version='1.0'?>
<server>
<mbean code="org.jboss.security.auth.login.DynamicLoginConfig"
name="jboss.security.tests:service=LoginConfig">
<depends optional-attribute-name="SecurityManagerService">
jboss.security:service=JaasSecurityManager
</depends>
<depends optional-attribute-name="LoginConfigService">
jboss.security:service=XMLLoginConfig
</depends>
<attribute name="PolicyConfig" serialDataType="jbxb">
<jaas:policy
xsi:schemaLocation="urn:jboss:security-config:4.1 resource:security-config_4_1.xsd"
xmlns:jaas="urn:jboss:security-config:4.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<jaas:application-policy name="mySecurityDomain">
<jaas:authentication>
<jaas:login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required">
<jaas:module-option name="unauthenticatedIdentity">noone</jaas:module-option>
<jaas:module-option name="dsJndiName">java:/myDataSource</jaas:module-option>
<jaas:module-option name="principalsQuery">SELECT password FROM WebServiceUser WHERE userName=?</jaas:module-option>
<jaas:module-option name="rolesQuery">SELECT role, 'Roles' FROM WebServiceUser WHERE userName=?</jaas:module-option>
</jaas:login-module>
</jaas:authentication>
</jaas:application-policy>
</jaas:policy>
</attribute>
</mbean>
</server>
A: You can try and setup login module using DynamicLoginConfig service. I never use it but it looks like something that can help you. It allows you to create login module configuration
in different file and deploy it during application installation.
Here you can find more info about it:
*
*Dynamic configuration of JAAS login
*AS5: Specifying Security Domain Configuration
*Configuration DynamicLoginConfig
*10.5.2. The DynamicLoginConfig service
*using DynamicLoginConfig
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: automatically print stack trace on any uncaught exception How can I automatically print the stack trace to stdout on any uncaught exceptions ?
I am using
pipe = subprocess.Popen(cmd, shell=False, cwd=cwd, env=env,stdout=open(pth,'w'),stderr=open(pth,'w'))
On uncaught Exception, the file will only contain
Unhandled Exception:
but I'd like in addition the trace to be written to my logfile.
Moreover I'd like the original trace if the exception had been reraised
Thanks
A: In the child process initialize the logging module and assign sys.stdout = LoggerFile(). Then any exception not handled within the child process will be written to your log file instead of to standard out. If you want it to be written to both, enhance the LoggerFile class.
Please note that because the child process is a completely separate interpreter, with its own separate execution stack, exceptions occurring within the child process cannot be propagated back to the parent process. But you could send encoded messages to simulate that.
from functools import partial
from itertools import imap
def text_coerce(encoding):
u"given encoding returns function that takes bytes or characters and returns characters"
def decode(data):
u"if given characters returns them; if given bytes decodes them"
if isinstance(data, StringType): # really bytes
return data.decode(encoding)
else: return data
return decode
def consume(iterable):
u"consume all values from an iterable in a loop"
while True:
try:
iterable.next()
except StopIteration:
break
class LoggerFile(object):
u"a non-seekable character-based file-like object that logs all data written to it"
def __init__(self, logger=None, level=logging.INFO, encoding='UTF-8'):
if logger is None: logger = logging.getLogger()
self._encoder = text_coerce(encoding)
self._log = partial(logger.log, level)
self.writelines = partial(map, self.write)
self.close = lambda: None # pretends to close
self.flush = lambda: None # pretends to flush
self.mode = 'w'
def write(self, message):
u"write() results in exactly one log message; same for the print statement when replacing stdout"
message = self._encoder(message).rstrip()
if message != u'': self._log(message)
def writelines(self, message):
consume(imap(self.write, message.split(u'\n')))
A: Thanks a lot to all.
Wberry's solution works but is not necessary. It works fine using just
f = open(pth,'w');
pipe = subprocess.Popen(cmd,shell=False,cwd=cwd,env=env,stdout=f,stderr=f)
My problem came from redifining excepthook somewhere else (so that it enables Eclipse's breakpoint). I fixed it (switching to original sys.excepthook() when needed).
@patrys: I open it once. It was a misleading one-line shortcut. Apologies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Inclusion of header files in case of templates. When we make a class we declare its functions in a header files and define them in a source file... then the header file can be included in the main file to use the class...
But if we declare a template class in header files and define it in the .cpp file and then if we include the header file in the main(containing int main) file then why does a linker error crop up... and the error does not crop up if we included the .cpp file(containing the header file ) in the main file... any answers plz?
A: Templates don't actually produce any object code at the point where the compiler reads their source code; they're (typically) only "instantiated" when something actually uses the template. So if you define a template function in one source file, and call it from another, the code for the template function doesn't get compiled at all: it's not in the first object file since nothing there needed it, and it's not in the second object file since the compiler didn't have access to the function's definition.
You define template functions in header files so that in each translation unit where something calls the template function, the compiler has access to its code and can compile a copy of it specialized with the appropriate template arguments.
Alternatively, you can use explicit instantiation: you define the template function in a .cpp file, and also tell the compiler exactly which types that it should compile the function for. This is harder to maintain, because you have to keep track of which instantiations are needed by the rest of the program. If something calls foo<float>(), but you've only explicitly instantiated foo<int>() and foo<char>(), you get a missing-symbol error.
You shouldn't #include a .cpp file from another .cpp file. Just put the template function definitions in the header together with their declarations.
A: A template is neither a class nor a function. Its a pattern that compiler uses to generate classes or functions.
Very nicely explained in HERE
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hide and remove class on blur See this:
http://jsfiddle.net/AFhvS/4/
Try remove the text inside the input field in one of the two filled fields: http://jsfiddle.net/AFhvS/5/ and then go on blur, it should appear a alert, but it doesnt, so i have done something wrong?
A: you may add the class you want to remove
$('.upstartRemoveClass').removeClass("upstartRemoveClass");
You may also want to look into when you tab between items, at the moment you are using the click event on the tr, maybe you want to use the focus event on your inputs instead?
edit: http://jsfiddle.net/AFhvS/7/ changed events on when things should trigger.
A: This might work for you, or at least lead you in the right direction:
$('tr').removeClass('upstartRemoveClass');
or in your blur function:
$(this).removeClass('upstartRemoveClass');
A: You've put the onBlur handler on the tr instead of on the input. That's why it's not firing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accessing JPEG EXIF rotation data in JavaScript on the client side I'd like to rotate photos based on their original rotation, as set by the camera in JPEG EXIF image data. The trick is that all this should happen in the browser, using JavaScript and <canvas>.
How could JavaScript access JPEG, a local file API object, local <img> or remote <img>, EXIF data to read the rotation information?
Server-side answers are not OK; I am looking for a client-side solution.
A: I upload expansion code to show photo by android camera on html as normal on some img tag with right rotaion, especially for img tag whose width is wider than height. I know this code is ugly but you don't need to install any other packages. (I used above code to obtain exif rotation value, Thank you.)
function getOrientation(file, callback) {
var reader = new FileReader();
reader.onload = function(e) {
var view = new DataView(e.target.result);
if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
var length = view.byteLength, offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112)
return callback(view.getUint16(offset + (i * 12) + 8, little));
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
return callback(-1);
};
reader.readAsArrayBuffer(file);
}
var isChanged = false;
function rotate(elem, orientation) {
if (isIPhone()) return;
var degree = 0;
switch (orientation) {
case 1:
degree = 0;
break;
case 2:
degree = 0;
break;
case 3:
degree = 180;
break;
case 4:
degree = 180;
break;
case 5:
degree = 90;
break;
case 6:
degree = 90;
break;
case 7:
degree = 270;
break;
case 8:
degree = 270;
break;
}
$(elem).css('transform', 'rotate('+ degree +'deg)')
if(degree == 90 || degree == 270) {
if (!isChanged) {
changeWidthAndHeight(elem)
isChanged = true
}
} else if ($(elem).css('height') > $(elem).css('width')) {
if (!isChanged) {
changeWidthAndHeightWithOutMargin(elem)
isChanged = true
} else if(degree == 180 || degree == 0) {
changeWidthAndHeightWithOutMargin(elem)
if (!isChanged)
isChanged = true
else
isChanged = false
}
}
}
function changeWidthAndHeight(elem){
var e = $(elem)
var width = e.css('width')
var height = e.css('height')
e.css('width', height)
e.css('height', width)
e.css('margin-top', ((getPxInt(height) - getPxInt(width))/2).toString() + 'px')
e.css('margin-left', ((getPxInt(width) - getPxInt(height))/2).toString() + 'px')
}
function changeWidthAndHeightWithOutMargin(elem){
var e = $(elem)
var width = e.css('width')
var height = e.css('height')
e.css('width', height)
e.css('height', width)
e.css('margin-top', '0')
e.css('margin-left', '0')
}
function getPxInt(pxValue) {
return parseInt(pxValue.trim("px"))
}
function isIPhone(){
return (
(navigator.platform.indexOf("iPhone") != -1) ||
(navigator.platform.indexOf("iPod") != -1)
);
}
and then use such as
$("#banner-img").change(function () {
var reader = new FileReader();
getOrientation(this.files[0], function(orientation) {
rotate($('#banner-img-preview'), orientation, 1)
});
reader.onload = function (e) {
$('#banner-img-preview').attr('src', e.target.result)
$('#banner-img-preview').css('display', 'inherit')
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
});
A: If you want it cross-browser, your best bet is to do it on the server. You could have an API that takes a file URL and returns you the EXIF data; PHP has a module for that.
This could be done using Ajax so it would be seamless to the user. If you don't care about cross-browser compatibility, and can rely on HTML5 file functionality, look into the library JsJPEGmeta that will allow you to get that data in native JavaScript.
A: Improving / Adding more functionality to Ali's answer from earlier, I created a util method in Typescript that suited my needs for this issue. This version returns rotation in degrees that you might also need for your project.
ImageUtils.ts
/**
* Based on StackOverflow answer: https://stackoverflow.com/a/32490603
*
* @param imageFile The image file to inspect
* @param onRotationFound callback when the rotation is discovered. Will return 0 if if it fails, otherwise 0, 90, 180, or 270
*/
export function getOrientation(imageFile: File, onRotationFound: (rotationInDegrees: number) => void) {
const reader = new FileReader();
reader.onload = (event: ProgressEvent) => {
if (!event.target) {
return;
}
const innerFile = event.target as FileReader;
const view = new DataView(innerFile.result as ArrayBuffer);
if (view.getUint16(0, false) !== 0xffd8) {
return onRotationFound(convertRotationToDegrees(-2));
}
const length = view.byteLength;
let offset = 2;
while (offset < length) {
if (view.getUint16(offset + 2, false) <= 8) {
return onRotationFound(convertRotationToDegrees(-1));
}
const marker = view.getUint16(offset, false);
offset += 2;
if (marker === 0xffe1) {
if (view.getUint32((offset += 2), false) !== 0x45786966) {
return onRotationFound(convertRotationToDegrees(-1));
}
const little = view.getUint16((offset += 6), false) === 0x4949;
offset += view.getUint32(offset + 4, little);
const tags = view.getUint16(offset, little);
offset += 2;
for (let i = 0; i < tags; i++) {
if (view.getUint16(offset + i * 12, little) === 0x0112) {
return onRotationFound(convertRotationToDegrees(view.getUint16(offset + i * 12 + 8, little)));
}
}
// tslint:disable-next-line:no-bitwise
} else if ((marker & 0xff00) !== 0xff00) {
break;
} else {
offset += view.getUint16(offset, false);
}
}
return onRotationFound(convertRotationToDegrees(-1));
};
reader.readAsArrayBuffer(imageFile);
}
/**
* Based off snippet here: https://github.com/mosch/react-avatar-editor/issues/123#issuecomment-354896008
* @param rotation converts the int into a degrees rotation.
*/
function convertRotationToDegrees(rotation: number): number {
let rotationInDegrees = 0;
switch (rotation) {
case 8:
rotationInDegrees = 270;
break;
case 6:
rotationInDegrees = 90;
break;
case 3:
rotationInDegrees = 180;
break;
default:
rotationInDegrees = 0;
}
return rotationInDegrees;
}
Usage:
import { getOrientation } from './ImageUtils';
...
onDrop = (pics: any) => {
getOrientation(pics[0], rotationInDegrees => {
this.setState({ image: pics[0], rotate: rotationInDegrees });
});
};
A: Check out a module I've written (you can use it in browser) which converts exif orientation to CSS transform: https://github.com/Sobesednik/exif2css
There is also this node program to generate JPEG fixtures with all orientations: https://github.com/Sobesednik/generate-exif-fixtures
A: If you only want the orientation tag and nothing else and don't like to include another huge javascript library I wrote a little code that extracts the orientation tag as fast as possible (It uses DataView and readAsArrayBuffer which are available in IE10+, but you can write your own data reader for older browsers):
function getOrientation(file, callback) {
var reader = new FileReader();
reader.onload = function(e) {
var view = new DataView(e.target.result);
if (view.getUint16(0, false) != 0xFFD8)
{
return callback(-2);
}
var length = view.byteLength, offset = 2;
while (offset < length)
{
if (view.getUint16(offset+2, false) <= 8) return callback(-1);
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1)
{
if (view.getUint32(offset += 2, false) != 0x45786966)
{
return callback(-1);
}
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
{
if (view.getUint16(offset + (i * 12), little) == 0x0112)
{
return callback(view.getUint16(offset + (i * 12) + 8, little));
}
}
}
else if ((marker & 0xFF00) != 0xFF00)
{
break;
}
else
{
offset += view.getUint16(offset, false);
}
}
return callback(-1);
};
reader.readAsArrayBuffer(file);
}
// usage:
var input = document.getElementById('input');
input.onchange = function(e) {
getOrientation(input.files[0], function(orientation) {
alert('orientation: ' + orientation);
});
}
<input id='input' type='file' />
values:
-2: not jpeg
-1: not defined
For those using Typescript, you can use the following code:
export const getOrientation = (file: File, callback: Function) => {
var reader = new FileReader();
reader.onload = (event: ProgressEvent) => {
if (! event.target) {
return;
}
const file = event.target as FileReader;
const view = new DataView(file.result as ArrayBuffer);
if (view.getUint16(0, false) != 0xFFD8) {
return callback(-2);
}
const length = view.byteLength
let offset = 2;
while (offset < length)
{
if (view.getUint16(offset+2, false) <= 8) return callback(-1);
let marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) {
return callback(-1);
}
let little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
let tags = view.getUint16(offset, little);
offset += 2;
for (let i = 0; i < tags; i++) {
if (view.getUint16(offset + (i * 12), little) == 0x0112) {
return callback(view.getUint16(offset + (i * 12) + 8, little));
}
}
} else if ((marker & 0xFF00) != 0xFF00) {
break;
}
else {
offset += view.getUint16(offset, false);
}
}
return callback(-1);
};
reader.readAsArrayBuffer(file);
}
A: You can use the exif-js library in combination with the HTML5 File API: http://jsfiddle.net/xQnMd/1/.
$("input").change(function() {
var file = this.files[0]; // file
fr = new FileReader; // to read file contents
fr.onloadend = function() {
// get EXIF data
var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));
// alert a value
alert(exif.Make);
};
fr.readAsBinaryString(file); // read the file
});
A: Firefox 26 supports image-orientation: from-image: images are displayed portrait or landscape, depending on EXIF data. (See sethfowler.org/blog/2013/09/13/new-in-firefox-26-css-image-orientation.)
There is also a bug to implement this in Chrome.
Beware that this property is only supported by Firefox and is likely to be deprecated.
A: https://github.com/blueimp/JavaScript-Load-Image is a modern javascript library that can not only extract the exif orientation flag - it can also correctly mirror/rotate JPEG images on the client side.
I just solved the same problem with this library: JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "139"
}
|
Q: Using C dynamic memory functions in C++ to avoid Segmentation Fault I'm trying to safely recover from a segmentation fault I expect to happen. I'm trying to avoid it checking using my canAlloc() function here. When canAllow returns false, A0 (which is Ackermann's if you didn't see it) should throw an exception that I can catch in the main method. checkTable and saveInTable are both functions that use a map<int hash, int value> to store returns from A0.
bool canAlloc(){
bool reBool = false;
int * memch = (int*)calloc (10000, sizeof(int));
reBool = (memch != NULL);
free(memch);
return reBool;
}
int A0(int m, int n){
if(!canAlloc()) throw;
int reInt = checkReturnTable(m,n);
if(reInt == -1){
if(m == 0){
return n + 1;
} else if(m > 0){
if(n == 0){
reInt = A0(m-1,1);
} else if(n > 0){
reInt = A0(m-1, A0(m,n-1));
}
}
saveInReturnTable(m,n,reInt);
return reInt;
} else return reInt;
}
From a comment:
In main I have a try-catch block to catch any exception try{} catch(...){}. As I understand it the three periods should catch any exception thrown. And as I understand, the throw keyword throws the exception without any specifiers, but can still be caught by the three dots.
A: A segmentation fault is not a C++ exception. It is indicative of a program failure that causes the OS to send a SIGSEGV signal to your process. You won't be able to catch a SIGSEGV signal directly; you'd have to set up a signal handler and ... well, it gets tricky at that point, because it is not clear that you can throw an exception from within a signal handler.
A throw with no exception specified rethrows the current exception; it only makes sense inside a catch block.
You probably get the SIGSEGV when your system is unable to extend the stack any further, probably because you've run out of virtual memory. That means one of your function calls failed because there was no space to put its arguments or local variables or return address, etc. There is no clean way to recover from that, which is why the system generates the segmentation fault.
If the fault was because calloc() could not allocate memory, you'd not get a segmentation fault; you'd get a zero return value. And you could raise an 'out of memory' exception cleanly and synchronously when it happens. But that isn't your problem.
A: You cannot recover from a segmentation fault, because once the fault occurs, your program is no longer in a well-defined state, and there's no mechanism to roll back to a well-defined state, either.
A segmentation fault is always a programming error in one way or another, and you must simply avoid it. In C++, you can simply catch exceptions coming from a dynamic allocation:
T * p;
try { p = new T; }
catch(const std::bad_alloc & e) { /* ... */ }
Usually there's no need to be quite that manual, though, since you would wrap your dynamic allocations inside suitable managing containers (like unique_ptr or shared_ptr), and you should catch exceptions (not even just allocation ones) at points in your program flow where you are in a position to handle the error and continue meaningfully.
(Thanks to exceptions you should not usually need to check the result of possibly throwing functions right at the call side - that's the whole point of using exceptions.)
If for some reason you just want to allocate raw memory, without constructing any object, you can do it in two ways:
// Method #1, the C++ way:
void * addr = ::operator new(n); // will throw std::bad_alloc on error
// Method #2, the manual way:
void * addr = std::malloc(n);
if (!addr) throw std::bad_alloc(); // throw exception manually, handled elsewhere
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to check if an hash is "completely" included in another hash? I am using Ruby on Rails 3.1.0 and I would like to check if an hash is "completely" included in another hash and return a boolean value.
Say I have those hashes:
hash1 = {
:key1 => 'value1',
:key2 => 'value2',
:key3 => 'value3'
}
hash2 = {
:key1 => 'value1',
:key2 => 'value2',
:key3 => 'value3',
:key4 => 'value4',
:key5 => 'value5',
...
}
I would like to check if the hash1 is included in the hash2 even if in the hash2 there are more values than hash1 (in the above case the response that I am looking for should be true)? Is it possible to do that by using "one only code line"\"a Ruby method"?
A: The easiest way I can think of would be:
hash2.values_at(*hash1.keys) == hash1.values
A: the more elegant way is to check the equality when one hash merge another.
e.g. rewrite Hash include? instance method for this.
class Hash
def include?(other)
self.merge(other) == self
end
end
{:a => 1, :b => 2, :c => 3}.include? :a => 1, :b => 2 # => true
A: That will be enough
(hash1.to_a - hash2.to_a).empty?
A: There is a way:
hash_2 >= hash_1
Alternatively:
hash_1 <= hash_2
More info in this post: https://olivierlacan.com/posts/proposal-for-a-better-ruby-hash-include/
A: The most efficient and elegant solution I've found - with no intermediary arrays, or redundant loops.
class Hash
alias_method :include_key?, :include?
def include?(other)
return include_key?(other) unless other.is_a?(Hash)
other.all? do |key, value|
self[key] == value
end
end
end
Since Ruby 2.3 you can use built-in Hash#<= method.
A: Since Ruby 2.3, you can do this:
hash1 <= hash2
A: I am not sure if I understand the inclusion idea in hash.
To see if it has the same keys(usual problem).
All keys in hash1 are included in hash2:
hash1.keys - hash2.keys == []
Then if you want to compare those values do as suggested in the previous post:
hash1.values - hash2.values_at(*hash1.keys) == []
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: What Eclipse products are there by default? I have a number of Eclipse versions installed. I noticed they have different icons in my task bar. The reason for this are different lines in the eclipse.ini files:
-product
org.eclipse.epp.package.jee.product
versus
-product
org.eclipse.epp.package.java.product
My question is now: What is the relevance of this? What does it affect? Anything besides the icon? What other products are there hidden in a normal Eclipse download?
I understand this comes from different downloads, but in the end it does not matter much which version you start with when you can add all the plugins.
EDIT: Assume I download the Java EE version, but like the icon of the standard Java version better. What ill effects can be expceted if I change the -product line in eclipse.ini?
A: Packages depend on the version of Eclipse you downloaded, e.g. the Modeling. Java EE, C++, etc..
If you go to the downloads page and click on the names of the various versions it lists the packages included by default. Sometimes there are difficult dependencies or incompatibilities you can run into when downloading each plug-in separately, so the downloads serve as a collection of plug-ins guaranteed to run 'out-of-the-box'.
I pretty sure all versions come with Mylyn, JDT, and CVS. Although these are all developed separately, they are considered so fundamental or useful to Eclipse they are included.
A: I have now used an Eclipse download that was labelled as JEE (and used the jee product) for quite a while as a Java product and was not able to notice any difference except for the icon. Therefore, I have come to believe this is indeed the only effect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Create a HUE color bar I'm creating a color picker and I am at a stage where I need to create a HUE color bar:
One way to create it would be through gradient stops in XAML. For example:
<Rectangle Width="50" Height="100">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0.5,0.025" EndPoint="0.5,1" >
<GradientStop Color="#FFFF0000" />
<GradientStop Color="#FEFFFF00" Offset="0.15" />
<GradientStop Color="#FE00FF00" Offset="0.3" />
<GradientStop Color="#FE00FFFF" Offset="0.45" />
<GradientStop Color="#FE0000FF" Offset="0.6" />
<GradientStop Color="#FEFF00FF" Offset="0.85" />
<GradientStop Color="#FFFF0000" Offset="1" />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
The above will generate:
However, I am not sure whether the stops are correct.
Is there a convention on how to generate such a bar? Any advice would be highly appreciated.
Best Regards,
Casey
A: It looks like your 2nd last stop is at a different interval (+0.25) to the previous ones (+0.15). You basically want the same gap between all stops to get the same effect (that colour bar is just a linear distribution).
Try this instead:
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1.0" >
<GradientStop Color="#FFFF0000" />
<GradientStop Color="#FEFFFF00" Offset="0.167" />
<GradientStop Color="#FE00FF00" Offset="0.333" />
<GradientStop Color="#FE00FFFF" Offset="0.5" />
<GradientStop Color="#FE0000FF" Offset="0.667" />
<GradientStop Color="#FEFF00FF" Offset="0.833" />
<GradientStop Color="#FFFF0000" Offset="1.0" />
</LinearGradientBrush>
</Rectangle.Fill>
Which looks like:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there any point to using Any() linq expression for optimisation purposes? I have a MVC application which returns 2 types of Json responses from 2 controller methods; AnyRemindersExist() and GetAllUserReminders(). The first returns a boolean, 2nd returns an array, both wrapped as Json.
I have a JavaScript timer checking for calendar reminders against a user. It makes the first call (AnyRemindersExist) to check whether reminders exist and whether the client should then make the 2nd call.
For example, if the result of the Json response is false from the Any() query, it doesn't then make the 2nd controller action which makes a LINQ select call. If there are reminders that exist, it then goes further and then requests them (making use of the LINQ SELECT).
Imagine a system ramped up where 100-1000s users use the system and on the client, every 30-60 seconds a request comes in to load in the reminders. Does this Any() call help in anyway in reducing load on the server?
A: If you're always going to get the actual values afterwards, then no - it would make more sense to have fewer requests, and just always give the full results. I very much doubt that returning no results is slower than returning an indication that there are no results.
EDIT: tvanfosson's latest comment (at the time of this writing) is worth promoting:
You can really only tell by measuring and I'd only resort to it IFF the performance of the select only option didn't meet the requirements.
That's the most important thing about performance: the value of a guess is much less than the value of test data.
A: Any only checks to see if there is at least one item in the Collection that is being returned. Versus using something like Count > 0 which counts the total amount of items in the collection then yes this is more optimal.
If your AnyRemindersExist method is operating on a similar principle then not calling a second call to the server would reduce your load.
A: I would say that it depends on how the underlying queries are translated. If the any call is translated into an indexed lookup when the select (perhaps due to a join to get related data) must do some sort of table scan, then it will save some work in the case when there are no reminders to be found. It will cause a little extra work when there are reminders. It might be useful if the majority of the calls don't result in any results.
In the general case, though, I would just select the data and only try to optimize IF that turns out to not be fast enough. The conditions under which it will actually save effort on the server are pretty narrow and might only apply if you hand-craft the SQL rather than depend on your ORM.
A: So you are asking if not doing work the application doesn't need to do would reduce the workload on the server?
Of course. How would this answer every be "yes, doing extra work for no reason won't effect the server load".
A: It ultimately depends on how much faster the Any check is compared to getting the results and how often it will be false.
*
*If the Any call takes near as long as the select then it pretty
much never makes sense.
*If the Any call is much faster than the select but 90% of the
time it's true, then it probably isn't worth it (best case you
get 10% improvement, worst case it's actually more work).
*If the Any call is much faster than the select and 90% of the
time it's false, then it probably makes sense to check if there
are any before actually getting results.
So the answer is it depends on your specific scenario. Ultimately you're going to need to measure both the relative performance (on different typical loads, maybe some queries are more intensive than others) as well as the frequency that there are no results to return.
Actually it should almost never make sense to check Any in this case.
*
*If Any returns false then you don't need to grab the results.
However this means it would have returned no results anyway, so
unless your Any check is significantly faster than a select
returning 0 results, there's no added benefit here.
*On the other hand, if Any returns true, then you'll need to get the
results anyway, so in this case Any is purely additional work done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Google image search: How do I construct a reverse image search URL? How can I programmatically through java convert an image to "some string" to pass it as a parameter for searching in google image search. Actually I have made some base64 convertion of image but it differs from that that google does in its image search engine. I've made such a convertion(java 7):
import javax.xml.bind.DatatypeConverter;
...
Path p = Paths.get("my_photo.JPG");
try(InputStream in = Files.newInputStream(p);
PrintWriter write = new PrintWriter("base64.txt");
) {
byte [] bytes = new byte[in.available()];
in.read(bytes);
String base64 = DatatypeConverter.printBase64Binary(bytes);
write.println(base64);
} catch(IOException ex) {
ex.printStackTrace();
}
the output of this simple program differs from the google's string in url. I talk about that string that goes after tbs=sbi:AMhZZ...
A: Using google's image search.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class HttpFileUpload {
public static void main(String args[]){
try {
HttpClient client = new DefaultHttpClient();
String url="https://www.google.co.in/searchbyimage/upload";
String imageFile="c:\\temp\\shirt.jpg";
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart("encoded_image", new FileBody(new File(imageFile)));
entity.addPart("image_url",new StringBody(""));
entity.addPart("image_content",new StringBody(""));
entity.addPart("filename",new StringBody(""));
entity.addPart("h1",new StringBody("en"));
entity.addPart("bih",new StringBody("179"));
entity.addPart("biw",new StringBody("1600"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
if (line.indexOf("HREF")>0)
System.out.println(line.substring(8));
}
}catch (ClientProtocolException cpx){
cpx.printStackTrace();
}catch (IOException ioex){
ioex.printStackTrace();
}
}
}
A: Based on @Ajit's answer, this does the same but using the curl command (Linux / Cygwin / etc)
curl -s -F "image_url=" -F "image_content=" -F "filename=" -F "h1=en" -F "bih=179" -F "biw=1600" -F "encoded_image=@my_image_file.jpg" https://www.google.co.in/searchbyimage/upload
This will print a URL on standard output. You can download that URL with curl or wget but you may have to change the User Agent to that of a graphical web browser like Chrome.
A: This is my best guess for how the image search works:
The data in the URL is not an encoded form of the image. The data is an image fingerprint used for fuzzy matching.
You should notice that when you upload an image for searching, it is a 2 step process. The first step uploads the image via the url http://images.google.com/searchbyimage/upload. The Google server returns the fingerprint. The browser is then redirected to a search page with a query string based on the fingerprint.
Unless Google publishes the algorithm for generating the fingerprint, you will be unable to generate the search query string from within your application. Until then, you can have your application post the image to the upload URI. You should be able to parse the response and construct the query string.
EDIT
These are the keys and values sent to the server when I uploaded a file.
image_url =
btnG = Search
encoded_image = // the binary image content goes here
image_content =
filename =
hl = en
bih = 507
biw = 1920
"bih" and "biw" look like dimensions, but do not corrispond to the uploaded file.
Use this information at your own risk. It is an undocumented api that could change and break your application.
A: This is what work for me. No need any encoding actually.
https://www.google.com/searchbyimage?image_url=YOUR_IMAGE_URL
A: Use Google Vision API for that. There are also lot of examples available from Google
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: PHP radom output from key value array How can I get the follow thing done.
The follow array I have:
array(2) { [0] => array(3) {
["id"] => string(1) "5"
["avatar"] => string(15) "4e0d886ee9ed3_n"
["username"] => string(5) "testuser1"}
[1] => array(3) {
["id"] => string(1) "1"
["avatar"] => string(15) "4e25bc58b6789_w"
["username"] => string(6) "testuser2"
}
}
I want to create a array with just one user in it, but it has to be random. It can be like
user with id=5, id=1 or a hole other user (when there are more users).
A: Did you try, something like:
$rand = array_rand($your_array);
http://fr2.php.net/manual/en/function.array-rand.php
A: $rand_user = array_rand($your_array);
PHP Manual: array_rand
A: Try using array_rand().
$randomKey = array_rand($yourArray);
$randomUserId = $yourArray[$randomKey]['id'];
Simple.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP & MySQL - get top level category with just one query I'm trying to get the first category (level zero, no parents) from a child category (which might be any level) with just one query with MySQL. Is that possible?
Here's an example DB structure :
Table categories
id (INT 11)
parent (INT 11, zero if it has no parent)
name
edit: Would MPTT be a easier solution to the problem?
A: Yes, with a stored function and recursion. You may run into an endless loop, so take care.
A: It is impossible to scan infinite levels with only one query but if you are sure your categoies tree doesn't go deeper than a certain number of levels you can use this trick, this is for 4 levels:
SELECT COALESCE(c4.parent, c3.parent, c2.parent, c1.parent)
FROM categories AS c1
LEFT JOIN categories AS c2 ON( c1.parent = c2.id )
LEFT JOIN categories AS c3 ON( c2.parent = c3.id )
LEFT JOIN categories AS c4 ON( c3.parent = c4.id )
WHERE c1.id = {someID}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Seamless image replacement / update I am creating a multi-layered image editor using AJAX to send calls to a PHP script, then using a GD library to process the changes, save the new image and send the new image path back to the browser for AJAX to replace old with new.
This example, when you move a layer it seamlessly moves the layer without a single flicker of the image. This example uses a dll file to serve the image, I want to be able to achieve the same thing in PHP / JS.
Idea 1
I thought about applying a z-index to the current image and load the new image below it, once it's loaded, hide the old image.
Idea 2
Set the image path to a php script which outputs the raw data of the compiled image direct to the browser.
A: if you want to replace the image "without a single flicker", just preload the image
(load the image to a hidden img element or a Image javascript object and then show it on an onload callback)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: latest Mercurial and IIS on Windows 2003 I don't get it working :(
What I did so far:
installed:
-tortoisehg-2.1.3-hg-1.9.2-x86.msi
-python-2.7.2.msi
-mercurial-1.9.2-x86.msi
My PATH Variable contains: D:\Program Files\TortoiseHg\;D:\Python27;
Created D:\MercurialWeb\ and set it up in IIS to run a test python cgi script.
In copied the templates directory from tortoiseHg to that web dir and extracted the library zip, too.
My hgweb.cgi looks like this:
#!/usr/bin/env python
#
# An example hgweb CGI script, edit as necessary
# See also http://mercurial.selenic.com/wiki/PublishingRepositories
# Path to repo or hgweb config to serve (see 'hg help hgweb')
config = "/path/to/repo/or/config"
# Uncomment and adjust if Mercurial is not installed system-wide:
#import sys; sys.path.insert(0, "/path/to/python/lib")
# Uncomment to send python tracebacks to the browser if an error occurs:
import cgitb; cgitb.enable()
from mercurial import demandimport; demandimport.enable()
from mercurial.hgweb import hgweb, wsgicgi
application = hgweb(config)
wsgicgi.launch(application)
hgweb.config
[paths]
MySourceCode = D:\MercurialRepos\**
[web]
style = monoblue
But if I open the Site I get this:
<type 'exceptions.ImportError'>: No module named mercurial
args = ('No module named mercurial',)
message = 'No module named mercurial'
A: There are a number of different blogs about setting up Mercurial on Windows Server, and most of them specify a specific Mercurial version ( the hightest I've seen is 1.7 ).
See if this blog helps : http://hyperionchaos.net/blog
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery $(document).ready and reading div content on load Anyone know why this isnt working?
css
#test1
{
height: 50px;
border: 1px solid black;
}
#test2
{
height: 50px;
color: red;
border: 1px solid black;
}
html
<div id="test1">
test<br />
Text
</div>
<br />
<div id="test2">
</div>
jquery
$(document).ready(function(){
if($("#test1").val() != "")
{
$("#test2").val($("#test1").val());
$("#test2").val("");
}
});
I also have a link of the code here to play with: http://jsfiddle.net/FDe9N/4/
on the $(document).ready doesnt the site fully load before executing the code? and if so doesnt that mean the div should already contain the text? the code doesnt hit the code in the if statement as if the div was empty when in fact it does have text in it... Thanks in advance!
A: val() only gets or sets the value of form elements. Since you're using <div> elements, you should use text() or html() instead:
$(document).ready(function() {
if ($("#test1").html() != "") {
$("#test2").html($("#test1").html());
$("#test1").empty();
}
});
A: Use .html() not .val(). Val is for form elements.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get href of wrapping anchor on click I need to be able to get the href (or somehow get the target url) of any <a> tag that is clicked even if it is wrapping another element. For example, you could ordinarily do:
$("document").click(function (event) {
url = event.target.href;
});
However, in this example, the <a> wraps an <img>, so the event target will not have the href. Using parentNode is no good either, because there is also a span around the img in the example:
http://jsfiddle.net/z7ZYw/
I cannot change the selector either.
So is there any way to get the href in this circumstance?
A: You're looking for jQuery's closest method:
$(e.target).closest('a');
A: As a note, this can be done without jQuery aswell:
var href = (e.target.parentNode && e.target.parentNode.href) ? e.target.parentNode.href : e.target.href;
A: You need to bind only on anchor tags:
$("a[href]").click(function () {
console.log($(this).attr("href"));
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do you add a variable to the global scope? (ruby on rails) So, I'm trying to do some unit tests, and my current_account_permissions variable is undefined when running the tests. (works fine when the server is running).
It's similar to current_user in that it's available everywhere, except tests apparently.
Is there a way I can add the variable to the global scope?
Maybe something like ENV["current_account_permissions"] = whatever but not having to use the ENV[] notation to retrieve the variable?
A: I am assuming here, but without any code it is hard to tell, that somehow the current_account_permissions is mixed in into the ApplicationController.
I would also assume that the current_account_permissions is a method, which should do something like
def current_account_permissions
@current_account_permissions ||= current_user.get_current_account_permissions
end
So if that is the case, all your controller tests would run fine as dandy. In your view tests however, you will have to stub the current_account_permissions because when testing there is no controller context.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is blockquote element not inheriting parent p's styles? I have very very simple HTML:
<p>
<blockquote>
</blockquote
</p>
The p element has a rule in an external stylesheet to define the font-family and color, yet when the blockquote is inside the p, the blockquote is not inheriting any of the p's styles. This is in IE 9.
Why is this?
A: You cannot have a blockquote inside a paragraph.
Since the end tag for a paragraph is optional, the following means:
<p> <!-- Start paragraph -->
<blockquote> <!-- Blockquote forbidden inside p. End paragraph. Start blockquote -->
</blockquote> <!-- End blockquote -->
</p> <!-- End paragraph. Paragraph not open. Error. Ignore. -->
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Avoid long lines in Perl scripts I have used \ at the end of shell scripts to avoid long lines, and improve code readability.
But I cannot do it in Perl, what am I doing wrong ? Do I have to escape them in any way?
I mean something like:
my $dbh = DBI->connect("DBI:mysql:database=xxxxxxx;host=xxxxxt", "xxxx", "xxxxxx", \%dbattr) or die ("Bla bla bla bla");
A: There is no need to escape.
From perldoc perlsyn:
Perl is a free-form language, you can format and indent it however you
like. Whitespace mostly serves to separate tokens, unlike languages
like Python where it is an important part of the syntax:
my $dbh =
DBI->connect("DBI:mysql:database=xxxxxxx;host=xxxxxt",
"xxxx", "xxxxxx", \%dbattr
)
or die ("Bla bla bla bla");
A: Perl statements are terminated separated by a semicolon ;, you don't need to write code on one line. Your example can be formatted as:
my $dbh = DBI->connect(
"DBI:mysql:database=xxxxxxx;host=xxxxxt",
"xxxx",
"xxxxxx",
\%dbattr
) or
die ("Bla bla bla bla");
Or in any way you like.
You can also take a look at tools like perltidy to automatically beautify your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What actually does this javascript snippet mean? From HTML5 Mobile Boilerplate's helper.js:
(function(document){
//all stuff here
})(document);
What does this snippet do or when does it run?
A: This is a closure, it defines a method which takes an argument document and immediately calls it with document as the parameter.
It runs as soon as it's finished evaluating - so basically straight away.
A: It creates a temporary, anonymous function and calls it with an argument called document. Presumably it has some local variables that it is hiding from the enclosing scope.
A: This is a javascript function that executes immediately when the browser encounters it while parsing the page. The function takes one parameter, which is the window.document property (as passed in at the bottom of the function.
A: If you say:
(function(var1){/*stuff*/})(var2)
That immediately calls the function and passes var2 to the function. Note that the function is anonymous and cannot be called directly. You can read about anonymous functions in general and anonymous functions in Javascript here:
http://en.wikipedia.org/wiki/Anonymous_function#JavaScript
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PowerShell+MSI. How to release opened database? I have VB Script:
.....
Set oInstaller = CreateObject("WindowsInstaller.Installer")
Set otempDB = oInstaller.OpenDatabase(sMsiFullPathTemp, 1)
.......
Set otempDB = Nothing
At this string it releases database: Set otempDB = Nothing.
I need to make PowerShell script like this VBS to work with MSI.
PowerShell:
....
function Invoke-Method ($Object, $MethodName, $ArgumentList) {
return $Object.GetType().InvokeMember($MethodName, 'Public, Instance, InvokeMethod', $null, $Object, $ArgumentList)
}
$oInstaller = New-Object -ComObject WindowsInstaller.Installer
$otempDB = Invoke-Method $oInstaller OpenDatabase @($tempmsi, 1)
But how I can release MSI database until script haven't finished work?
I mean something like: Set otempDB = Nothing
Could someone help me with it?
Thanks
A: you can always assign the variable to $null:
$otempDB = $null
However for COM objects this often results in the object just being shuffled off to limbo somewhere. Better is to explicitly relese the object and clean up the memory:
([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$otempDB) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Somewhere I came across a function for this some time ago (if someone knows who originally posted this function please leave a comment and I will attribute it). I use it pretty much any time that I work with COM objects:
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add views to UIWebVIew? like this image I wonder how some apps do this great affect, i've trying to accomplish this but without much success.
the idea is to add views like textview or label to a webview or to scollview so that it appears with gray background and can be scrolled, the below image describes the intended goal :
I would be very much appreciated if you help me.
A: Use following code and just background color your UIView.Hope It will helps you.
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
A: Use a pure HTML/javascript/CSS solution, not a native UIVIew laid on top of the UIWebView
CSS like this creates an initially invisible box, 400px wide, 120px from top, white background, bordered:
.floater
{
display: none;
position: absolute;
top: 120px;
left: 50%;
width: 400px;
margin-left: -200px;
z-index: 200;
background-color: #ffffff;
border-top: solid 2px #b0b0b0;
border-left: solid 2px #b0b0b0;
border-bottom: solid 2px black;
border-right: solid 2px black;
}
Use this class="floater" on your label, div, whatever.
You can then use the display style to hide/unhide it via javascript.
A: If you want your content to scroll within the webView, You have to add the view as a subview of the first subview of the webview.
The scrollview is the first subview of the webview
[[[webview subviews] objectAtIndex:0] addSubview:imageview];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making firefox addon using Qt I wanted to ask whether it is possible to make an firefox addon using Qt.If possible how can I do that ?
A: See the Qt Browser Plugin example from Nokia/Digia/etc. Was part of Qt Solutions (now discontinued, but is under the BSD license and since it used Qt 4.x when it was supported, should still be usable, just a little dusty. Expect a bit of work to compile it at first, though).
It supports creating a NPAPI plugin. You can find the READEME at http://qt.gitorious.org/qt-solutions/qt-solutions/blobs/master/qtbrowserplugin/README.TXT - and all the other files are in the same directory.
The documentation is also available: http://doc.qt.digia.com/solutions/4/qtbrowserplugin/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sending querystring variable to new popup window My JavaScript code is this:
var newwindow;
function poptastic(url) {
newwindow = window.open(url, 'name', 'height=400,width=200');
if (window.focus) { newwindow.focus() }
}
And my C# code:
foreach (GridViewRow row in GvComments.Rows)
{
Button btnReplay = (Button)row.FindControl("btnReplay");
string url = "javascript:poptastic('Configuration.aspx?id=" + e.CommandArgument + "')";
btnReplay.Attributes.Add("onclick", url);
}
I think the C# code has problem, because when I use this JavaScript code in a tag it works, but in attribute.add not working.
A: Try using OnClientClick for this instead:
btnReplay.OnClientClick = String.Format("poptastic(\"Configuration.aspx?id={0}\");return false;", e.CommandArgument);
EDIT
Here's a JavaScript function you can use to open popup windows:
openChildWindowWithDimensions = function(url, width, height, showMenu, canResize, showScrollbars) {
var childWindow = window.open(url, "", "\"width=" + width + ",height=" + height + ",menubar=" + (showMenu ? "1" : "0") + ",scrollbars=" + (showScrollbars ? "1" : "0") + ",resizable=" + (canResize ? "1" : "0") + "\"");
if (childWindow){
childWindow.resizeTo(width, height);
childWindow.focus();
}
}
A: This problem would be very easy to answer, if you can provide the HTML generated. To find HTML generated go the browser window where you are seeing the rendered page and do a View Source. See How do I check my site's source code
With the code you have provided all the suggestions I can make are already made by @James Johnson
Please see a minor correction to James code
btnReplay.OnClientClick = String.Format("poptastic('Configuration.aspx?id={0}');return false;", e.CommandArgument);
Note: I have changed \" to '
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Race condition with Performance Counters for current process I am trying to get around the old "How do I get a Windows Performance Counter for the current process" issue. Basically I am enumerating Process Object instances to get a list of Process objects that I can then query for their process id and compare to my own.
Based on this I can build a performance counter path using the correct instance index (to create something similar to \Process(my_program#3)\<counter>) that I can then use to query whatever counter it is that I am interested in. But what happens if one or more of the other instances of my_program exit prior to the PdhAddCounter call? If I understand correctly, this would mean that my counter path now refers to a different process or is now invalid. They might even disappear while querying for the process id...
How do I prevent the counter path from becoming invalid before I can use it to get a counter handle?
A: Wow, you are right. This seems like a major design flaw to me. Basically it is impossible to reliably monitor an instance if it's name is not unique. I did stumble across a workaround specifically for the Process and Thread objects, but that's a global setting that could affect other applications.
I think the safest way to do this would be to watch all process objects, and each time you collect the data go through and find the one with the desired Process Id.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Locating a file directory to display pdf in c# I am having a problem with displaying a pdf in my form wen a menu item is clicked
the directory im using cant be found
the file is in the project folder
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(@"\\ColsTechieApp\\TechnicianApplicationUserManual.pdf");
}
when i enter the full location
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(@"C:\Users\UV Chetty\Dropbox\Final\Complete\ColsTechieApp (Complete)\ColsTechieApp\Technician Application User Manual.pdf");
}
it works how do i make the path exclusive to the project folder
A: Try using Environment.CurrentDirectory as your current set and combin it with Path.Combine
Should work, becaus you are using full path
A: First, you're trying to escape backslashes but the @ specifies that the string shouldn't be escaped. (Plus, you seem to be missing whitespaces)
Secondly, Environment.CurrentDirectory inserts the current path. Used with Path.Combine, you'll have your entire location.
If you're really lazy, you can skip the Path.Combine and directly concatenate strings. Process.Start() probably converts it to a Path automatically.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to add an image to a MessageBox in VBA? I am wondering if it is possible to add an image to a messagebox in VBA mainly, but if not any other languages.
MsgReply = MsgBox("InspectionCreator - Continue?", vbMsgBoxSetForeground + vbSystemModal + vbYesNo)
If vbYes = MsgReply Then
Listener.Connect2SW
Else: End
End If
A: No, you can't display an image in a MessageBox. Unless you mean the symbols such as Warning, Error, etc?
Although you could simulate it by creating a UserForm which has the appearance of a MessageBox, with an image in the background and then just Show() the form instead of calling the MsgBox function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Excel 2007 Pass-Through Windows Authentication I've created a simple (asmx) web service which returns a DataSet.
I've added the webservice to my Excel 2007 workbook using the Data -> From Web button and I'm able to view / refresh the data.
The problem comes when I need to secure the web service: I've turned on Windows authentication for the web service and the request uses SSL.
Unfortunately, the user's logged on windows credentials aren't used by Excel when trying to refresh the data - the refresh fails.
If I click on Data -> Connections -> Properties -> Definition -> Edit Query, only then am I prompted for my windows credentials and does the refresh then succeed.... not a problem for me, but not something I want every user of this spreadsheet to have to do... any ideas how to make the prompt come up when the refresh is attempted instead of having it fail??
Thanks!!
Update Answers so far are to do with SharePoint and Excel Services (neither of which are any use to me)... and one link for which "The following procedure does not apply to data that is retrieved from a text file or a Web query"... I just want a person with a copy of excel on his desktop machine to be able to update from a password-protected web service... is that so hard Microsoft??
Another Update Still no answers accepted - because no answers so far have provided a working solution ( Nice googling though - thanks guys ;-) )
A: While I haven't got SSL I can attest that Excel normally shouldn't ask you for authentication when using pass through authentication.
My guess is that you will need to add the destination website (with the https) to your trusted zone in IE. The effect should be that when you go to the website you shouldn't be challenged for your password at all. IE will now pass through the authentication credentials because the destination is in the trusted zone.
Once this is fixed Excel should treat it like a normal website.
Here's a link which talks you through adding your site to the trusted zone: http://www.nateirwin.net/2007/01/19/enabling-ntlm-authentication-in-firefox-and-internet-explorer/
A: The last time I dealt with this issue was in 2004. If I remember correctly, this is a bug in the Web Query technology in how the query deals with the SSL certificate. This is Excel 97 technology; therefore, fairly basic implementation.
After much research and troubleshooting, the only way around this issue is to create user and password parameters and post the web query. Using POST will keep the user/password hidden from prying eyes.
Following is my note from 2004: There is a problem with https, application/vnd.ms-excel, Internet Query (iqy), and Excel 2000/2002.
Have you checked out this question: What do I need to do to make Excel access a Web Query via HTTPS?
Excel's Web Queries Enable You to Populate Worksheets from Web Sites at http://msdn.microsoft.com/en-us/library/aa155714(v=office.10).aspx.
Sites requiring authentication and passwords provide additional
challenges. They may require coded workarounds or may be unsolvable.
Error message when you use Web query to a secure Web page () in Excel: "Unable to open" at http://support.microsoft.com/kb/290347.
XL97: How to Create Web Query (.iqy) Files at http://support.microsoft.com/kb/157482 is an invaluable resource. (There was a Web Query SDK once that I cannot find, but this article is a good replacement.)
Different Ways of Using Web Queries in Microsoft Office Excel 2003 at .
A: I don't know if this will help, but I faced a similar situation while importing data from a remote SQL Server Database. What I did was create a role inside the database itself, and assign any users who needed access to that role.
The data is updated into the workbook when the file is loaded using Microsoft Query, so I don't know how that might differ from how you have done things.
The biggest issue with doing it this way was to open the properties for the query and check the "Use Trusted Connection" box. This worked without an issue for me. Again, this was from a remote server, not a secure website. Hope this helps.
A: i hope this will help you : Refresh connected imported data
A: We had a similar situation at work, however, we are using Office 2010. I'm not sure of the limitations of 2007. Check out these links. The last two are specifically for Excel 2007.
Link 1: Configure Secure Store Service for Excel Services
Link 2: Ten Tips for Using SharePoint Server 2007 with Excel Services
Link 3: Plan external data connections for Excel Services
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: A basic question on java/TestNG After writing my first few Java test programs, I want to write corresponding TestNG classes. I am using RHEL 5. I see that a typical directory looks like src/main/java and src/test/java.
(a) Who creates such directory? Do we create it manually? or there is a way to create test directory structure corresponding to main code dir structure.
(b) Also, how do I run these testNG classes from command line? Do I need to have any additional extra jars like testng.jar or something to support these annotations or these annotations are supported in default jdk 1.6?
(c) Also, when I create a TestNG class from Eclipse, it necessarily asks for a package name. Why is it so?
A: a) Who creates such directory? Do we create it manually? or there is a way to create test directory structure corresponding to main code dir structure.
Its created by some tool like Maven or yourself. Tools will just create a test folder, further folders/structure are purely specific to practices in your project.
(b) Also, how do I run these testNG classes from command line? Do I need to have any additional extra jars like testng.jar or something to support these annotations or these annotations are supported in default jdk 1.6?
Here is nice link which shows how to run TestNG classes from command line including the extra jars needed
(c) Also, when I create a TestNG class from Eclipse, it necessarily asks for a package name. Why is it so?
I don't any reason other than enforcing a fair practice.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apache 2 The requested URL / was not found on this server I'm hosting a couple of webservers. I've set the first one up with no problems. On the second server when I attempt to navigate to it (http://192.168.1.47:99/) I get this error "The requested URL / was not found on this server." I know that the port is being forwarded properly because I can access "http://192.168.1.47:99/phpmyadmin" just fine. I've tried to figure this out for a week or so now and I'm at a loss. Any help would be greatly appreciated!
Ubuntu Linux 10.04
Apache2
php5
I'll provide any additional information that may be needed.
Thanks!
Update - Included config files
* apache2.conf
* httpd.conf
* ports.conf
* sites enabled
A: we need to change the following lines to /etc/apache2/apache2.conf:
Note :- Change here AllowOverride None to AllowOverride All usingsudo property
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
Now :- Restart your web server
sudo /etc/init.d/apache2 restart
It will work now..
A: As far as I understand you, you want your server to respond on Port 99. Your configuration is listening on Port 80 instead. Change the following line in sites-enabled:
<VirtualHost *:80>
to
<VirtualHost *:99>
and in ports.conf
NameVirtualHost *:80
to
NameVirtualHost *:99
Restart your apache. That should do it.
A: If you want to make it work without changing port you can follow these steps
sudo nano /etc/apache2/apache2.conf
and add following line at end
Include /etc/phpmyadmin/apache.conf
then restart apache
/etc/init.d/apache2 restart
Better explain here
https://askubuntu.com/questions/55280/phpmyadmin-is-not-working-after-i-installed-it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: how to display total sum of rows in datagrid in flex I have an AdvanceDataGrid. How can I show the total of each column at the bottom. I am able to calculate the total, and tried displaying them on labels below each column by giving width as column width. But they are not getting aligned properly below each column.
<mx:Label id="TotalMonth" text="{numberFormatter.format(totalMonthAmount)}" width="{colWidth}"/>
Is there a way by which I can assign total to the grid itself instead of using seperate labels below.
A: You have two options for this. First is to use another advanced data grid, the other is to modify the dataProvider of yours.
Lets say you have arrayCollection of objects of type MockData
public class MockData
{
public var value1:Number;
public var value2:Number;
public var value3:Number;
public var value4:Number;
}
The two data grids option should be something like this:
<?xml version="1.0" encoding="utf-8"?>
protected function getSummedResult(value:Object):ArrayCollection
{
var summedResult:MockData = new MockData();
summedResult.value1 = 0;
summedResult.value2 = 0;
summedResult.value3 = 0;
summedResult.value4 = 0;
for each (var data:MockData in value as ArrayCollection)
{
summedResult.value1 += data.value1;
summedResult.value2 += data.value2;
summedResult.value3 += data.value3;
summedResult.value4 += data.value4;
}
return new ArrayCollection([summedResult]);
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
<s:ArrayCollection id="mockData">
<mock:MockData
value1="{Math.random() * 10}"
value2="{Math.random() * 100}"
value3="{Math.random() * 1000}"
value4="{Math.random() * 10000}"/>
<mock:MockData
value1="{Math.random() * 10}"
value2="{Math.random() * 100}"
value3="{Math.random() * 1000}"
value4="{Math.random() * 10000}"/>
<mock:MockData
value1="{Math.random() * 10}"
value2="{Math.random() * 100}"
value3="{Math.random() * 1000}"
value4="{Math.random() * 10000}"/>
<mock:MockData
value1="{Math.random() * 10}"
value2="{Math.random() * 100}"
value3="{Math.random() * 1000}"
value4="{Math.random() * 10000}"/>
<mock:MockData
value1="{Math.random() * 10}"
value2="{Math.random() * 100}"
value3="{Math.random() * 1000}"
value4="{Math.random() * 10000}"/>
<mock:MockData
value1="{Math.random() * 10}"
value2="{Math.random() * 100}"
value3="{Math.random() * 1000}"
value4="{Math.random() * 10000}"/>
<mock:MockData
value1="{Math.random() * 10}"
value2="{Math.random() * 100}"
value3="{Math.random() * 1000}"
value4="{Math.random() * 10000}"/>
</s:ArrayCollection>
</fx:Declarations>
<mx:VBox>
<mx:AdvancedDataGrid id="dateGrid" dataProvider="{mockData}" />
<mx:AdvancedDataGrid rowCount="2"
id="dateGrid2" dataProvider="{getSummedResult(dateGrid.dataProvider)}" />
</mx:VBox>
The second option is to use only one grid like this:
<mx:AdvancedDataGrid id="dateGrid" dataProvider="{getSummedResult(mockData)}" />
protected function getSummedResult(value:Object):ArrayCollection
{
var dataProvider:ArrayCollection = ArrayCollection(value);
var summedResult:MockData = new MockData();
summedResult.value1 = 0;
summedResult.value2 = 0;
summedResult.value3 = 0;
summedResult.value4 = 0;
for each (var data:MockData in dataProvider)
{
summedResult.value1 += data.value1;
summedResult.value2 += data.value2;
summedResult.value3 += data.value3;
summedResult.value4 += data.value4;
}
var result:ArrayCollection = new ArrayCollection(dataProvider.source.concat());
result.addItem(summedResult);
return result;
}
Your personal choice is what will be more helpful. You can modify the data provider if you have setter for it ofc but with binding is pretty simple.
Have fun and good luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Filtering DataTable in VB.Net I am having a datatable with following structure.
mid mname version baseID
------------------------------------
1 tag3 1 1
2 tag3 2 1
3 tag3 3 1
4 tag5 1 4
5 tag5 2 4
6 tag6 1 6
From the above structure I need a datatable similar like this.
I need to take the highest version from the datatable.
mid mname version baseID
------------------------------------
3 tag3 3 1
5 tag5 2 4
6 tag6 1 6
How can I create a datatable similar like the above.
I am using Vb.Net
Thanks in advance.
A: It depends upon how your populating the original datatable. if you are doing it by querying a database I would format the result set in the query itself something like:
(SQL)
select mid, mname, version, baseID
from <table> t
Join (select baseid, max(version) as version
from <table> group by baseID)maxVersion
on maxVersion.baseid = t.baseid and maxVersion.version = t.version
this would format the data before its put into the datatable.
If the datatable is populated by other means and you need to filter it then put it in antoher datatable. then an easy way to do it (assuming your datatable is always sorted in the above manner) is:
for i as integer = 0 to datatable.rows.count - 1
if i < datatable.rows.count - 1 Then
if datatable.rows(i)(4).value <> datatable.rows(i+1)(4).value then
newDataTable.rows.Add(datatable.rows(i).itemArray())
End If
Else
newDataTable.rows.Add(datatable.rows(i).itemArray())
End if
Next
Now the syntax might be off here or there (wrote it in notpad) but the idea of the logic is there. assuming you have the same format each time then I'm checking for when the row changes to a new baseid and adding that row to the new datatable. from the example you posted it looks like the max version of a particular baseid is the last row of that baseid.
-Chris
A: I have used
Datatables.Compute() to get the MAX value using GROUP By
Function GroupBy(ByVal i_sGroupByColumn As String, ByVal i_sAggregateColumn As String, ByVal i_dSourceTable As DataTable) As DataTable
Dim dv As New DataView(i_dSourceTable)
'getting distinct values for group column
Dim dtGroup As DataTable = dv.ToTable(True, New String() {i_sGroupByColumn})
'adding column for the row count
dtGroup.Columns.Add("Max_Version", GetType(Double))
'looping thru distinct values for the group, counting
For Each dr As DataRow In dtGroup.Rows
dr("Max_Version") = i_dSourceTable.Compute("MAX(" & i_sAggregateColumn & ")", i_sGroupByColumn & " = '" & dr(i_sGroupByColumn) & "'")
Next
'returning grouped/counted result
Return dtGroup
End Function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: JSON call fails with JQuery I've been searching arround and I can't retrive JSON information from this example. Can anybody help me please?
var jsonURL = "http://mdc2.cbuc.cat/dmwebservices/index.php?q=dmGetCollectionList/json";
var jqxhr = $.getJSON(jsonURL, function(data) {
alert("Success!");
alert(data[0].alias);
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
jqxhr.complete(function(){ alert("second complete"); });
I've checked the URL and everywhere it says that is valid and well formated...
A: Is the page running that code hosted on mdc2.cbuc.cat? Otherwise, you're probably running into the same origin policy.
A: Since that request is not returning proper jsonp, the browser can't interpret it.
If you have access to that server, it would need to be modified to accept a callback function such as ?callback=cbfunc which would then wrap the json response in a callback function, such as cbfunc(["foo","bar"]);
If you do not have access to that server, you can either use a 3rd party solution such as YQL, or you can build a server-side proxy that will make the request for you. For YQL, here's a page that can help:
http://developer.yahoo.com/yql/console/#h=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22http%3A//mdc2.cbuc.cat/dmwebservices/index.php%3Fq%3DdmGetCollectionList/json%22
choose the json radio button, then at the bottom of the page you'll find a url. just remove the callback=cbfunc part.
This is the url that was generated:
http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22http%3A%2F%2Fmdc2.cbuc.cat%2Fdmwebservices%2Findex.php%3Fq%3DdmGetCollectionList%2Fjson%22&format=json&callback=cbfunc
If the request contains any sensitive data, i would suggest against YQL and for using a server-side script to get the data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Testing code that uses another framework than jQuery using QUnit? I am writing a small library that can use several frameworks (jQuery, Prototype, YUI2 at the moment) as its backend and I am testing it using QUnit. However, QUnit requires jQuery.
Is there a way to run a test in a sandboxed environment which does not contain jQuery?
EDIT: I'd prefer a sandbox over just including everything because it would enable me to test several versions of the libraries at the same time.
A: This answer may be a bit late -- qunit now does not utilize jquery as it's base, so you should be able to run it independent of jquery. Good luck on your work!
A: I would include your additional libraries, then jQuery, then qUnit, then use $.noConflict() to relinquish control of the $ variable back to the other libraries. At that point, you can write unit tests for your other libraries just like you would for jquery without worrying about conflicts. Since jQuery doesn't extend any core methods, you shouldn't have any issues.
A: Is http://jsfiddle.net/ something you would be looking for?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When to expect IEnumerable and when to expect IQueryable from a Linq query I am having some trouble understanding when Linq is giving me an IQueryable result and when it is giving me an IEnumerable result.
Example:
I am using EF and I have two entities Location and Configuration.
Each Location can have multiple Configurations.
The following query is giving me an IQueryable as result:
Context.Locations.Where(l => l.Name == "SomeName")
whereas the following is giving me an IEnumerable as result:
Context.Locations.Where(l => l.Name == "SomeName").First().Configurations.Select(c => c)
Why is that?
A: In general, LINQ extension methods on IQueryable (defined in Queryable) return IQueryables, and the ones on IEnumerable (defined in Enumerable) return IEnumerables. In this particular case, Configurations is a collection (IEnumerable) on the first returned Location object. Therefore the .Select call returns an IEnumerable.
EDIT: To make it all execute remotely, you could try this:
Context.Locations.Where(l => l.Name == "SomeName").Configurations
Assuming that your filter on Locations is only going to return one row, you should get the same result. Of course it will be an IQueryable, but that shouldn't make a difference. If you need to materialize it, you can do something like:
Context.Locations.Where(l => l.Name == "SomeName").Configurations.ToList()
A: Basically, IQueryable allows for remote data sources (like SQL Server). It will work against the database, if possible. IEnumerable works with in-memory collections.
So, if you are querying a SQL Server database, you will get an IQueryable. Otherwise it'll be an IEnumerable.
This article may further help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: variable is not a CFStringRef I have this:
partenaire_lat = 48.8160525;
partenaire_lng = 2.3257800;
And obtain a NSString like this:
NSString *endPoint =[NSString stringWithFormat:@"%@,%@", partenaire_lat, partenaire_lng];
and after using this NSString in some context I get this stupid error:
Variable is not a CFString.
But if I create the NSString like this:
endPoint = @"48.8160525,2.3257800" it then works perfect!
For this error Variable is not a CFString I tried the following:
NSString *endPoint1 =[NSString stringWithFormat:@"%@,%@", partenaire_lat, partenaire_lng];
CFStringRef endPoint =(CFStringRef)endPoint1;
and tried to use endPoint but not working neither this way.Anyone any miraculous idea?Thx
EDIT:partenaire_lat and partenaire_lng are both NSString!!
A: You have
partenaire_lat = 48.8160525;
partenaire_lng = 2.3257800;
You keep saying that the two variables are NSStrings but you aren't assigning NSStrings to them. You need to assign NSString objects to NSString variables - they aren't created for you automatically.
So the answers which are telling you to use formatted strings are correct. You really should be doing it like this:
partenaire_lat = [[NSString stringWithFormat:@"%f", 48.8160525] retain];
partenaire_lng = [[NSString stringWithFormat:@"%f", 2.3257800] retain];
A: You code has several potential problems:
*
*%@ format specifier expects object parameter, while it looks like you pass plain float (I may be wrong here as there's not enough context to be sure). Change format to %f to fix your problem if that's really the case:
NSString *endPoint1 =[NSString stringWithFormat:@"%f,%f", partenaire_lat, partenaire_lng];
*Your endPoint1 string is autoreleased and may become invalid outside of current scope if you don't retain it. So if you try to use your variable in another method you probably should retain it.
A: what are lat and lng? i'm assuming float or double..so you should use [NSString stringWithFormat:@"%f,%f", lat, lng]; (or however you want the floats to be formatted)
A: All you need to do
NSString *latStr=[[NSNumber numberWithFloat:partenaire_lat] stringValue];
NSString *lngStr=[[NSNumber numberWithFloat:partenaire_lng] stringValue];
and do whatever you want to do with these two string :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Ajax ComboBox rendering incorrectly I'm using the ComboBox from the AjaxControlToolkit v4.1.50731. When it displays on the page, the dropdown list renders well below the origin of the control. Unfortunately, I can't post an image due to SO restrictions.
I kept the code to a minimum on the page to avoid any possible conflicts:
<AjaxToolKit:ComboBox ID="ComboBox1" runat="server">
<asp:ListItem Text="Mild" Value="0" />
<asp:ListItem Text="Medium" Value="1" />
<asp:ListItem Text="Hot" Value="2" />
</AjaxToolKit:ComboBox>
Any idea why this is happening or how it can be corrected?
A: The issue was caused by CSS styling but I couldn't isolate it the exact cause. To resolve the problem, I created a new page with no styling and only the combo box control, calling it "PlainComboBox.aspx". Then I used an iframe tag in the page where I wanted to display the combo box, as seen below:
<iframe src="PlainComboBox.aspx" frameborder="0" height="130" >
<p>Your browser does not support iframes.</p>
</iframe>
This isolated the combo box from any styling issues elsewhere on the page and rendered correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: easiest way to move a Rect upto bounds of enclosing Rect when about to move out of it I have a Rect A inside an enclosing Rect B. the enclosing Rect B is the area in which the Rect A is allowed to be moved. when trying to move Rect A beyond the borders of enclosing Rect B it should get stuck at a border or corner of enclosing Rect B and move no further. while moving I have the following parameters at hand: properties of enclosing Rect B, properties of Rect A before the move, potential topleft position of Rect A after the move. Note that the move is not necessarily per-pixel, it might just as well be (for example) 20 pixels, in any direction. please tell me how do I go about doing this efficiently but not over-complicated?
PS: these are simply drawn geometries on a canvas in WPF so the use of transforms is also allowed but I only have Rect variables at this particular bit, not RectangleGeometries.
A: eventually I created an enclosing Rect of A and B, and then applied the solution in this question, like this:
private static Point CorrectForAllowedArea(Point previousLocation, Point newLocation, Rect allowedArea, Rect newBox)
{
// get area that encloses both rectangles
Rect enclosingRect = Rect.Union(allowedArea, newBox);
// get corners of outer rectangle, index matters for getting opposite corner
var outsideCorners = new[] { enclosingRect.TopLeft, enclosingRect.TopRight, enclosingRect.BottomRight, enclosingRect.BottomLeft }.ToList();
// get corners of inner rectangle
var insideCorners = new[] { allowedArea.TopLeft, allowedArea.TopRight, allowedArea.BottomRight, allowedArea.BottomLeft }.ToList();
// get the first found corner that both rectangles share
Point sharedCorner = outsideCorners.First((corner) => insideCorners.Contains(corner));
// find the index of the opposite corner
int oppositeCornerIndex = (outsideCorners.IndexOf(sharedCorner) + 2) % 4;
// calculate the displacement of the inside and outside opposite corner, this is the displacement outside the allowed area
Vector rectDisplacement = outsideCorners[oppositeCornerIndex] - insideCorners[oppositeCornerIndex];
// subtract that displacement from the total displacement that moved the shape outside the allowed area to get the displacement inside the allowed area
Vector allowedDisplacement = (newLocation - previousLocation) - rectDisplacement;
// use that displacement on the display location of the shape
return previousLocation + allowedDisplacement;
// move or resize the shape inside the allowed area, right upto the border, using the new returned location
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Issue with pagination in Datatables implementation I am having a small issue with pagination. When implementing the "four_button" type, the table displays correctly (with correct pagination buttons) however clicking on any of the pagination buttons (Next, Previous, etc...) will throw an error of "fnCallbackDraw is not a function". Inspecting it further in Firebug, i see that fnCallbackDraw is a div (div.dataTables_paginate). Looking within the code, I do not see where this value is being assigned??!!
To make matters more interesting the other pagination implementation of "full_numbers" works correctly.
Has anyone else come across this issue? Any help in this matter will be greatly appreciated.
A: As far as I have used the datatable plugin, there are only two options for pagination namely "full_numbers" and "two_button". I don't think "four_button" type exists even in the latest plugin as I have been using version "1.8.2". Try using either of "full_numbers" or "two_button" types.
Hope this Helps!!
A: There is no fnCallbackDraw. It is fnDrawCallback. Without seeing your DT initialization code, I'm guessing it's just a syntax error. ;-)
If I'm wrong, post back with a copy of your initialization object and we'll see if there's anything else going on there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "Connection to SQL server files require SQL Server 2005" error in Visual Studio 2008 I am very much new to the .net framework and Visual Studio. When i try to add a SQL Server database to my project using solution explorer App_data -> Add new item i get the following error message:
Connection to sql server files(.*mdf) require sql server 2005 to function properly.
I have reinstalled SQL Server 2005 succesfully but still the problem remains the same. Please help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: android version required I have created and published an application on the market...
However, on the market page it says: "Version required 1.0" while I know it needs at least version 2.0 (level 8) as it uses google maps..
I know that I have to include in the manifest file something like this:
I have tried to change the number 1 for another, but if I do it, the app crashes straight away with the following message:
android.view.InflateException: Binary XML file line #154: Error inflating class
Has anybody came across something similar?
Thanks
A: In your AndroidManifest.xml file, you need to include android:minSdkVersion and <uses-sdk> element. For example, I have this in my AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:minSdkVersion="4"
...
>
...
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="7"/>
...
</manifest>
Have a look here for more details: http://developer.android.com/guide/topics/manifest/uses-sdk-element.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Should I use Unity Config file or Code to register types and instances? Finally started to configure an IoC Container!
I'm using Unity and have configured it to have my objects registered using the config file:
e.g.
<container>
<register type="ILogger" mapTo="Logger">
<lifetime type="singleton"/>
</register>
<register type="IPdfWriter" mapTo="PdfWriter">
<lifetime type="perthread" />
<constructor />
</register>
</container>
I've reached a point where I doubt this is a good approach to register types.
For example a class of mine is dependent on the ICacheManager from Microsoft Enterprise Library Caching block and the below should be injected to it:
EnterpriseLibraryContainer.Current.GetInstance<ICacheManager>()
and that doesn't seem to be possible using just unity config settings.
It seems to me that always it's better to register the types using code rather than the config file.
What's your experience/advise in this?
Thanks
A: The answer is - do you think you'll need to change the configuration after deployment? If so, use the config file. If not, I find doing it in code to be easier.
And to answer the question you didn't ask - what you want to do is in fact possible, and quite easy. The trick is to use the same container instance for Enterprise Library and for everything else. In your startup code, set up your Unity container instance, and add the EnterpriseLibraryCoreExtension to it (which you can do in config). Then set that container as your EnterpriseLibraryContainer.Current. Once you've done that, you can have a type with a dependency on ICacheManager and everything else will just work.
Something like this:
In XML config:
<unity>
<namespace name="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity" />
<assembly name="Microsoft.Practices.EnterpriseLibrary.Common" />
<container>
<extension type="EnterpriseLibraryCoreExtension" />
<register type="IMyType" mapTo="MyImplementation">
<constructor>
<param name="cacheManager" />
</constructor>
</register>
</container>
</unity>
(You will of course need your entlib configuration as well).
Then in the startup of your application, have code like this:
var container = new UnityContainer()
.LoadConfiguration();
EnterpriseLibraryContainer.Current = new UnityServiceLocator(container);
From there everything should just work. EnterpriseLibraryContainer.Current will get objects from your container, and objects resolved from the container will get entlib objects injected like any other dependency.
Once you've gone this step, the next one is to get all your entlib objects via DI and drop the explicit calls to EnterpriseLibraryContainer.Current.
A: Some good answers so far.
There is a third option: use both. When you configure the same thing twice, the second definition over-writes the first. That means you can configure a set of reasonable defaults in code at design time and then load runtime updates from xml.
Also remember that Attributes on classes are an option for defining interception call handlers. This can remove that whole section from your policies whether xml or C#.
A: In my experience, using C# is way more expressive and dynamic than xml. However, there are parts of the setup that you may want to be able to change at runtime, then you can do both. You can use both config and code to setup the container.
A: If you expect to be switching out component implementations on a production machine (such as a client's web server) then you should be using a configuration file.
If you are just using Unity to make testing easier/reduce or remove dependencies and don't expect to be changing out parts on a production machine, then spinning it up in code is fine.
A: As others have said : using the config approach makes the code massively flexible in terms of switching types without a code change.
The downside is leaving yourself open to typos that take a while to trace if you have a large set of registrations. Every now and then I often see a fat fingered developer mistype a class name and this leads to a good thirty minutes or so of head scratching!
Personally having used both approaches I prefer the coding convention. But if I was on a project that really really needed to be dynamic then go configuration!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: spring jdbctemplate: different behaviour on different app servers (date issue) I am running the same select query on the same database using the same code but using 2 different app servers.
Query: Find a certian day's entries in a journal.
1) Existing legacy app server (BroadVision running on unix):
Select title, content from journal where entry_date = TO_DATE(?, 'DD/MM/YY HH24:MI:SS');
DEBUG:core.StatementCreatorUtils:Setting SQL statement parameter value: column index 1, parameter value [Thu Sep 29 14:32:58 IST 2011], value class [java.util.Date], SQL type unknown
This works fine
2) JBoss app server (Running on windows):
Select title, content from journal where entry_date = TO_DATE(?, 'DD/MM/YY HH24:MI:SS');
DEBUG:core.StatementCreatorUtils:Setting SQL statement parameter value: column index 1, parameter value [Thu Sep 29 14:41:26 IST 2011], value class [java.util.Date], SQL type unknown
ORA-01858: a non-numeric character was found where a numeric was expected
Any ideas how to get this running on the JBoss app?
Thanks,
Kenny
A: The code seems incorrect to me. The TO_DATE function's goal is to transform a string in a given format into a date. And you're not passing a string as argument to this function, but a java.util.Date object.
You should remove the use of the TO_DATE function, transform your java.util.Date into a java.sql.Timestamp object, and use setTimestamp to pass the argument to your prepared statement.
The fact that it worked as is on your unix box looks like an accident to me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android: After closing my app, in Application Management, still showing Force Close I can start my app and close later. But after closing, if I go to Settings-->Applications-->Manage Applicaitons and select my app, the Force Close button is still active which means my app is running behind the scenes. Why is this...???
A: When you close your application, the process of it is still active and will be active while/if system will not kill it in the future. So in Settings-->Applications-->Manage Applicaitons you can by force kill process of your application.
This is feature of Android OS.
A: Use this to close your application. It still show you Force Close button but it's closes all your activity.
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JavaScript Curve Generation How can I write a function that takes an array of 2D points and returns the Bezier/Quadractic curve(s) so I can redraw it later using the HTML5 Canvas bezierCurveTo or quadraticCurveTo method?
A: EDIT: improved.
See a demo which uses the code below.
var makeCurveArgs = function(points) {
var copy = points.slice();
var result = [];
copy.shift(); //drop the first point, it will be handled elsewhere
var tangent;
if(copy.length >= 3) {
var cp1 = copy.shift();
var cp2 = copy.shift();
var p2 = copy.shift();
result.push([cp1[0], cp1[1], cp2[0], cp2[1], p2[0], p2[1]]);
}
while(copy.length >= 2) {
var cp1 = [2 * p2[0] - cp2[0], 2 * p2[1] - cp2[1]];
var cp2 = copy.shift();
var p2 = copy.shift();
result.push([cp1[0], cp1[1], cp2[0], cp2[1], p2[0], p2[1]]);
}
return result;
}
var notThatHard = function(points) {
var origin = points[0].slice();
var curves = makeCurveArgs(points);
var drawCurves = function(context) {
context.beginPath();
context.moveTo(origin[0], origin[1]);
for(var i = 0; i < curves.length; i++) {
var c = curves[i];
context.bezierCurveTo(c[0], c[1], c[2], c[3], c[4], c[5]);
}
};
return drawCurves;
};
The general approach is that you give me the coordinates of your points and control points and I give you back a function which will execute that path on a canvas context.
The function I give requires an array of 2N+2 2-element arrays; each 2-element array is an (x,y) coordinate. The coordinates are used as follows:
points[0]: starting point of the curve
points[1]: lies on a line tangent to the beginning of the 1st bezier curve
points[2]: lies on a line tangent to the end of the 1st bezier curve
points[3]: end of 1st bezier curve, start of 2nd bezier curve
points[4]: lies on a line tangent to the end of the 2nd bezier curve
points[5]: end of 2nd bezier curve, start of 3rd curve
...
points[2*K+2]: lies on a line tangent to the end of the Kth bezier curve
points[2*K+3]: end of Kth bezier curve, start of (K+1)th
I think a similar function for quadraticCurveTo wouldn't be hard to write.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Dependant Observable Array in Knockout JS I have started to play around with knockoutjs and do some simple binding/dependant binding.
My goal is to have 1 <select> list populated based on the value of another <select> list. Both are being loaded from an ajax call to my asp.net webservice.
So I have two <select> lists
<select id="make" data-bind="options: availableMakes, value: selectedMake, optionsText: 'text', optionsCaption: 'Choose a make'"></select>
<select id="model" data-bind="options: availableModels, value: selectedModel, optionsText: 'text', optionsCaption: 'Choose a model'"></select>
Then my javascript looks like this:
$(function () {
// creating the model
var option = function (text, value) {
this.text = text;
this.value = value;
}
// creating the view model
var searchModel = {
availableMakes: ko.observableArray([]),
availableModels: ko.observableArray([]),
selectedMake: ko.observable(),
selectedModel: ko.observable()
}
// adding in a dependentObservable to update the Models based on the selected Make
searchModel.UpdateModels = ko.dependentObservable(function () {
var theMake = searchModel.selectedMake() ? searchModel.selectedMake().text : '';
if (theMake != '') {
$.ajax({
url: "/data/service/auction.asmx/GetModels",
type: 'GET',
contentType: "application/json; charset=utf-8",
data: '{make:"' + theMake + '"}',
success: function (data) {
var makes = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
var mappedModels = $.map(makes, function (item) {
return new option(item.text, item.value);
});
searchModel.availableModels(mappedModels);
},
dataType: "json"
});
}
else {
searchModel.availableModels([]);
}
return null;
}, searchModel);
// binding the view model
ko.applyBindings(searchModel);
// loading in all the makes
$.ajax({
url: "/data/service/auction.asmx/GetMakes",
type: 'GET',
contentType: "application/json; charset=utf-8",
data: '',
success: function (data) {
var makes = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
var mappedMakes = $.map(makes, function (item) {
return new option(item.text, item.value);
});
searchModel.availableMakes(mappedMakes);
},
dataType: "json"
});
});
Currently this works as expected, but I think that I am doing this wrong as the code looks pretty long, and I could do this without using knockoutjs in less code.
Also the way that I am loading up the availableModels is obviously not correct because I am using a dependentObsevable called UpdateModels which I added in order to load up the availableModels based on the value of selectedMake().text
I hope this makes sense and you can point out an improved version of this? Or tell me simply How do I reload the Models based on the Make selection?
Many Thanks,
A: I think that your code looks pretty normal. For the UpdateModels dependentObservable, you can actually use a manual subscription to selectedMake like:
searchModel.selectedMake.subscribe(function (newMake) {
if (newMake) {
//ajax request
}
else {
searchModel.availableModels([]);
}
}, searchModel);
This would not change the functionality, just a more explicit way to subscribe to a single observable changing.
You could also choose to use optionsValue: 'text' (or 'value') in the binding and your selectedMake would be set to the text or value directly.
If your models were children of the make objects, then you could even bind the models to selectedMake().models (would need to protect against selectedMake being null, which could be done using a DO, the 1.3 control flow binding, or inline like selectedMake() ? selectedMake().models : []
A: I agree with Ryan's answer.
Taking it a bit on a related tangent, I refactored it a bit to not use ajax and to simplify the example (you can always add that back in). But here is a fiddle that demonstrates what you are looking to do with some sample data.
http://jsfiddle.net/johnpapa/vGg2h/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I give focus back to object with lower z-index, trying to create a series of transparent divs on top of a map If I have a parent div that contains a child div on top of it, can I give the parent div the focus without hiding the child div?
I am using Google Maps API and would like to draw a grid of transparent divs on top of it for inserting information, however, with all of those little divs on top of my map, I cannot drag the map.
I'm sure I can do it using the API but that's sort of beside the point, because I would like to do this regardless of what I'm working on top of.
<div style="position: relative; width: 100px; height: 100px;" id="wanttofocus">
<div style="position: absolute; width: 100px; height: 100px;"
id="want_to_see_but_dont_want_to_focus_on">Some overlay information</div>
</div>
I am using JQuery and messed around with .focus() but that didn't work out.
THANKS!
A: Turns out, you can "passthru" events with jQuery:
$(document).ready(function(){
$('#want_to_see_but_dont_want_to_focus_on').bind('mousemove mousedown mouseup', function(e){
$("#wanttofocus").trigger(e); // passing thru the event
});
$('#wanttofocus').bind('mousemove mousedown mouseup', function(e){
$('.status').html(e.type + ' ' + e.pageX + ' ' + e.pageY);
});
});
I've thrown together a jsFiddle, feel free to play: http://jsfiddle.net/gK6Aa/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to deserialize object with custom serializable properties? I'm trying to serialize/deserialize collection of interfaces, which basically is unsupported. I found a question on SO where a proposition is stated to provide a serializable wrapper properties for those properties which depends on interfaces. So that's what I have:
public class Serialize {
public Serialize() {
this.SCollection = new SerializableInterfacesCollection<ObservableCollection<A>>(new ObservableCollection<A>());
}
[XmlIgnore()]
public ObservableCollection<A> Collection {
get {
return this.SCollection.Value;
}
set {
SCollection.Value = value;
}
}
public SerializableInterfacesCollection<ObservableCollection<A>> SCollection { get; set; }
}
public interface A {
string Str { get; set; }
int Int { get; set; }
// bad properties... very bad:
B B { get; set; }
ObservableCollection<B> Collection {get;set;}
}
public interface B {
string Label { get; set; }
string Value { get; set; }
}
public class AImpl: A {
public AImpl() {
SB = new SerializableInterface<B>();
SCollection = new SerializableInterfacesCollection<ObservableCollection<B>>(new ObservableCollection<B>());
}
[XmlAttribute()]
public string Type = typeof(AImpl).FullName;
public string Str {get;set;}
public int Int {get;set;}
[XmlIgnore()]
public B B {
get {
return SB.Value;
}
set {
SB.Value = value;
}
}
public SerializableInterface<B> SB;
[XmlIgnore()]
public ObservableCollection<B> Collection {
get {
return SCollection.Value;
}
set {
SCollection.Value = value;
}
}
public SerializableInterfacesCollection<ObservableCollection<B>> SCollection { get; set; }
}
public class BImpl01: B {
[XmlAttribute()]
public string Type = typeof(BImpl01).FullName;
public string Label {get;set;}
public string Value {get;set;}
}
public class BImpl02: B {
[XmlAttribute()]
public string Type = typeof(BImpl02).FullName;
public string Label {get;set;}
public string Value {get;set;}
}
Everything works fine if the A interface does not include "bad properties" (and of course they do not appear in the AImpl class). If it does than the collection's element does not deserialize and stops after deserializing first property of interface B.
Here are the wrappers:
public class SerializableInterface<T>: IXmlSerializable {
public SerializableInterface(T value) {
Value = value;
}
public SerializableInterface() { }
public T Value { get; set; }
public const string TypeAttr = "Type";
public const string NullAttrValue = "null";
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema() {
return null;
}
public virtual void ReadXml(System.Xml.XmlReader reader) {
if (!reader.HasAttributes)
throw new FormatException("expected a type attribute!");
string type = reader.GetAttribute(TypeAttr);
reader.Read(); // consume the value
if (type == NullAttrValue)
return;// leave T at default value
XmlSerializer serializer = new XmlSerializer(Type.GetType(type));
this.Value = (T)serializer.Deserialize(reader);
}
public virtual void WriteXml(System.Xml.XmlWriter writer) {
if (Value == null) {
writer.WriteAttributeString(TypeAttr, NullAttrValue);
return;
}
try {
var type = Value.GetType();
var ser = new XmlSerializer(type);
writer.WriteAttributeString(TypeAttr, type.FullName);
ser.Serialize(writer, Value);
}
catch (Exception e) {
// some logging
throw e;
}
}
#endregion
}
public class SerializableInterfacesCollection<T>: SerializableInterface<T> where T: IList, new() {
public SerializableInterfacesCollection() { }
public SerializableInterfacesCollection(T value)
: base(value) {}
#region IXmlSerializable Members
public override void ReadXml(System.Xml.XmlReader reader) {
try {
if (!reader.HasAttributes)
throw new FormatException("No " + TypeAttr + " in element");
string type = reader.GetAttribute(TypeAttr);
if (string.IsNullOrEmpty(type) || type == NullAttrValue || type != typeof(T).FullName)
return;
reader.Read();
Value = new T();
while (reader.NodeType != XmlNodeType.EndElement) {
string typename = reader.GetAttribute(TypeAttr);
if (string.IsNullOrEmpty(typename)) {
throw new FormatException("Collection element has to have " + TypeAttr + " attribute specifing its type");
}
Type t = Type.GetType(typename);
if (null == t.GetInterface(typeof(T).GetProperty("Item").PropertyType.FullName))
break;
XmlSerializer xs = new XmlSerializer(t);
var o = xs.Deserialize(reader);
Value.Add(o);
}
}
catch (Exception e) {
// some logging
throw e;
}
}
public override void WriteXml(System.Xml.XmlWriter writer) {
if (Value == null) {
writer.WriteAttributeString(TypeAttr, NullAttrValue);
return;
}
try {
writer.WriteAttributeString(TypeAttr, Value.GetType().FullName);
foreach (var el in Value) {
var ser = new XmlSerializer(el.GetType());
ser.Serialize(writer, el);
}
}
catch (Exception e) {
// some logging
throw e;
}
}
#endregion
}
and here is a method generating data for tests:
private Serialize makeA() {
Serialize result = new Serialize();
for (int i = 0; i < 10; ++i) {
A a = new AImpl() { Str = "str " + i, Int = i, B = makeB(i) };
for (int j = 0; j < 10; ++j) {
a.Collection.Add(makeB(j));
}
result.Collection.Add(a);
}
return result;
}
B makeB(int i) {
if (i % 2 == 0) {
return new BImpl01(){Label= "Blabel " + i, Value="value b"+i};
}
else {
return new BImpl02(){Label= "B2label " + i, Value="value b2"+i};
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Check if iphone has Square app installed - open or install In my code, I need to determine if an app has been installed on the iphone device or not (the app I need to check is Square). If the app isn't installed, I would to open the app directly to Square, and if it is installed, I would like to open Square. Is there a way to do this? I checked out this discussion: iphone - Check if an app is installed , but wasn't able to work it out. Since I was not a developer of Square, where do I get the information about the URL scheme?
Thanks.
A: It doesn't necessarily HAVE a scheme. The developers would have had to do that, and to have a reason to support incoming URLs. I don't know whether they've done that, or if they've documented it, or anything.
Assuming there's no documentation, then you can stab at it and see what you get. If you've got a guess at the scheme ("square:", perhaps?) you can test it with the canOpenUrl method of UIApplication:
UIApplication *app = [UIApplication sharedApplication];
if ([app canOpenURL:[NSURL URLWithString:@"square:"]]) {
NSLog(@"found it!");
}
If "square:" is a URL scheme that any app on the device has declared, this code will tell you so in the console.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Swing ignores first click after decreasing Windows time I have a Swing application that deals with date and time, so a lot of tests are done changing the system's date and time settings.
During the tests, we noticed that after decreasing the clock, the first click is ignored by the application.
Is it a bug of Swing/Java/Windows? Is there a workaround to this?
Interestingly, this issue only happens when decreasing the date/time settings. If I increase it, the application behaves normally.
Situation:
*
*Swing application running.
*Decrease Windows date and time settings (e.g. change time from 15:00 to 14:00).
*Notice that the first click in the Swing application does not fire any action.
Code example (you can use it to testify the situation):
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
final JFrame frame = new JFrame("frame");
final JButton button = new JButton("button");
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
System.out.println("Button Pressed!");
}
});
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
System.exit(0);
}
});
}
}
A: As seen here the Swing uses a date to check when the event occoured. So, in some way, probally a handler is acting here, by discarting your action, since it happened "before" the last action. I can't confirm you this, but probally some Layout Manager or another handler is messing with something here to prevent delayed events to mess up with the current flow.
A: I've debugged it via Eclipse and found out what is happening.
*
*Clock at 15:00h.
*Click at the button. Swing record last event time to 15:00.
*Change the clock to 14:00h.
*Click at the button. Swing ignores the event because it looks like a multi-click.
The problem here is that the comparison made by Swing checking for multi-click is this:
if (lastTime != -1 && currentTime - lastTime < multiClickThreshhold) {
shouldDiscardRelease = true;
Here, currentTime - lastTime yields a negative value. It's less than 0 (my multiClickThreshhold), so it does not fire the action event:
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
// Support for multiClickThreshhold
if (shouldDiscardRelease) {
shouldDiscardRelease = false;
return;
}
AbstractButton b = (AbstractButton) e.getSource();
ButtonModel model = b.getModel();
model.setPressed(false);
model.setArmed(false);
}
}
All the source listed above is in javax.swing.plaf.basic.BasicButtonListener.
The Button class does have a setMultiClickThreshhold, but it throws IllegalArgumentException in case the threshhold is less than 0.
So, as a workaround, I did this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.Field;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) throws Exception {
final JFrame frame = new JFrame("frame");
final JButton button = new JButton("button");
removeMulticlickThreshold(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
System.out.println("Button Pressed!");
}
});
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
System.exit(0);
}
});
}
private static void removeMulticlickThreshold(final JButton button) throws Exception {
final Field multiClickThreshhold = AbstractButton.class.getDeclaredField("multiClickThreshhold");
multiClickThreshhold.setAccessible(true);
multiClickThreshhold.set(button, Long.MIN_VALUE);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Using the appengine datastore admin to move data to a new application - how long should this take? I am moving to the high-replication datastore which is relatively simple when using the AppEngine Datastore Admin feature to copy all data from the old application to the high-replication application.
However, I have several applications (and started by copying applications with smaller databases), and have seen that the rate of copy is about 1Gb every two hours. This is acceptable for some of my applications, however I am now going to be moving an application with about 14GB of data, and would prefer to not have to shut down my website for more than a day while transferring the data.
Is there any way to make this process go faster? Are these data transfer speeds typical for the Datastore Admin tool?
Kind Regards
A: Google are working on a new migration tool, which will allow a shorter read-only period while migrating.
They mentioned it when 1.5.3 was released:
http://googleappengine.blogspot.com/2011/08/app-engine-153-sdk-released.html
You can try signing up for early access to the migration tool here:
https://docs.google.com/spreadsheet/viewform?authkey=CLXR0LMN&formkey=dERMcDZuMnlycHoyZDd4Vy1PNXlhWlE6MQ&ndplr=1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: mod_perl debugging & viewing source I've recently started work on a project that uses mod_perl. I'm attempting to use the Perl debugger to debug some Perl scripts that are running under mod_perl. I start the debugger with the following command:
sudo OPTIONS="-X -DPERLDB" /etc/init.d/httpd restart
The relevant debugging section of perl.conf (included by httpd.conf) is:
<IfDefine PERLDB>
<Perl>
use Apache::DB ();
Apache::DB->init;
</Perl>
<Location />
PerlFixupHandler Apache::DB
</Location>
</IfDefine>
That takes me into the debugger. When I load the required page in the browser, the debugger breaks on the first line of the Perl script that has been wrapped by mod_perl (the app is using PerlRun, btw). I can now step through the code, print variables, and so on.
My problem is that the commands to view source code (l, - and v), don't display anything when inside a Perl script. They work as expected inside a module - that is, if the code steps into a module that is used by the Perl script, the view source commands work.
Is this a known problem with debugging in mod_perl? Is there anything I can do to fix it?
I'm using Apache 2.2.3 and Perl 5.8.8 on CentOS 5.6 x86_64.
A: I've ran into the problem before, and have an educated guess about the problem. My current working theory is that the debugger doesn't show the code that perl parsed, because perl already threw it away during the compile phase. Instead, the debugger looks through relative paths to get the source code from the actual file. However, the debugger starts looking from the Apache server root, which may not be the same as where you started Apache. When it can't find the file, it shows up as a bunch of blank lines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to send my program to background while a certain process is running I have a program that starts another program (iexplore.exe), then my program should go "invisible" or atlast to background, and stay there while this asd.exe is running. This code is working, BUT it eats memory, and sometimes its just stays hiden while asd.exe is not running anymore. There must be a more efficient way to do this =)
So my program code :
this.Hide();
Process.Start(Path.Combine(Path, "iexplore.exe"));
Process[] Running_ = null;
do
{ // this loops eats memory!
System.Threading.Thread.Sleep(500);
Running_ = null;
Running_ = Process.GetProcessesByName("iexplore");
}while (Running_.Length > 0);
this.Show();
A: You'll want to use the Process.Exited event here, prevents blocking the UI thread and avoids hassling threads. Like this:
private void button1_Click(object sender, EventArgs e) {
var prc = new Process();
prc.EnableRaisingEvents = true;
prc.Exited += processExited;
prc.StartInfo = new ProcessStartInfo("notepad.exe");
prc.Start();
this.Hide();
}
private void processExited(object sender, EventArgs e) {
this.BeginInvoke(new Action(() => {
this.Show();
this.BringToFront();
}));
}
A: What about the Process.WaitForExit method?
this.Hide();
Process p = Process.Start(Path.Combine(WoWPath, "asd.exe"));
p.WaitForExit();
this.Show();
A: I like what MatthiasG has done, but WaitForExit() is a blocking call...Your program will be hidden until asd.exe finishes executing, but your program will not be doing anything productive.
This may be the desired result. If not, I would
*
*Hide the form -> this.Hide();
*Create a thread (BackgroundWorker will suffice)... In the DoWork() event, create the Process object for asd (as MatthiasG had done):
Process p = Process.Start(Path.Combine(WoWPath, "asd.exe"));
p.WaitForExit();
*In the RunWorkerCompleted event, have this.Show();
A: *
*No need to null WoWRunning_. Process.GetProcessesByName changes the reference anyways
*Call .Dispose() !
A: You need to call Dispose() on each object in your array, then it stops to eat memory.
I mean instead of WoWRunning_ = null; put there something like foreach(Process p in WoWRunning_) p.Dispose();
But anyway your algorithm should be revised completely, it is quite expensive because you load an array of all processes again and again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: "popover" problems on twitter bootstrap css/javascript library I've tried to implement popover javascript on my site with twitter bootstrap and i couldn't. If anyone could help me with my code, i would appreciate a lot. thanks in advance for that.
<head>
...
<script src="scripts/jquery.min.js"></script>
<script src="scripts/html5.js"></script>
<script src="scripts/bootstrap-tabs.js"></script>
<script src="scripts/bootstrap-alerts.js"></script>
<script src="scripts/bootstrap-popover.js"></script>
<script src="scripts/bootstrap-twipsy.js"></script>
<script src="scripts/bootstrap-modal.js"></script>
<script src="1.3.0/bootstrap-scrollspy.js"></script> -->
<link rel="stylesheet" href="bootstrap.css" />
...
</head>
<body>
...
<div class="tab-content">
<div class="active" id="dwcenter_iso">
<table class="zebra-striped">
<thead>
<tr>
<th>Arquivo</th>
<th>Tamanho</th>
<th>Data</th>
<th>md5</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="download.php">nimbus-opensource-backup-1.1.iso</a> <span class="label success">new</span></td>
<td>332M</td>
<td>16/09/11</td>
<!-- HERE GOES -->
<td><a href="#" class="btn danger" rel="popover" title="md5 Check Sum" data-content="343453453453453rfef34">ver</a>
<script>
$(function () {
$('a[rel=popover]')
.popover({
html: true
})
.click(function(e) {
e.preventDefault()
})
})
</script>
</td>
</tr>
<tr>
<td>nimbus-opensource-backup-1.0.iso <span class="label important">deprecated</span></td>
<td>332M</td>
<td>10/08/11</td>
<td>ver</td>
</tr>
<tr>
<td>nimbus-opensource-backup-0.9beta.iso <span class="label important">deprecated</span></td>
<td>380MB</td>
<td>25/09/10</td>
<td>ver</td>
</tr>
</tbody>
</table>
</div>
...
</body>
i have tried "html: true" and the bootstrap doc example "offset: 10".
It does shows the red danger button, but nothing happens then (the popover doesn't work).
And something else, how could i implement this on the TD element of the table rather than the button?
A: Change these 2 scripts around as popover is an extension of twipsy and needs to be loaded first...
<script src="scripts/bootstrap-twipsy.js"></script>
<script src="scripts/bootstrap-popover.js"></script>
You don't need to set html to true, here's mine with options you can change if you wish
$(function(){
$(".btn").popover({
offset: 5,
placement: 'left'
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: AJAX asynchronous response callbacks I have been working with AJAX for a while now, but in limited and simple ways. I use JQuery
Currently I am debugging a web application. The client side code uses JavaScript and JQuery. I noticed that in this application it is possible to have multiple AJAX requests sent out at the same time (one right after the other). My concern is that because AJAX is asynchronous that the AJAX request might not be completed in the correct order. I was wondering if the proper AJAX callbacks will be executed regardless of witch response is returns first or the call back functions are executed in FIFO manner
Let me elaborate
I have 2 AJAX requests A and B. Both A and B have there own call back functions. The app first makes request A then immediately afterward makes request B. Now the App expects A to return first. Now my question is what if B returns first. Which Call back will be executed?
I did some research and could not find any info on this issue. So I assumed that the browser would coordinate the callbacks. To make sure I wrote a little test. My test showed that regardless of which response returns first the first requests call back is always used first.
My question is what is the behavior? Also what techniques or methods are used to avoid such a case.
A: Look at the jQuery promise/deferred objects, they allow you to control this exact behavior.
$.when( $.ajax("test.aspx") ).then( $.ajax("test2.aspx") );
http://api.jquery.com/category/deferred-object/
A: As you described the flow - if the request B returns first, then its callback will be called first.
You can always call the second ajax request when the first one suceed, for example:
function callbackA() { return true; }
function callbackB() { return true; }
$.ajax({url: '/my/url', data: {mydata: mydata}, success: function(data) {
callbackA(data);
$.ajax({url: '/my/url2', data: {mydata2: mydata2}, success: function(data) {}
callbackB(data);
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: delay qTip call using setTimeout and clearTimeout This was working fine:
$('#panel_derecho a.tooltip').each(function(){
$(this).qtip({
content: { url: '/includes/qtip.php?'+$(this).attr('rel')+' #'+$(this).attr('div'), text:'<center><img src="/images/loader.gif" alt="loading..." /></center>' },
show: { delay: 700, solo: true,effect: { length: 500 }},
hide: { fixed: true, delay: 200 },
position: {
corner: {
target: 'topLeft',
tooltip: 'middleRight'
}
},
style: {
name: 'light',
width: 700,
padding: 0,border: {
width: 4,
radius: 3,
color: '#5588CC'
}
}
});
});
but sometimes the user hovered while scrolling down the page and many calls to qtip that won't be shown where called so thought that adding a timeout was best go (isn't it?)
so i tried to set delayTip var with time to wait (while hover) and to clear it when mouse out:
$('#panel_derecho a.tooltip').each(function(){
var delayTip;
$(this).bind('mouseover',function(){
delayTip = setTimeout(function () {
$(this).qtip({
content: { url: '/includes/qtip.php?'+$(this).attr('rel')+' #'+$(this).attr('div'), text:'<center><img src="/images/loader.gif" alt="loading..." /></center>' },
show: { delay: 700, solo: true,effect: { length: 500 }},
hide: { fixed: true, delay: 200 },
position: {
corner: {
target: 'topLeft',
tooltip: 'middleRight'
}
},
style: {
name: 'light',
width: 700,
padding: 0,border: {
width: 4,
radius: 3,
color: '#5588CC'
}
}
});
}, 500);
};
$(this).bind('mouseout',function(){ clearTimeout(delayTip); });
});
the ting is that the tooltip is not shown and no errors are jumping in firebug,
what am I missing?
A: When the timeout fires the this keyword refers to the global object (most likely the window), try to do something like this:
$('#panel_derecho a.tooltip').each(function(){
var delayTip = 0;
var self = $(this);
self.bind('mouseover',function(){
if (delayTip === 0) delayTip = setTimeout(function () {
self.qtip({
content: { url: '/includes/qtip.php?'+self.attr('rel')+' #'+self.attr('div'), text:'<center><img src="/images/loader.gif" alt="loading..." /></center>' },
show: { delay: 700, solo: true,effect: { length: 500 }},
hide: { fixed: true, delay: 200 },
position: {
corner: {
target: 'topLeft',
tooltip: 'middleRight'
}
},
style: {
name: 'light',
width: 700,
padding: 0,border: {
width: 4,
radius: 3,
color: '#5588CC'
}
}
});
delayTip = 0;
}, 500);
};
self.bind('mouseout',function(){ clearTimeout(delayTip); delayTip = 0; });
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting Date range picker variables OnClose I'm trying to get the StartDate and EndDate variables of the date range picker when the OnClose function is called, however I am having difficulties.
I replaced
onClose: function(){},
with
onClose: alertdata,
However that already breaks the daterange picker and I cannot pick dates anymore.
According to the documentation, there already are variables set dateStart and dateEnd, so what I was going to do is this:
function alertData() {
$("#DivDateStart").html(dateStart); //update div for debugging
$("#DivDateEnd").html(dateEnd); //update div for debugging
}
And then just use those variables in a POST method to send all that to a PHP file. Here is what I have now, I would be grateful if someone let me know where I made a mistake in getting the data, thanks!
A: Try accessing each datepicker individually to get the selected dates like so:
onClose:function(){
var startDate = $('#startDatePickerID').datepicker("getDate");
var endDate = $('#endDatePickerID').datepicker("getDate");
}
Here is a live example: http://jsfiddle.net/Rex3q/1/
Update (based on comments)
You can retrieve the start and end dates by modifying the source of the daterangepicker.jQuery.js file.
Replace the hideRP function with the function below:
function hideRP() {
if (rp.data('state') == 'open') {
rp.data('state', 'closed');
rp.fadeOut(300);
var startDate = rp.find('.range-start').datepicker('getDate');
var endDate = rp.find('.range-end').datepicker('getDate');
options.onClose(startDate, endDate);
}
}
This will retrieve the start and end date from the individual datepickers and pass them to the onClose function.
Then when you initialise the daterangepicker, specify the onClose function like below:
$('#rangePickerID').daterangepicker(
{
arrows: true,
onClose: function (startDate, endDate) {
alert(startDate);
alert(endDate);
}
});
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Screen resolution change notification message? I have a WTL app running and would like to know when the screen resolution has changed. The most likely candidate would appear to be SPI_SETWORKAREA sent via the WM_SETTINGCHANGE message but I wondered if this is the correct message to use. This has to work on XP and Windows 7.
A: WM_DISPLAYCHANGE is the better mouse trap.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Set match function in a mysql query with Java I have the following excerpt from a query (mysql) made in java:
queryGeral.append("FROM product p, fabricante_product fp, fabricante f, extensao e, product_autor pa ")
.append(" WHERE ")
.append("a.nome like ? AND ")
.append("p.cod_material = pa.cod_material AND ")
.append("f.fabricante = fp.fabricante AND ")
.append("p.cod_material = fp.cod_material AND ")
.append("e.id_extensao = p.id_extensao ");
necessary to put the MATCH function (and perhaps AGAINST) to detail my research when I put it in the code above, the missing parameters mysql says, I'm trying to do like this below, but does not work:
queryGeral.append("FROM product p, fabricante_product fp, fabricante f, extensao e, product_autor pa ")
.append(" WHERE ")
.append("MATCH p.name AND ")
.append("a.nome like ? AND ")
.append("p.cod_material = pa.cod_material AND ")
.append("f.fabricante = fp.fabricante AND ")
.append("p.cod_material = fp.cod_material AND ")
.append("e.id_extensao = p.id_extensao ");
I need to put the function in this query MATCH..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Autofac Webform Integration: Manual Property Injection Consider this autofac registration module for a webform MVP style application, where I register a couple of components by providing some parameters dependency.
public class SampleModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<FooService>().As<IFooService>();
builder.Register<FooPresenter>((c, p) =>
new FooPresenter(p.Named<IFooView>("view"),
c.Resolve<IFooService>(p),
p.Named<string>("connectionString")))
.InstancePerHttpRequest();
base.Load(builder);
}
}
In the page I can resolve the type using some code like this:
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
var cpa = (IContainerProviderAccessor) HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
// Resolve presenter
var presenter = cp.RequestLifetime.Resolve<FooPresenter>(
new NamedParameter[]
{
new NamedParameter("connectionString", "xyz"),
new NamedParameter("view", this)
});
}
But I would really like to use property injection and manage the dependency on the parameters at that level; Something like this for example:
public FooPresenter Presenter { get; set; }
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
var cpa = (IContainerProviderAccessor) HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
// Parameters bindings?
cp.RequestLifetime.InjectProperties(this);
}
Is there something that I can leverage on Autofac? Thanks in advance.
A: Yes, there is ASP.NET integration which will inject page-level properties.
See the "Add Modules to Web.config" section here:
http://code.google.com/p/autofac/wiki/AspNetIntegration
Edit: Sorry for misunderstanding the question. I see now that you are not asking if property injection is available, but rather how to use it in conjunction with named parameters.
I am going to make an inference and say the reason you need named parameters is solely to pass the view to the presenter. The connection string shouldn't really be the page's responsibility; you can probably make that a property on SampleModule and read it from there.
I have a preferred approach to MVP/Autofac which has been battle-tested for years. It is clean, provides some nice extension points, and keep pages relatively free of implementation details. You can find the overview in my answer to this question:
Injecting Lower Layer Dependency in Presenter in an ASP.NET MVP Application
A: This works and is automatic in Autofac
<Autofac.Integration.Web.Forms.InjectUnsetProperties()>
Public MustInherit Class ViewBasePage(Of TPresenter As BasePresenter(Of TView, TPresenter), TView As {IView, Class})
Inherits System.Web.UI.Page
Implements IView
Protected _presenter As TPresenter
Private _factory As Func(Of TView, TPresenter)
Public Property PresenterFactory As Func(Of TView, TPresenter)
Get
Return _factory
End Get
Set(value As Func(Of TView, TPresenter)
_factory = value
_presenter = _factory(DirectCast(DirectCast(Me, IView), TView))
End Set
End Property
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: android getHeight()/getWidth with RelativeLayout Hi I'm new to Android and am facing the problem: how do I get the Height/Width of a view, which is placed in a relative layout? I tried getHeight() and getWidth() and both return 0.
I need to know whether this view has reached the end of the Layout so that I can place the next view to its right or below it.
or maybe there is a better way to do this without knowing the position of the current view?
edit:
I use this code to create an EditText and add it to the layout:
EditText et1 = new EditText(context);
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.RIGHT_OF,curView.getId());
et1.setLayoutParams(p);
et1.setId(loopid++);
curLayout.addView(et1);
curView=et1;
and then call:
int[] location=new int[2];
curView.getLocationOnScreen(location);
Log.d("right:", String.valueOf(location[1]));
and it shows a 0.
A: You are calling getHeight()/getWidth() before the view can be laid out so it is returning 0. If you call it later in the lifecycle it will stop this issue.
A: Once your views are created, the UIThread inflates them. So when you instanciate them they have no size.
try using
ViewTreeObserver vto = curView.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
{
public boolean onPreDraw()
{
curView.getLocationOnScreen(location);
}
}
Not sure if it'll work though
A: final Button button = new Button(this);
button.setText("123");
TextPaint paint = button.getPaint();
float len = paint.measureText(button.getText().toString());
This len will give buttons width after plus a fixed value
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: linux search multiple word in a files I have a folder containing a set of text files.
-Folder
--- file 1
--- file 2
--- file 3
--- file 4
I have a set of word that i want to check if are inside. {word1, username, blah blahblah}
Is there a way on a single command to discover which of these file contains all the word within my list?
I saw it's possible to use some and with grep but i think they work on a single line while in my case the wors are always on different lines.
the number of word is static. are always 3 or 4 so if needed i can hard code them in the command.
EDIT:
They are in AND. a file is not accepted if does not have ALL of them inside!
i would like to avoid doing
egrep -l 'word1' .| xargs egrep -l 'word2'
Is there a better solution to call grep just once?
Cheers,
Ste
A: Does this work for you?
grep -IRE 'word1|username|blah blahblah' /path/to/files/ |
sed -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P' |
awk -F: '$1!=p{if(b"" && c > 2)print b; p=$1;c=0;b=s=""}{b=b s $0;s=RS;c++}END
{if(b"" && c > 2)print b}' | awk -F: '{print $1}' | sort -u
The first part (grep) will list all the file names with matching pattern. The second part (sed) will strip the duplicates from the first output giving only distinct rows. The third part will only show the file which occurs more than once and the forth one will strip your matched pattern and the last one will only serve you the file name my friend.
my head hurts now ...
A: use:
grep -f words.txt input
Example:
$ cat words
word1
username
blah blahbla
a
word1
username blah blahblah
b
username blah blahblah
c
word1
d
word1, username, blah blahblah}
$ grep -f words.txt *
a:word1
a:username blah blahblah
b:username blah blahblah
c:word1
d:word1, username, blah blahblah}
A: Use grep:
grep -E '(word1|username|blah blahblah)' Folder/*
the -E flag puts grep into 'extended' mode for regular expressions. This will by default show the filename AND the matching text. If you want just the filename, add -l to the options.
A: Another solution, which works best for a small set of words:
grep -e word1 -e username -e "blah blahblah" Folder/*
A: The following if you want to grep into a directory tree
egrep -E '{word1|username|blah blahblah)' `find . -type f -print`
I suggest you also to use the term directory instead of folder when you are searching for answers about *nix systems :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: `Out of resources` error while doing loop unrolling When I increase the unrolling from 8 to 9 loops in my kernel, it breaks with an out of resources error.
I read in How do I diagnose a CUDA launch failure due to being out of resources? that a mismatch of parameters and an overuse of registers could be a problem, but that seems not be the case here.
My kernel calculates the distance between n points and m centroids and selects for each point the closest centroid. It works for 8 dimensions but not for 9. When I set dimensions=9 and uncomment the two lines for the distance calculation, I get an pycuda._driver.LaunchError: cuLaunchGrid failed: launch out of resources.
What do you think, could cause this behavior? What other iusses can cause an out of resources*?
I use an Quadro FX580. Here is the minimal(ish) example. For the unrolling in the real code I use templates.
import numpy as np
from pycuda import driver, compiler, gpuarray, tools
import pycuda.autoinit
## preference
np.random.seed(20)
points = 512
dimensions = 8
nclusters = 1
## init data
data = np.random.randn(points,dimensions).astype(np.float32)
clusters = data[:nclusters]
## init cuda
kernel_code = """
// the kernel definition
__device__ __constant__ float centroids[16384];
__global__ void kmeans_kernel(float *idata,float *g_centroids,
int * cluster, float *min_dist, int numClusters, int numDim) {
int valindex = blockIdx.x * blockDim.x + threadIdx.x ;
float increased_distance,distance, minDistance;
minDistance = 10000000 ;
int nearestCentroid = 0;
for(int k=0;k<numClusters;k++){
distance = 0.0;
increased_distance = idata[valindex*numDim] -centroids[k*numDim];
distance = distance +(increased_distance * increased_distance);
increased_distance = idata[valindex*numDim+1] -centroids[k*numDim+1];
distance = distance +(increased_distance * increased_distance);
increased_distance = idata[valindex*numDim+2] -centroids[k*numDim+2];
distance = distance +(increased_distance * increased_distance);
increased_distance = idata[valindex*numDim+3] -centroids[k*numDim+3];
distance = distance +(increased_distance * increased_distance);
increased_distance = idata[valindex*numDim+4] -centroids[k*numDim+4];
distance = distance +(increased_distance * increased_distance);
increased_distance = idata[valindex*numDim+5] -centroids[k*numDim+5];
distance = distance +(increased_distance * increased_distance);
increased_distance = idata[valindex*numDim+6] -centroids[k*numDim+6];
distance = distance +(increased_distance * increased_distance);
increased_distance = idata[valindex*numDim+7] -centroids[k*numDim+7];
distance = distance +(increased_distance * increased_distance);
//increased_distance = idata[valindex*numDim+8] -centroids[k*numDim+8];
//distance = distance +(increased_distance * increased_distance);
if(distance <minDistance) {
minDistance = distance ;
nearestCentroid = k;
}
}
cluster[valindex]=nearestCentroid;
min_dist[valindex]=sqrt(minDistance);
}
"""
mod = compiler.SourceModule(kernel_code)
centroids_adrs = mod.get_global('centroids')[0]
kmeans_kernel = mod.get_function("kmeans_kernel")
clusters_gpu = gpuarray.to_gpu(clusters)
cluster = gpuarray.zeros(points, dtype=np.int32)
min_dist = gpuarray.zeros(points, dtype=np.float32)
driver.memcpy_htod(centroids_adrs,clusters)
distortion = gpuarray.zeros(points, dtype=np.float32)
block_size= 512
## start kernel
kmeans_kernel(
driver.In(data),driver.In(clusters),cluster,min_dist,
np.int32(nclusters),np.int32(dimensions),
grid = (points/block_size,1),
block = (block_size, 1, 1),
)
print cluster
print min_dist
A: You're running out of registers because your block_size (512) is too large.
ptxas reports that your kernel uses 16 registers with the commented lines:
$ nvcc test.cu -Xptxas --verbose
ptxas info : Compiling entry function '_Z13kmeans_kernelPfS_PiS_ii' for 'sm_10'
ptxas info : Used 16 registers, 24+16 bytes smem, 65536 bytes cmem[0]
Uncommenting the lines increases register use to 17 and an error at runtime:
$ nvcc test.cu -run -Xptxas --verbose
ptxas info : Compiling entry function '_Z13kmeans_kernelPfS_PiS_ii' for 'sm_10'
ptxas info : Used 17 registers, 24+16 bytes smem, 65536 bytes cmem[0]
error: too many resources requested for launch
The number of physical registers used by each thread of a kernel limits the size of blocks you can launch at runtime. An SM 1.0 device has 8K registers that can be used by a block of threads. We can compare that to your kernel's register demands: 17 * 512 = 8704 > 8K. At 16 registers, your original commented kernel just squeaks by: 16 * 512 = 8192 == 8K.
When no architecture is specified, nvcc compiles kernels for an SM 1.0 device by default. PyCUDA may work the same way.
To fix your problem, you could either decrease block_size (to say, 256) or find a way to configure PyCUDA to compile your kernel for an SM 2.0 device. SM 2.0 devices such as your QuadroFX 580 provide 32K registers, more than enough for your original block_size of 512.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do you localize the message of Ext.LoadMask? How do you localize the msg of Ext.LoadMask? I tried using Ext.override, but my gridpanel loading from a store still shows Loading... instead of the text I provided.
A: you don't have to override loadMask, you can set the text of the loading mask on the grid view. Just add the view config to your grid
viewConfig: {
loadingText: 'your special text'
}
Edit
You can override the grid view if you wan't the same text for all your grids
Ext.override(Ext.grid.View,{
loadingText: 'your special text'
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: regular expression to select after n number of occurences of certain character Creating some regex expressions here. I was wondering if I could get some pointers on how to go about selecting a string after n occurences of one character and before the next occurence of a certain char.
for instance
xyz|yui|i want to select this.
In this example I am wanting to select after the 2nd "|" and before the next ".". So the text I want to match is "i want to select this".
I appreciate any pointers thanks.
UPDATE
To be more specific on why I need to do this above, there is more text after the period at the end of "I want to select this.". Basically this is undelimited content which I am trying to delimit. Thusfar I have been able to delimt the first two fields, now I need to be able to select only text after the last "|" and before the next period and add a "|" character to the end. So the desired result would be
xyz|yui|i want to select this.|
Sorry for not being more specific on the outcome and I hope this clears it up a bit. Thanks for the info, its super.
A: Your regex would look like this:
/^(?:.+?\|){2}(.+?[^(Co)]\.)/
PHP
<?php
preg_match('/^(?:.+?\|){2}(.+?[^(Co)]\.)/','xyz|yui|This is a Co. sentence. Ending before this clause.',$out);
echo $out[1];
?>
HOWEVER
You should explode by the pipe character and access the respective information like that:
$stuff = explode('|','xyz|yui|i want to select this.');
echo $stuff[2];
A: First you need to create a group which contains the repeating part ([^|]+\|) here, which can be set to appear exactly two times {2}, then you need to match the rest (.*):
^([^|]+\|){2}(.*?)\.
Update
You can ungroup it as @Karolis mentioned with ?:
^(?:[^|]+\|){2}(.*?)\.
WIth the first regexp the second match will be yours, with the second it will be the first.
A: This will do it:
$text = 'xyz|yui|i want to select Co. this. But not this.';
$re = '/# Match stuff after nth occurance of a char.
^ # Anchor to start of string.
(?:[^|]*\|){2} # Everything up through 2nd "|"
( # $1: Capture up through next "."
[^.]* # Zero or more non-dot.
(?: # Allow dot if in "Co.".
(?<=Co) # If dot is preceded by "Co",
\. # then allow this dot.
[^.]* # Zero or more non-dot.
)* # Zero or more "Co." dots allowed.
\. # First dot that is not "Co."
) # End $1: Capture up through next "."
/ix';
$text = preg_replace($re, '$0|', $text);
echo $text;
Edit 2011-09-28 10:00 MDT: Added ability to skip over dots in: "Co."
Edit 2011-09-28 10:30 MDT: Changed to use preg_replace() to insert | after dot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7584968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.