text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Setting up a relative dimension? I have a pretty simple scenario but a very large data set (using even simpler example below to illustrate my issue).
Let's say i have a cube comprised of Country table(fact) that has one dimension called Continent.
With this, i can aggregate country data by continent.
But let's say each country has a city:
Here i can't assign Continent dimension directly to city, because city does not have a continent property. This is a simplified example, and it would be trivial to join Country information in while populating the city fact table. However, my application is using a very large dataset that requires a long time to query, and i am trying to avoid having to make a join on Country to get the continent id. I need to be able to write simple MDX query to get population count by country or by city.
How can i set up my cube, so that dimension relationship in above scenario can be set up between city and continent, without adding continentID to city?
Update
As Brian suggested, i could make country a dimension. This is how i did it initially, and perhaps i didn't do it correctly but it was a performance hit because: Above example is simple, but in my case, i have 15 properties (such as continent above) that i need to aggregate my data on. If i create a country dimension, and specify those 15 properties as dimensional attributes, every time i process my cube, it will do a "select distinct continent from country" x15 (once per each attribute) in order to get that distinct list of continents. if Country table is huge (which in my case it is a view comprised of many big tables), it will take a very long time just to get that list of distinct values per dimension.
my attempt above is just a way to work around this problem, and have separate table per dimension that i could easily manage. my only problem is that i have sub views which need to be aggregated on those properties, while the properties do not exist on sub tables and need to be looked up from "country" view etc..
A: It doesn't look like the dimensional model was thought through very well.
A band aid to fix the problem would be a Country Dimension. Country is common to both Country and City.
I'm sure the problem is much more complex than this, but you've listed a very simple issue.
AFAIK, no amount of MDX (or any other technology) can overcome bad design problems. The dimensional model is the foundation of data warehouse performance. It's very important to get it right early.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: python - Read file from and to specific lines of text I'm not talking about specific line numbers because i'm reading multiple files with the same format but vary in length.
Say i have this text file:
Something here...
... ... ...
Start #I want this block of text
a b c d e f g
h i j k l m n
End #until this line of the file
something here...
... ... ...
I hope you know what i mean. i was thinking of iterating through the file then search using regular expression to find the line number of "Start" and "End" then use linecache to read from Start line to End line.
But how to get the line number? what function can i use?
A: Here's something that will work:
data_file = open("test.txt")
block = ""
found = False
for line in data_file:
if found:
block += line
if line.strip() == "End": break
else:
if line.strip() == "Start":
found = True
block = "Start"
data_file.close()
A: If you simply want the block of text between Start and End, you can do something simple like:
with open('test.txt') as input_data:
# Skips text before the beginning of the interesting block:
for line in input_data:
if line.strip() == 'Start': # Or whatever test is needed
break
# Reads text until the end of the block:
for line in input_data: # This keeps reading the file
if line.strip() == 'End':
break
print line # Line is extracted (or block_of_lines.append(line), etc.)
In fact, you do not need to manipulate line numbers in order to read the data between the Start and End markers.
The logic ("read until…") is repeated in both blocks, but it is quite clear and efficient (other methods typically involve checking some state [before block/within block/end of block reached], which incurs a time penalty).
A: You can use a regex pretty easily. You can make it more robust as needed, below is a simple example.
>>> import re
>>> START = "some"
>>> END = "Hello"
>>> test = "this is some\nsample text\nthat has the\nwords Hello World\n"
>>> m = re.compile(r'%s.*?%s' % (START,END), re.S)
>>> m.search(test).group(0)
'some\nsample text\nthat has the\nwords Hello'
A: This should be a start for you:
started = False
collected_lines = []
with open(path, "r") as fp:
for i, line in enumerate(fp.readlines()):
if line.rstrip() == "Start":
started = True
print "started at line", i # counts from zero !
continue
if started and line.rstrip()=="End":
print "end at line", i
break
# process line
collected_lines.append(line.rstrip())
The enumerate generator takes a generator and enumerates the iterations.
Eg.
print list(enumerate("a b c".split()))
prints
[ (0, "a"), (1,"b"), (2, "c") ]
UPDATE:
the poster asked for using a regex to match lines like "===" and "======":
import re
print re.match("^=+$", "===") is not None
print re.match("^=+$", "======") is not None
print re.match("^=+$", "=") is not None
print re.match("^=+$", "=abc") is not None
print re.match("^=+$", "abc=") is not None
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Sharing JS objects between HTML frames in IE8/IE9 I have to bring support for IE8/IE9 to an application which was built specifically for IE6 and uses HTML frames (framesets) a lot. Application has a lot of JavaScript code where "navigator.PropertyABC" is used. Here "PropertyABC" is an object initialized in one of frames and used in many other frames. This worked in IE6 because "navigator" object seems to be shared in IE6 between all of the frames. It also works with IE7 compatibility mode. But it does not work in IE8/IE9.
There are frames nested into other frames, so it's multi-level.
Sample code:
<html>
<frameset rows="50%,50%">
<frame name="a" src="frame1.html">
<frame name="b" src="frame2.html">
</frameset>
</html>
frame1.html:
<html>
<body>
<script type="text/javascript">
navigator.testingSharedVariable ="1st frame!";
</script>
</body>
</html>
frame2.html:
<html>
<body>
<input type="button" onclick="alert(navigator.testingSharedVariable)">
</body>
</html>
When clicked on a button in IE6 - alert with "1st frame!" is raised. On IE8/IE9 - "undefined".
Is there anything else I could use to share objects between frames instead of "navigator"?
Other browser support is not required, just IE8/IE9.
A: Use the standard global object – window. In your case the shared global object would be window.top (which is a window itself).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to disable browser developer tools? I'm developing a web application and since it has access to a database underneath, I require the ability to disable the developer tools from Safari, Chrome, Firefox and Internet Explorer and Firebug in Firefox and all similar applications. Is there a way to do this?
Note: The AJAX framework provided by the database requires that anything given to the database to be in web parameters that can be modified and that anything it returns be handled in JavaScript. Therefore when it returns a value like whether or not a user has access to a certain part of the website, it has to be handled in JavaScript, which developer tools can then access anyway. So this is required.
UPDATE: For those of you still thinking I'm making bad assumptions, I did ask the vendor. Below is their response:
Here are some suggestions for ways of mitigating the risk:
1) Use a javascript Obfuscator to obfuscate the code and only provide
the obfuscated version with the sold application; keep the non
obfuscated version for yourself to do edits. Here is an online
obfuscator:
How can I obfuscate (protect) JavaScript?
http://en.wikipedia.org/wiki/Obfuscated_code
http://javascriptobfuscator.com/default.aspx
2) Use a less descriptive name; maybe 'repeatedtasks.js' instead of
'security.js' as 'security.js' will probably stand out more to anyone
looking through this type of information as something important.
A: you cannot disable the developer tool. but you can annoys any one who try to use the developer tool on your site, try the javascript codes blow, the codes will break all the time.
(function () {
(function a() {
try {
(function b(i) {
if (('' + (i / i)).length !== 1 || i % 20 === 0) {
(function () { }).constructor('debugger')()
} else {
debugger
}
b(++i)
}
)(0)
} catch (e) {
setTimeout(a, 5000)
}
}
)()
}
)();
A: If your framework requires that you do authorization in the client, then...
You need to change your framework
When you put an application in the wild, where users that you don't trust can access it; you must draw a line in the sand.
*
*Physical hardware that you own; and can lock behind a strong door. You can do anything you like here; this is a great place to keep your database, and to perform the authorization functions to decide who can do what with your database.
*Everything else; Including browsers on client computers; mobile phones; Convenience Kiosks located in the lobby of your office. You cannot trust these! Ever! There's nothing you can do that means you can be totally sure that these machines aren't lying to cheat you and your customers out of money. You don't control it, so you can't ever hope to know what's going on.
A: Update at the time (2015) when this answer was posted, this trick was possible. Now (2017) browsers are mature. Following trick no longer works!
Yes it is possible. Chrome wraps all console code in
with ((console && console._commandLineAPI) || {}) {
<code goes here>
}
... so the site redefines console._commandLineAPI to throw:
Object.defineProperty(console, '_commandLineAPI',
{ get : function() { throw 'Nooo!' } })
This is the main trick!
A: In fact this is somehow possible (how-does-facebook-disable-developer-tools), but this is terribly bad idea for protecting your data. Attacker may always use some other (open, self written) engines that you don't have any control on. Even javascript obfuscation may only slow down a bit cracking of your app, but it also gives practically no security.
The only reasonable way to protect your data is to write secure code on server side.
And remember, that if you allow someone to download some data, he can do with it whatever he wants.
A: There's no way your development environment is this brain-dead. It just can't be.
I strongly recommend emailing your boss with:
*
*A demand for a week or two in the schedule for training / learning.
*A demand for enough support tickets with your vendor to figure out how to perform server-side validation.
*A clear warning that if the tool cannot do server-side validation, that you will be made fun of on the front page of the Wall Street Journal when your entire database is leaked / destroyed / etc.
A: No. It is not possible to disable the Developer Tools for your end users.
If your application is insecure if the user has access to developer tools, then it is just plain insecure.
A: $('body').keydown(function(e) {
if(e.which==123){
e.preventDefault();
}
if(e.ctrlKey && e.shiftKey && e.which == 73){
e.preventDefault();
}
if(e.ctrlKey && e.shiftKey && e.which == 75){
e.preventDefault();
}
if(e.ctrlKey && e.shiftKey && e.which == 67){
e.preventDefault();
}
if(e.ctrlKey && e.shiftKey && e.which == 74){
e.preventDefault();
}
});
!function() {
function detectDevTool(allow) {
if(isNaN(+allow)) allow = 100;
var start = +new Date();
debugger;
var end = +new Date();
if(isNaN(start) || isNaN(end) || end - start > allow) {
console.log('DEVTOOLS detected '+allow);
}
}
if(window.attachEvent) {
if (document.readyState === "complete" || document.readyState === "interactive") {
detectDevTool();
window.attachEvent('onresize', detectDevTool);
window.attachEvent('onmousemove', detectDevTool);
window.attachEvent('onfocus', detectDevTool);
window.attachEvent('onblur', detectDevTool);
} else {
setTimeout(argument.callee, 0);
}
} else {
window.addEventListener('load', detectDevTool);
window.addEventListener('resize', detectDevTool);
window.addEventListener('mousemove', detectDevTool);
window.addEventListener('focus', detectDevTool);
window.addEventListener('blur', detectDevTool);
}
}();
A: https://github.com/theajack/disable-devtool
This tool just disabled devtools by detecting if its open and then just closing window ! Very nice alternative. Cudos to creator.
A: Don't forget about tools like Fiddler. Where even if you lock down all the browsers' consoles, http requests can be modified on client, even if you go HTTPS. Fiddler can capture requests from browser, user can modify it and re-play with malicious input. Unless you secure your AJAX requests, but I'm not aware of a method how to do this.
Just don't trust any input you receive from any browser.
A: No you cannot do this.
The developer menu is on the client side and is provided by the user's browser.
Also the browser developer should have nothing to do with your server side database code, and if it does, you need some maaaaaajor restructuring.
A: I found a way, you can use debugger keyword to stop page works when users open dev tools
(function(){
debugger
}())
A: Yeah, this is a horrible design and you can't disable developer tools. Your client side UI should be sitting on top of a rest api that's designed in such a way that a user can't modify anything that was already valid input anyways.
You need server side validation on inputs. Server side validation doesn't have to be verbose and rich, just complete.
So for example, client side you might have a ui to show required fields etc. But server side you can just have one boolean set to true, and set it to false if a field fails validation and then reject the whole request.
Additionally your client side app should be authenticated. You can do that 100 thousand ways. But one I like to do is use ADFS passthrough authentication. They log into the site via adfs which generates them a session cookie. That session cookie get's passed to the rest api (all on the same domain) and we authenticate requests to the rest api via that session cookie. That way, no one that hasn't logged in via the login window can call the rest api. It can only be called form their browser context.
Developer tool wise, you need to design your app in such a way that anything that a user can do in the developer console is just a (feature) or a breaking thing. I.e. say they fill out all the fields with a js snippet, doesn't matter, that's valid input. Say they override the script and try to send bad data to the api calls. Doesn't matter, your server side validation will reject any bad input.
So basically, design your app in such a way that developer tool muckery either brakes their experience (as it won't work), or lets them make their lives a little easier, like auto selecting their country every time.
Additionally, you're not even considering extensions... Extensions can do anything and everything the developer console can do....
A: I am just throwing a random Idea maybe this will help.
If someone tries to open the developer tool just redirect to some other site.
I don't know how much this is gonna effective for you but at least they can't perform something on your site.
A: You can not block developer tools, but you can try to stop the user to enter them. You can try to customize a right-click menu and block the keystrokes for developer tools.
A: You can't disable developer tools
However...
I saw one website uses a simple trick to make devtools unusable. It worked like this - when the user opens devtools the whole page turns into blank page, and the debugger in devtools is stuck in a loop on a breakpoint. Even page refresh doesn't get you out of that state.
A: You can easily disable Developer tools by defining this:
Object.defineProperty(console, '_commandLineAPI', { get : function() { throw 'Nooo!' } })
Have found it here: How does Facebook disable the browser's integrated Developer Tools?
A: Yes. No one can control client browser or disable developer tool or debugger tool.
But you can build desktop application with electron.js where you can launch your website. Where you can stop debugger or developer tool.
Our team snippetbucket.com had build plenty of solution with electron.js, where similar requirement was their. as well restructure and protect website with many tools.
As well with electron.js many web solution converted and protected in well manner.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "82"
}
|
Q: Postback of dropped content in HTML5 We have an ASP.NET MVC3 web application. We generate HTML5 pages.
And now, we would like the dragged & dropped content (images, word documents...) into the HTML5 page to be sent to the Web Server and then processed (content and MIME type) in C#.
How can this be solved?
A: They are a lot of tutorial or library that do it with HTML5. Here is one that combine HTML5 and JQuery to upload file to the server with drag-and-drop.
http://gokercebeci.com/dev/droparea
Example of code that you will need to generate from the ASP page.
<div class="droparea spot" data-width="460" data-height="345" data-type="jpg" data-crop="true" data-quality="60" data-folder="sample" data-something="stupid"></div>
<script>
$('.droparea').droparea({'post' : '/data/dev/droparea/upload.php'});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Efficiently Converting OracleDecimal to .NET decimal w/truncation I am getting an arithmetic overflow exception when trying to convert the following oracle spatial object to a coordinate set (decimals) in C# using (decimal) OracleUdt.GetValue()
MDSYS.SDO_GEOMETRY(2001, 1041001,
MDSYS.SDO_POINT_TYPE(-2.89957214912471,1.56043985049899E-15,NULL),NULL,NULL)
According to Oracle documentation, this is likely because one of the decimal values exceeds .NET's precision range of 28 decimals. Data that exceeds this precision limit in our database is extremely rare, and conversion needs to be as efficient as possible.
What is the best option for handling this exception by gracefully truncating the result if it exceeds the maximum precision?
A: VB.NET code, untested, but I used something similar for a oracleDecimal I had.
Transforming to C# should be easy.
OracleDecimal oraDec = MDSYS.SDO_GEOMETRY(2001, 1041001,
MDSYS.SDO_POINT_TYPE(-2.89957214912471,1.56043985049899E-15,NULL),NULL,NULL)
oraDec = OracleDecimal.SetPrecision(oraDec, 28) ' !!!
Decimal netDec = oraDec.Value
A: With reference to @AndrewR's answer, consider the following test:
[Test, Explicit]
public void OracleDecimal_NarrowingConversion_ShouldSucceed()
{
string sigfigs = "-9236717.7113439267890123456789012345678";
OracleDecimal od = new OracleDecimal(sigfigs);
OracleDecimal narrowedOd = OracleDecimal.SetPrecision(od, 28); //fails
//OracleDecimal narrowedOd = OracleDecimal.SetPrecision(od, 27); //succeeds
object narrowedObjectValue = (object)narrowedOd.Value;
Assert.IsInstanceOf<decimal>(narrowedObjectValue);
}
The Oracle documentation for the 12c Providers states that the precision should be between 1 and 38. (http://docs.oracle.com/cd/E51173_01/win.122/e17732/OracleDecimalStructure.htm#i1003600) . The .Net 'decimal' docs say that the precision is to 28 - 29 sig figs. I don't know why 28 doesn't work in this case.
Edit: If you remove the '-' sign, the above works at 28 significant figures.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: iotop script does not work via custom script execution I have CSF installed (configure safe firewall), it has a function to allow you to have custom scripts executed on load average events.
My script:
##!/usr/bin/env bash
iotop -bto --iter=1 2>&1 | mail -s "$HOSTNAME iotop output" incidents@
It works fine via bash shell but when executed by lfd (the monitoring process of CSF), I get the following output:
Traceback (most recent call last):
File "/usr/bin/iotop", line 9, in <module>
from iotop.ui import main
File "/usr/lib/python2.6/site-packages/iotop/ui.py", line 13, in
<module>
from iotop.data import find_uids, TaskStatsNetlink, ProcessList, Stats
File "/usr/lib/python2.6/site-packages/iotop/data.py", line 36, in
<module>
from iotop import ioprio, vmstat
File "/usr/lib/python2.6/site-packages/iotop/ioprio.py", line 52, in
<module>
__NR_ioprio_get = find_ioprio_syscall_number(IOPRIO_GET_ARCH_SYSCALL)
File "/usr/lib/python2.6/site-packages/iotop/ioprio.py", line 38, in
find_ioprio_syscall_number
bits = platform.architecture()[0]
File "/usr/lib64/python2.6/platform.py", line 1073, in architecture
output = _syscmd_file(executable, '')
File "/usr/lib64/python2.6/platform.py", line 1021, in _syscmd_file
rc = f.close()
IOError: [Errno 10] No child processes
Can anyone shed some light on this?
A: Internally it calls an equivalent of:
import os
import sys
f = os.popen('file -b "%s" 2> %s' % (sys.executable, os.devnull))
f.read()
f.close()
For popen() to work it has to be able to get the SIGCHLD signal telling it that a child process exited. It seems that the environment that executes iotop has a custom reaper process that intercepts SIGCHLD and prevents python from getting notified about the process exiting. Thus when the function calls .close(), python tries to kill the process that is already dead and gets an error from the operating system.
If you cannot reconfigure the environment to let SIGCHLD pass, I think you'll have ro resort to ugly hacking.
Wrapping iotop in a script that monkey-patches platform.architecture() with a function that always returns the same tuple (something like ('64bit', 'ELF')—consult the output of real architecture()) should let you progress.
Alternatively, you can just make a local copy of the platform.py file and edit that directly, setting PYTHONPATH for the cron job to point to that new file.
A: Normally when you have problems automating commands, it's because the thing that's running the command automatically does not have the same environment variables defined (because there's no login). I don't think that's the case here, though. I would sooner suspect the user that the script is running as doesn't have the same rights.
I would try to su to the user CSF is running the script as, and try running it manually as that user.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is message property on Error propertyIsEnumerable? What is the correct result of the following? Do any of the ECMA standards specify this? My current Chrome 14.0.835.186m thinks false and Firefox 3.6.22 thinks true.
(new Error()).propertyIsEnumerable("message")
This is extra annoying because Chrome used to think true as well, and now I have broken code because of this change.
A: I can't find in the ECMAScript 5 spec where it is required either way (doesn't mean it isn't there), but it does appear to be configurable, so you can do this:
Object.defineProperty( Error.prototype,'message',{enumerable:true});
console.log( Error.prototype.propertyIsEnumerable('message') ); // true
or this:
var err = new Error('a message');
Object.defineProperty( err,'message',{enumerable:true});
console.log( err.propertyIsEnumerable("message") ); // true
A: propertyIsEnumerable doesn't return true for 'built-ins' like:
Error.prototype.message or Array.prototype.length
Enumerable properties are those set directly on the object itself as defined in section 15.2.4.7 of ECMA 262, which can be downloaded here
For example:
> var arr = [];
> arr.propertyIsEnumerable("length")
false
> arr.kudos = 55;
55
> arr.propertyIsEnumerable("kudos")
true
> var err = new Error("some message");
> err.propertyIsEnumerable("message")
false
> err.Something = { };
{}
> err.propertyIsEnumerable("Something")
true
the propertyIsEnumerable method is meant to determine what can be used in a for..in loop.
For example:
> for(var key in arr) { console.log(key); }
kudos
> for(var key in err) { console.log(key); }
Something
Are you using propertyIsEnumerable instead of hasOwnProperty?
> err.hasOwnProperty("message")
true
> arr.hasOwnProperty("length")
true
Here are some other examples: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable
My assumption for the reason these used to work is that these browsers are ramping up for ECMAScript 5 compliance.
Edit:
If you need all properties including non-enumerable properties, you can use Object.getOwnPropertyNames(obj). Here's an example that copies non-enumerable properties to another object.
> var err = new Error("Some message");
> var copy = { };
> Object.getOwnPropertyNames(err).forEach(function(key) {
... copy[key] = err[key];
... });
> copy
{ stack: 'Error: Some message\n at repl:1:11\n at Interface.<anonymous> (r
epl.js:168:22)\n at Interface.emit (events.js:67:17)\n at Interface._onLin
e (readline.js:153:10)\n at Interface._line (readline.js:408:8)\n at Inter
face._ttyWrite (readline.js:585:14)\n at ReadStream.<anonymous> (readline.js:
73:12)\n at ReadStream.emit (events.js:70:17)\n at onKeypress (tty_win32.j
s:46:10)',
message: 'Some message',
arguments: undefined,
type: undefined }
> copy instanceof Error
false
> err instanceof Error
true
See here: https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects#section_2
A: The correct result is false because the message property of Error is inherited (I think from the prototype).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Java API design for RESTful application I need to design a RESTful application which allows me to access the people’s contact information from Facebook.
I stored the First name, last name, email address in the database. For the UI I will use Dojo to display the data.
But I don’t know how to design the middle layer to retrieve the data and how to pass it to the Dojo/javascript.
I have done J2EE development and used Struts framework. I know in J2EE, I can create entities beans, and then pass the information to the UI layer through the session beans.
But in a RESTful application, what type of classes do I need to use to accomplish what the entities and session beans can do?
Are there any books that can help me get up to speed ASAP?
A: I have done this quite rapidly (although I think that there are better ways) with the following steps:
*
*Created the RESTful web services from db using NetBeans's wizard: http://netbeans.org/kb/docs/websvc/rest.html
*In Dojo, I have used dojo.xhrGet specifing the url of the service, handleAs: "json"
dojo.xhrGet({
url: myURL,
handleAs: "json",
headers: {"Content-Type": "application/json; charset=uft-8", "Accept" : "application/json"},
load: function(responseObject) {
myList = responseObject;
}
});
*I have read one by one the items in the list and added to a dojo.data.ItemFileWriteStore by using newItem method
*I have added the store to a dojox.grid.DataGrid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# - Can't send mail in WIndows Azure via Gmail SMTP This is my Web.config:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network defaultCredentials="true" enableSsl="true" host="smtp.gmail.com" port="25" userName="xxxxxxx@gmail.com" password="xxxxxxxxxxx"/>
</smtp>
</mailSettings>
</system.net>
My method:
public static void EmailVerification(string email, string nickname)
{
MailAddress from = new MailAddress("xxxxxxxxxxx", "xxxxxxxxxxxx");
MailAddress to = new MailAddress(email);
MailMessage message = new MailMessage(from, to);
message.Subject = "Test";
message.Body = "Test";
SmtpClient client = new SmtpClient();
try
{
client.Send(message);
}
catch(SmtpFailedRecipientException ex)
{
HttpContext.Current.Response.Write(ex.Message);
return;
}
}
My failure SmtpException:
Failure sending mail.
InnerException:
Unable to connect to the remote server
I'm testing it locally but I guess it should work. I have to run it on Windows Azure, I tried and it didn't work too. Is there something I'm missing?
A: The basic authentication and default network credentials options are mutually exclusive; if you set defaultCredentials to true and specify a user name and password, the default network credential is used, and the basic authentication data is ignored.
Use
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network enableSsl="true" host="smtp.gmail.com" port="25" userName="xxxxxxx@gmail.com" password="xxxxxxxxxxx"/>
</smtp>
</mailSettings>
</system.net>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: addChild custom class AS3 This is the class I am trying instantiate into my main class:
public class Character extends Sprite {
[Embed(source='../lib/front1.svg')]
private var front1Class:Class;
private var crosshair:Sprite = new front1Class ();
public function Character() {
trace("started");
Mouse.hide();
crosshair.scaleX = 5;
crosshair.scaleY = 5;
this.addChild(crosshair);
stage.addEventListener(Event.ENTER_FRAME, MrEveryFrame);
stage.addEventListener(MouseEvent.CLICK, click);
}
private function click(evt:MouseEvent):void {
trace("clicked @ " + evt.stageX + "," + evt.stageY);
}
public function MrEveryFrame(e:Event):void
{
crosshair.x = mouseX - 15;
crosshair.y = mouseY - 15;
}
}
When I set it to the document class, it works fine.
However... when I make THIS my document class and try to call it from there:
public class Shell extends Sprite
{
private var character:Sprite = new Character ();
public function Shell()
{
addChild(character);
}
}
It breaks, and no longer shows the sprite object (though it does erase the mouse pointer).
What's the deal here? You can't instantiate custom sprite or movieclip classes into a DisplayObject class???
A: The stage is null in the constructor. That only works when your class is the Document Class, as you found out yourself. So change your constructor like this:
public function Character() {
trace("started");
Mouse.hide();
crosshair.scaleX = 5;
crosshair.scaleY = 5;
this.addChild(crosshair);
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(event:Event):void
{
stage.addEventListener(Event.ENTER_FRAME, MrEveryFrame);
stage.addEventListener(MouseEvent.CLICK, click);
}
Adding the listener will access the stage only after the stage is known, and it's no longer null
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: last.fm json call error the following code:
$.ajax({
type:'GET',
url:'http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=megadeath&api_key=b5bd5e1d31bf4188a6bcd329c964f6f2&limit=5&format=json&callback=?',
success : function(){
console.log("slurped up data");
},
complete: function(){
console.log("just completed the call");
},
error : function(){
console.log("something stinks in Denmark");
},
});
throws an error. When I look at the REST call in the browser I see that it actually produces output, so I think the error pops up in the way the data is handled by jQuery. Have folks encountered this problem before? any suggestions on how to handle this issue?
A: if you chop &callback=? off the end it works:
http://jsfiddle.net/Y44ZD/et
note how in the example on fiddle I get the error message with:
error : function(e,d,f){
alert(f);
}
I was getting "unexpected token ?"
http://api.jquery.com/jQuery.ajax/
says:
error(jqXHR, textStatus, errorThrown)Function
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred.
Your code would be:
$.ajax({
type:'GET',
url:'http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=megadeath&api_key=b5bd5e1d31bf4188a6bcd329c964f6f2&limit=5&format=json',
success : function(){
console.log("slurped up data");
},
complete: function(){
console.log("just completed the call");
},
error : function(){
console.log("something stinks in Denmark");
},
});
EDIT (Question from comment): I would have to read the last.fm documentation but normally callbacks only need to be specified in the request when the remote server is going to contact your server with the answer. this technique is used for more secure communication (e.g. making a payment with an online payment processing company) when the data is return in response to your request its up to you how you process it e.g.:
$.ajax({
type:'GET',
datatype:'json',
url:'http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=megadeath&api_key=b5bd5e1d31bf4188a6bcd329c964f6f2&limit=5&format=json',
success :
function(data){
$.each(data.results.artistmatches.artist, function(key, val) {
$('body').append('<a href="'+val.url+'">'+val.name + '</a><br />');
});
},
complete: function(){
alert("just completed the call");
},
error : function(e,d,f){
console.log(f);
},
});
here is that example: http://jsfiddle.net/rS3p9/7/
(note if like me you are having trouble interpreting json tools like this help: http://jsonformatter.curiousconcept.com/ thay format it nicely so you can see whats going on ;-)
EDIT: okay I just checked the docs:
http://www.last.fm/api/show?service=272
they dont mention a callback:
limit (Optional) : The number of results to fetch per page. Defaults to 50.
page (Optional) : The page number to fetch. Defaults to first page.
artist (Required) : The artist name
api_key (Required) : A Last.fm API key.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to reconnect mongo automatically in node.js server? Let say I have a node.js server connecting to a mongoDB. Then the mongoDB die or disconnect. Of course, node.js server will lose connection. Even if I restart mongoDB, node.js server will not connect to the new mongodb automatically even it is running on the same machine with same port. I need to either restart Node.js server or somehow write my own routine to reconnect it.
Is there any node module to handle reconnection? and in a less aggressive way. (i.e. won't ask for connection every second).
A: The answer to this question will depend on your driver version and your specific code.
The most recent driver versions should support connection pooling. This typically means that you may get an exception when attempting a first connection, but you should be able to re-connect.
Your implementation is also important. There are several ways to do this. Some people open a connection outside of starting the web server, others do it in response to requests.
If you have connection pooling, then you should be able to "open a connection" on every request. You will have to handle the errors correctly after reboot, but you should not need to restart the Node environment.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I determine the JVM minimum heap size from within a java application? I have reviewed the answer to how to get the min and max heap size settings of a JVM from within a Java program which was helpful, but the accepted answer doesn't appear to answer half of the question. In essence, I want to report the -Xms and -Xmx settings that were used when the JVM was launched.
A: These are the mappings between values you're looking for:
-Xmx=Runtime.getRuntime().maxMemory()
-Xms=Runtime.getRuntime().totalMemory()
Hope this helps.
A: If you want to get the real JVM arguments this should help you. You can get all JVM arguments with the MXBean:
RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = RuntimemxBean.getInputArguments();
You have to look for the arguments which start with "-Xm(s|x)". The problem is that the value could be something like "256M".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Only display .NET PasswordStrength Control after 6 characters? Anyone have any ideas on how to hide the .NET PasswordStrength control until after 6 characters have been typed? The control doesn't seem to support this so I'm guessing I'd have to wrap something around it maybe? Thoughts?
A: Unless you're doing a postback on every keystroke in the textbox (please don't do that! :), you'll need to use client-side script to do this work.
Easiest way I can think of is to hook the textfield's onkeyup event: have it call a javascript function which evaluates the length of the text in the field. If length is greater than 6 use CSS ('display: block;' most likely) to show the passwordStrength control; otherwise hide the control ('display: none').
Note: this doesn't account for paste operations into the text box - but since it's a password field, you probably don't want to allow paste into it anyway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Passing the stringValue of a TextField from one class to another I have a Cocoa app for Mac OS X written in Xcode 4. The app has a main window that is the app delegate. This window has a button that opens another window (call it pop window) with 2 TextFields and a couple of buttons. When the user click one of those button the idea is to close the pop window and grab the text from the 1st TextField and use it on the app delegate.
The code I have is as follow.
App delegate .h:
@interface TestAppAppDelegate : NSObject <NSApplicationDelegate> {
NSString *valueofedit;
@private
NSWindow *window;
NSPersistentStoreCoordinator *__persistentStoreCoordinator;
NSManagedObjectModel *__managedObjectModel;
NSManagedObjectContext *__managedObjectContext;
NSTextField *_StatusLabel;
}
@property (assign) IBOutlet NSWindow *window;
@property (nonatomic, retain) NSString *valueofedit;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (assign) IBOutlet NSTextField *StatusLabel;
- (IBAction)GetStatClick:(id)sender;
- (IBAction)OnLaunch:(id)sender;
- (IBAction)saveAction:sender;
@end
The Delegate .m:
#import "TestAppAppDelegate.h"
#import "MyClass.h"
@implementation TestAppAppDelegate
@synthesize StatusLabel = _StatusLabel;
@synthesize valueofedit;
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
valueofedit = [[[NSString alloc] init] autorelease];
}
- (IBAction)GetStatClick:(id)sender {
// I need to get the value of the pop window textfield here.
}
- (IBAction)OnLaunch:(id)sender {
MyClass *controllerWindow = [[MyClass alloc] initWithWindowNibName:@"pop"];
[controllerWindow showWindow:self];
// this of course is always null
NSString * tmp = [controllerWindow valueofedit];
NSLog(@"result: %@", tmp);
}
@end
OnLaunch will pop the new window.
The the pop window code
The .h:
@interface MyClass : NSWindowController {
NSString *valueofedit;
@public
NSTextField *one;
NSTextField *two;
NSWindow *popupwin;
}
@property (assign) IBOutlet NSWindow *popupwin;
@property (assign) IBOutlet NSTextField *one;
@property (assign) IBOutlet NSTextField *two;
@property (nonatomic, retain) NSString *valueofedit;
- (IBAction)onclose:(id)sender;
@end
and the .m
#import "MyClass.h"
#import "TestAppAppDelegate.h" //try to access the delegate but no luck
@implementation MyClass
@synthesize popupwin;
@synthesize one;
@synthesize two;
@synthesize valueofedit;
// when we hit the "Done" button
- (IBAction)onclose:(id)sender
{
// the value of the textfield that I need
valueofedit = [one stringValue];
// I tried to get the value sent to the app delegate
TestAppAppDelegate *mainwin = [TestAppAppDelegate alloc];
[[mainwin valueofedit] initWithFormat:@"%@", valueofedit];
[popupwin close];
}
@end
So the idea was that since I can't access the pop window directly I tried with having a variable made public on the app delegate and copy the value of the text field there before closing the pop window. It didn't work.
How do I do this? How do i pass the value of the text field of one window to another?
Note: No, I can't use alerts for this.
Code samples are appreciated. Thank you.
A: You are allocating a new instance of your application delegate. Instead of [TestApplicationDelegate alloc] you should be using [NSApp delegate].
Once you have a pointer to the actual delegate, you are not using the accessor properly to set the vauleOfEdit property.
Currently you are calling initwithformat on the returned value of an accessor, which is either going to be nil or an already initialised string.
Amend your onclose method to:
// when we hit the "Done" button
- (IBAction)onclose:(id)sender
{
TestAppAppDelegate *mainwin = (TestAppAppDelegate*)[NSApp delegate];
mainwin.valueofedit = [one stringValue];
[popupwin close];
}
@end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using pagination to display elements of an element in a table I'm new to JSP, so bear with me.
I'm trying to make a JSP page that will display a table of some objects that I have fetched. Contained inside these objects is an array. In the table, I want there to be a hyperlink, or even a button, that will send the user to a page that will display the array contained inside the object.
I currently have a for-loop going through the list of container objects (which hold the array), and that loop constructs the main table, I have it displaying other elements of the container object.
What technique should I use to have the table of container objects link to another page which has a table of the array? (which is in the container object) Each link from a container object needs to link to its contained array.
A: Your question is missing some basic information about the these containers and their origin. If they are coming from a database then the suggested route is to put in a link to another page passing the PK of the container object. This way, the second page will refetch the container and display its array.
if your container cannot be fetched a second time, I suggest then using javascript/jquery magic to display the array in the same page. This will result in larger HTML content but will avoid having to store the content in some sort of user's based cache.
A: Well, let me explain with a Order example. Orders is a collection and you want to list the entire collection in the mainpage. When a link is clicked you want to show the details pertaining to the particular order item.
In this case, you'd iterate through the collection using c:forEach
<c:forEach var="orderDetail" items="orders"><a href="/myProj/orderDetail?orderId=${orderDetail.id}">Order Detail</a></c:forEach>
Each listing would have a link with a parameter that uniquely identifies the item as above.
Note here that the orderDetail is a servlet (or any controller). The request goes to the servlet, it reads the request parameter. With the orderId parameter it takes the associated order object, places it in request scope under a name, say orderDetailModel and dispatches the request to orderDetailsPage.jsp The orderDetailsPage.jsp merely finds this orderDetailModel object from request scope and displays it.
Like ${orderDetailModel.placedTime}
Hope this example helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to convert an existing website application into a Facebook app? I looked at a few of the SO questions that were similar to mine but didn't find them as informative as I had hoped. I read one place that said use iFrame but that requires using the Canvas, and Facebook api, and finally, now on Oct. 1, SSL (which means a static IP, more money, paid certificate.)
I don't want all that for a sandbox. I want to build, test, and if I think the product is worthy, then, after I am satisfied with my product, get all the stuff required for a Facebook app. If I take a low price host, I can do it cheaply for my "sandbox."
Not sure how to proceed.
edit: For that matter, I can do it all locally before putting on FB.
A: The quickest & easiest way to get started with integrating with Facebook is to add a "Login with Facebook" button to your site: Facebook for Websites. Users will browse to your site at your domain as usual, as opposed to inside a Facebook canvas. You'll have access to any Facebook feature you want to test to see if a canvas app is worthwhile.
This does require that you set up a Facebook Developer app to get an App ID and Secret, but you won't have to parse a signed_request, use SSL, etc.
Once you do this, a user can click the "Login with Facebook" button on your site and allow access on the permissions prompt. That user will then be authenticated with your Facebook app, and you'll have access to the social channels like feeds and requests, the Graph API, etc.
Update
To answer @johnny's comment question: Yes, by using the Facebook Javascript SDK. You can post to a user's wall by either prompting them with a Feed Dialog each time you want them to post a story to their wall, or by requesting the 'publish_stream' extended permission, which allows you to post stories to their wall without prompting the user every time (only if the user indicates they want to share that particular story - be sure to read through the TOS).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Finding Unhandled Exceptions - .NET I have a fairly large .NET solution that has poor exception handling. The original authors meant well, catching specific types of exceptions rather than the base exception class, however, this has resulted in more than I can count places where exceptions of a type are thrown but not caught anywhere and makes the software unreliable. How can I perform a code analysis to identify where in the solution an exception type can be thrown but is not being caught?
A: You can add a global exception handler that logs the Exception including stack trace, and puts up a nice error dialog for the user. You can use the stack trace to identify the places in the code that generates errors and put up better handling of those scenarios. Log as much as possible.
How you do that depends on the platform (WebForms, MVC, WinForms, WPF, ... ?)
Also, an in-depth code review of the entire code base with emphasis on error handling might catch many errors before they manifest themselves as errors to the user.
A: This is how I handle them. In my Program.cs in the Main method, I set up event handling. After, you put in these events the code your want.
Application.ThreadException += Form1_UIThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
EDIT: This is for non-web based apps.
A: Any exception that is not caught is unhandled. The good news is you can subscribe to that AppDomain.CurrentDomain.UnhandledException event.
This handles any exception that is thrown that is not caught.
How can I perform a code analysis to identify where in the solution an
exception type can be thrown but is not being caught?
There are programs like StyleCop that will highlight possible unhandled exceptions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Json result wrapped in pre tag - how to get value of it This is first time that I work with json. I am trying to return Json from my action method:
public JsonResult Upload()
{
...
return Json(new { foo = "sos....sos....sos..."});
}
But in result all I get is my message wrap in this "pre" tag. How to parse "foo" from this?
"<pre style="word-wrap: break-word; white-space: pre-wrap;">{"foo":"sos....sos....sos..."}</pre>"
A: This returns the content of the first pre tag with the class "yourclass".
document.querySelector("pre.yourclass").innerHTML
A: I think the reason you are receiving the data wrapped in a pre tag is because you are requesting the data as HTML and not plain text or json.
Try specifying the data type as json to stop the response being converted to HTML.
A: It's possible that the handler on the client side is trying to ensure that the server's response is well formed HTML. I believe some javascript libraries with file upload support will wrap non-HTML repsonses in the tag as you describe. A very non-intuitive solution might be to set the mimetype at the server to be "text/html", so that the ajax handler doesn't try to wrap the response.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to fill dataset with 2 datatable objects? I have a an XML file which I am loading into a dataset, I need this datatset to return 2 data tables.
How can I achieve this? Thanks and appreciate your feedback.
A: Start with a dataset having two tables, export it to xml. Then you will have the correctly formatted XML.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiple MYSQL Inner Joins Hi I am trying to create a search function but having trouble on getting it to work.
This is what I have so far:
SELECT DISTINCT users.ID, users.name
FROM users
INNER JOIN usersSkills
ON users.ID = usersSkills.userID
INNER JOIN usersLanguages
ON users.ID = usersLanguages.userID
WHERE activated = "1"
AND type = "GRADUATE"
AND usersSkills.skillID IN(2)
GROUP BY usersSkills.userID HAVING COUNT(*) = 1
AND usersLanguages.languageID IN(2)
GROUP BY usersLanguages.userID HAVING COUNT(*) = 1
But I keep getting this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY usersLanguages.userID HAVING COUNT(*) = 1' at line 14
If i remove one of the inner joins and group bys it works so not sure what it is can i use two group bys?
A: You have two group by clauses in the statement; that is invalid SQL . Do your first group by, then a comma, then your second group by. Your Having clauses should come after using ORs and ANDs to join them into a logical statement
GROUP BY usersSkills.userID, usersLanguages.userID
HAVING COUNT(*) = 1
AND usersLanguages.languageID IN(2)
that answers your syntax error question.. (not trying to speak down here) but the structure of the query shows you don't really know what you want to do in the form of the query though... I would strongly suggest you get a SQL book or go through a sql tutorial so you understand what the statements you are trying to write actually do..
A: Tr this:
SELECT DISTINCT users.ID, users.name, COUNT(*)
FROM users
INNER JOIN usersSkills ON users.ID = usersSkills.userID
INNER JOIN usersLanguages ON users.ID = usersLanguages.userID
WHERE activated = "1"
AND type = "GRADUATE" AND usersSkills.skillID = 2
AND usersLanguages.languageID = 2
GROUP BY usersSkills.userID,
usersLanguages.userID
HAVING COUNT(*) = 1
Removed the multiple erroneous GROUP BY's and merged the query.
Also changed the IN(x) to = x
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: source code for F# 3.0 talk on BUILD is there a dowload link for the source code in Don Syme's F#3.0 talk on //build/?
A: You can find the source code of the examples from the talk on his blog:
http://blogs.msdn.com/b/dsyme/archive/2011/10/05/demo-scripts-from-the-f-3-0-build-talk.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can an Android application duplicate "Auto-rotate" functionality? In other words, can an application sit in the background, read the g-sensor of the device, and accordingly set (or rotate) the view of the active Android application?
A: No, sorry. You could use sensors to perhaps control your app, but you cannot impose your will upon other apps, any more than they can impose their will upon yours.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get a value from a radio-buttons' collection I was able to get the value from an input type=text with code like this:
$salad_size = $form->addField('line','salad');
$salad_button->js('click')->univ()->ajaxec(
array(
$this->api->getDestinationURL(),
'generate_salad'=>true,
'salad_size'=>$salad_size->js()->val(),
));
Now I need to get a value from any out of three radio-buttons. This is the object construction:
$salad_size = $form->addField('radio','salad_size')->setValueList(array('S'=>'Chica','M'=>'Mediana','L'=>'Grande'));
I'd like to know which exactly is the method name to use instead of 'val()' (as it looks not to be the right one for radios).
I was unable to get the methods list from the API reference page here. Any other source of avail methods?
TIA
A: Have you tried is(':checked') instead of val() ?
A: Have a look at the agiletoolkit radio button demo page
For the radio button it has the following example
$p=$this;
$values=array('M'=>'Male','F'=>'Female');
$f=$p->add('Form');
$f->addField('line','name');
$f->addField('radio','gender')
->setValueList($values)
->setNotNull();
$f->addSubmit();
if($f->isSubmitted()){
$f->js()->univ()->alert($f->get('name').', you are a '.$values[$f->get('gender')])->execute();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In perl, backreference in replacement text followed by numerical literal I'm having trouble with a backreference in my replacement text that is followed by a literal. I have tried the following:
perl -0pi -e "s/(<tag1>foo<\/tag1>\n\s*<tag2>)[^\n]*(<\/tag2>)/\1${varWithLeadingNumber}\2/" file.xml
perl -0pi -e "s/(<tag1>foo<\/tag1>\n\s*<tag2>)[^\n]*(<\/tag2>)/\g{1}${varWithLeadingNumber}\g{2}/" file.xml
The first of course causes problems because ${varWithLeadingNumber} begins with a number, but I thought the \g{1} construct in my second attempt above was supposed to solve this problem. I'm using perl 5.12.4.
A: Using \1, \2, etc in the replacement expression is wrong. \1 is a regular expression pattern that means "match what the first capture matched" which makes no sense in a replacement expression. Regular expression patterns should not be used outside of regular expressions! $1, $2, etc is what you should be using there.
After fixing \1, you have
perl ... -e'... s/.../...$1$varWithLeadingNumber.../ ...'
That said, I think varWithLeadingNumber is supposed to be a shell variable? You shouldn't have any problems if it's a Perl variable. If you're having the shell interpolate varWithLeadingNumber, the problem can be fixed using
perl ... -e"... s/.../...\${1}${varWithLeadingNumber}.../ ..."
Note that you will have problems if $varWithLeadingNumber contains "$", "@", "\" or "/", so you might want to use a command line argument instead of interpolation.
perl ... -pe'
BEGIN { $val = shift; }
... s/.../...$1$val.../ ...
' "${varWithLeadingNumber}"
You could also use an environment variable.
export varWithLeadingNumber
perl ... -pe's/.../...$1$ENV{varWithLeadingNumber}.../'
or
varWithLeadingNumber=varWithLeadingNumber \
perl ... -pe's/.../...$1$ENV{varWithLeadingNumber}.../'
If you did have a \1
s/...\1.../.../
you can avoid the problem a number of ways including
s/...(?:\1).../.../
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Can I get types from an arbitrary query in Postrges? I've got a situation building a data analysis tool where my users can write SQL query (including joins, calculations, etc) and I need to be provide options to the user based on the data types of the columns in the result. I'm using JDBC to connect to Postgres. Is there any way to get Postgres to report the data type of a computed column?
A: With JDBC, you should be able to call .getMetaData() in your ResultSet, and iterate through the columns and e.g. learn their types with .getColumnType()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Excel Macro Subscript out of range error I have below macro,getting script out of range error in If arr(0) <> opt Then arr(0) = VAL_DIFF
if i see the length of that array it is showing 2.I dont understand why i am not able to access arr(0),As per i know Array always starts with 0.I able to print arr(1),arr(2) values.
Below macro able to findout similar records and copied to sheet2.Here i also wants to highlight with color in sheet1. Please help me.
Option Base 1
Sub Tester()
Const COL_ID As Integer = 1
Const COL_SYSID As Integer = 2
Const COL_STATUS As Integer = 4
Const COL_OPTION As Integer = 3
Const VAL_DIFF As String = "XXdifferentXX"
Dim d As Object, sKey As String, id As String
Dim rw As Range, opt As String, rngData As Range
Dim rngCopy As Range, goodId As Boolean
Dim FirstPass As Boolean, arr
With Sheet1.Range("A1")
Set rngData = .CurrentRegion.Offset(1).Resize( _
.CurrentRegion.Rows.Count - 1)
End With
Set rngCopy = Sheet1.Range("F2")
Set d = CreateObject("scripting.dictionary")
FirstPass = True
redo:
For Each rw In rngData.Rows
sKey = rw.Cells(COL_SYSID).Value & "<>" & _
rw.Cells(COL_STATUS).Value
If FirstPass Then
'Figure out which combinations have different option values
' and at least one record with id=US or CHN
id = rw.Cells(COL_ID).Value
goodId = (id = "US" Or id = "CHN")
opt = rw.Cells(COL_OPTION).Value
If d.exists(sKey) Then
arr = d(sKey) 'can't modify the array in situ...
If arr(1) <> opt Then arr(1) = VAL_DIFF
If goodId Then arr(2) = True
d(sKey) = arr 'return [modified] array
Else
d.Add sKey, Array(opt, goodId)
End If
Else
'Second pass - copy only rows with varying options
' and id=US or CHN
If d(sKey)(2) = VAL_DIFF And d(sKey)(1) = True Then
rw.Copy rngCopy
Set rngCopy = rngCopy.Offset(1, 0)
End If
End If
Next rw
If FirstPass Then
FirstPass = False
GoTo redo
End If
End Sub
A: Stop using Option Base 1 at the top of your modules. It might seem to make things easier, but it only ends up causing confusion. I already gave you the answer to coloring the range - please try to look things up and try them out before posting here.
A: To check the lower bound position of an array, use Lbound(arr).
Also, you did not initialize arr as an array. Initialize it like so:
Dim arr() As Variant.
You could also specify the lower dimension and upper dimension of the array.
Dim arr(3 To 10) As Variant. This creates an array of 7 elements starting at position zero. I suggest learning more about arrays in VBA by doing a Google search.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using data-attributes with jquery validate Is it possible to use data-attributes to with the JQuery Validate plugin. I currently use the class name e.g.
class="{required:true, messages:{required:'You must choose a site.'}}"`
but need to use the data attribute e.g.
data-validate="{required:true, messages:{required:'You must choose a site.'}}"`
The inputs may have more than one data attribute associated with it which won't be related to the validation e.g.
<input name="txt_txt001" type="text" maxlength="30" id="txt_txt001" class= "
{required:true, messages:{required:'This field is required.'} }" data-
children="ddl_txt007,ddl_txt008" data-optionGroup="1" data-optionGroupParent="" />
I know the ketchup plugin offers this but dont want to move over to it as I've put loads of work into getting the page setup with JQuery Validate.
Thanks
A: Try making the following chages to validate 1.9.0.
I've made a few mods so my line numbers may be off, but here goes:
Around ln 149:
var data = $.validator.normalizeRules(
$.extend(
{},
$.validator.metadataRules(element),
$.validator.classRules(element),
$.validator.dataRules(element), // add this
$.validator.attributeRules(element),
$.validator.staticRules(element)
), element);
Add this after classRules around ln 782:
// pretty much steal everything from the class based settings
dataRules: function(element) {
var rules = {};
var classes = $(element).data("validation");
classes && $.each(classes.split(' '), function() {
if (this in $.validator.classRuleSettings) {
$.extend(rules, $.validator.classRuleSettings[this]);
}
});
return rules;
},
Add any additional validators to the class rules:
jQuery.validator.addClassRules({
phone: {
phoneUS: true
},
zipcode: {
zipcode: true
},
notFirstSelect: {
notFirstSelect : true
}
});
Then add a data-validation attribute to your for fields:
<input type="text" data-validation="zipcode required" maxlength="10" class="inputText med" value="" name="zip" id="zip">
This has been working really well for me. Check out: http://www.roomandboard.com/rnb/business_interiors/contactus/send.do for an example of this in use.
A: I havent used the plugin, but there doesn’t seem to be a built-in option to change attribute from where it fetches rules. But if you look at the uncompressed source at line 767, you’ll see a classRules method.
In this method at line 769 there is:
var classes = $(element).attr('class');
You can try to change this to:
var classes = $(element).attr('data-validate');
As said, I havent tested this, although it seems more logical and semantic to put this kind of stuff in a data attribute than a class as the plugin suggests per default.
A: ASP.NET MVC 3 incorporates unobtrusive validation using HTML5 data- attributes. The file jquery.validate.unobtrusive.js in the MVC 3 framework parses the data- attributes, and adds the rules into jquery.validate.js.
You can get more details in this article.
A: I know this is old, but I just stumbled upon it looking for something related. I figured since there is no accepted answer you may still be in need of one? Anyway, David was really close:
var classes = $(element).data("validate");
This should grab the contents of your data-validate attribute. From there you should be able to parse or pass on the value as you are/were doing with the class name.
A: Recommend to Use data-attriubtes.
You don't need jquery.validate.unobtrusive.js anymore. As of version 1.11.0 jquery.validate.js has that included by default. The syntax is kept the same, take a look at samples here:
http://denverdeveloper.wordpress.com/2012/09/26/some-things-ive-learned-about-jquery-unobtrusive-validation/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How can one check an identifier for unescaped validity in most RDBMSs? I'd like my application to work on several databases. While I'm not going to explicitly support them right now, I'd like to be able to define my schemata such that I'm not using reserved identifiers. The reason? Identifier delimiters are not standard between databases. For instance, MySQL uses backticks (`) to quote identifiers, while MSSQL uses brackets ([]).
However, I'm not sure what subset of names are "safe". Is there an easy way to check this?
A: Main Answer
An easy way? I don't think so. So, NO.
A way to do it
The only way is to look up the docs for each supported RDBMS.
The reason
You can always look up the ANSI SQL for reserved words but, at the end, each RDBMS will have its particularities.
A workaround
Let's look at this at a different angle: instead of having your SQL queries avoid reserved names, you can have part of your code escape the columns accordingly to the RDBMS.
Other problems to face
Column naming is not your only problem. Heck, it's not even your main problem!
If you are familiar with GROUP_CONCAT in MySQL you know what I mean. Its alternative in SQL Server is using XML PATH. Firebird has the LIST built-in aggregate function. In the end, you will end up having a different query per RDBMS. I know that because of...
My experience
My "Been there, done that" anecdote: I've worked in a company whose main enterprise product was supposed to support the client's existing RBDMS, which could be Oracle, SQL Server or Informix (don't ask).
In the end it worked like that:
*
*Is it a simple query? Try to write it as to work on all RDBMS;
*Is that not possible (meaning: too hard / will take a lot of time)? There will be an IF in your code. There's no escape (BWAHAHA!), you'll have one query per RDBMS.
*Everything we tested, we tested 3 times: one per RDBMS.
Conclusion
Having your application support multiple RDBMS is a great feature and a very persuasive sales argument. However, it's just not that easy to maintain. It takes work, really.
You might think now that you are never going to use RDBMS specific queries. But then comes the day when an odd query is very easily resolved by both SQL Server and Oracle, but in each's own way. However you will try to write the same query using ANSI SQL (of course, why wouldn't you?) and that will take you hours and may drive you a little crazy. Again, "been there, done that". But don't take my word alone: talk to people and, most importantly, prototype!
A: *
*Stick to alphanumerics (ASCII A-Z, 0-9) plus underscore.
*Don't start with an underscore (and you must start with an alphabetic).
*Don't require delimited identifiers - assume case-insensitive.
*You may need to research length limits - old SQL standards (SQL-86, SQL-89) limited names to 18 characters, but most DBMS allow at least 31 these days.
*Avoid keywords (but the list of keywords is immense - for each DBMS separately, and the union of all keywords across all DBMS).
A: Overall I think this is not a good strategy, but to answer your specific question about identifiers, I expect you will need to determine them on a per-case basis if you want to avoid escaping completely.
You could also consider using ANSI_QUOTES mode in MySQL - then all your identifiers for SQL Server, Oracle and MySQL could be quoted with double-quotes - the ANSI standard.
For instance, SQL Server 2000 "Regular Indentifiers" are undelimited: http://msdn.microsoft.com/en-us/library/aa223962%28v=sql.80%29.aspx
Same docs for SQL Server 2005: http://msdn.microsoft.com/en-us/library/ms175874%28v=sql.90%29.aspx
SQL Server 2005 Reserved Word List: http://msdn.microsoft.com/en-us/library/ms189822%28v=SQL.90%29.aspx
Equivalents for Oracle 10g: http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements008.htm
Reserved words in MySQL: http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Resource Dictionary Styles not available to UserControl So I have made a resource dictionary of styles to use and included it in my UserControl:
<UserControl.Resources>
<ResourceDictionary Source="../affinityStyles.xaml" />
</UserControl.Resources>
Which makes it available to all the controls in the UserControl, but not the UserControl itself. I am guessing this is because that bit of code comes after the UserControl tag.
How can I use Resource Dictionary defined styles for my UserControl background?
A: One option is to use DynamicResource rather than StaticResource; this postpones resolution until runtime.
Alternately, you can use the following XAML property syntax and place it after the ResourceDictionary is merged in:
<UserControl.Background>
<StaticResource ResourceKey="SomeResourceKey"/>
</UserControl.Background>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Confused about idempotency, PUT, GET, POST, etc Most of the discussions about these topics are about how to form a URL or how to request a resource. Let me describe what I'm doing and see if the community can help me restate my problem in the more web-design-professional language :-)
I'm building a piece of hardware that I suppose you'd call a "web appliance". Similar to an online weather station, it will sit on a home LAN and send messages to a remote server. Let's say that every 5 minutes it will send a record of:
timestamp
temperature reading
unit ID #
The "web page in the sky" that is collecting this data is a Ruby-on-Rails app containing tables for device ID's and samples.
I want the web appliance to be able to directly post new samples to the "samples" data table by composing an URL similar to the following:
http://kevinswebsite.com/samples/new?timestamp=2011_Oct_01_1440&unit_id=75&temp=75.5
The above should create a record that at 2:40PMon October 1, 2011, Unit #75 reported a temperature of 75.5 degrees.
Is something like this possible?
Thanks,
Kevin
A: You should use the GET only to retrieve information in a safe and idempotent way! Looks like your URL is using GET and you want to create corresponding record in your database. I would recommend using POST instead. Please note that POST is not safe and idempotent method. Once you process the POST request, you can create a new record in your table for your new information that you obtain from your web appliance.
That way you can be sure the clients will count on your methods such as GET, POST, DELETE, HEAD, PUT, etc.
Good luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using Maven to just download JARs I would like to have Maven download the JARs listed in a pom.xml file. How do I do that? Currently, Maven wants to compile the project (and it fails). I don't care about compiling it because I'm compiling manually. I just want the JARS. Help?
Albert
ps: Background, I am compiling it manually because I can easily debug the project in Eclipse. I've manually downloaded a bunch of JAR files, but I suspect there's a JAR version mismatch as there's a mysterious error at runtime. I would do this checking manually, but there are hundreds of associated JAR files. Ideally, I want to download all the JAR files, point my Eclipse project to the newly download JARS, and get on with my life. :)
A: You can try this command:
mvn dependency:resolve
Or just invoke the "install" life cycle as follows:
mvn install
A: Your best approach is to use m2eclipse and import your pom into eclipse. It will download and link all dependencies to your project, and as an added bonus, it will also download and associate their source and javadoc jars. It does not really matter if the project has hundreds or just few dependencies, it will work the same.
Sometimes, we want to do something quickly and be done with it, but it ends up taking longer than doing the right away especially when there hundreds of dependencies.
A: Try
mvn install dependency:copy-dependencies
You will see all the jars under 'target/dependency' folder
A: If you are using eclipse, I believe you can just right click on the project --> maven --> update project
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
}
|
Q: Error in installing BIRT for FB Eclipse 4.5 I am trying to install BIRT on my existing FLash Builder Eclipse 4.5
However, after all the preferences have been selected, when it actually begins to downlaod, I get this Error:
An error occurred while collecting items to be installed
session context was:(profile=epp.package.java, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
No repository found containing: osgi.bundle,com.adobe.flash.codemodel.core,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flash.codemodel.osgi,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flash.profiler,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flash.profiler.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flashbuilder.launching.multiplatform.ui,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flashbuilder.launching.multiplatform.ui.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flashbuilder.multiplatform.android.ui,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flashbuilder.multiplatform.android.ui.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flashbuilder.multiplatform.ios.ui,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flashbuilder.multiplatform.ios.ui.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flashbuilder.project.multiplatform.ui,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flashbuilder.project.multiplatform.ui.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.DCDService,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.DCDService.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.ajaxbridge,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.ajaxbridge.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.as.editor,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.as.editor.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.axis2,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.axis2.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.codemodel,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.codemodel.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.crimson,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.crimson.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.css.editor,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.css.editor.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.dcrad,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.dcrad.derived,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.dcrad.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.debug,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.debug.e33,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.debug.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.debug.ui,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.debug.ui.actions,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.debug.ui.e36,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.debug.ui.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.designview,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.designview.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.editorcore,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.editorcore.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.editors.derived,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.editors.derived.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.exportimport,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.exportimport.nl1,4.5.0.308971
No repository found containing: org.eclipse.update.feature,com.adobe.flexbuilder.feature.core,4.5.0.308971
No repository found containing: org.eclipse.update.feature,com.adobe.flexbuilder.feature.core.nl1,4.5.0.308971
No repository found containing: org.eclipse.update.feature,com.adobe.flexbuilder.feature.standalone,4.5.0.308971
No repository found containing: org.eclipse.update.feature,com.adobe.flexbuilder.feature.standalone.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.flashbridge,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.flashbridge.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.flex,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.flexunit,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.flexunit.derived,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.flexunit.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.help,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.help.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.importartwork,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.importartwork.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.json,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.launching.ui,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.launching.ui.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.monitors.network,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.monitors.network.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.multisdk,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.mxml.editor,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.mxml.editor.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.mxmlmodel,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.project,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.project.e35,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.project.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.project.ui,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.project.ui.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.BlazeDSService,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.CFService,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.CFService.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.HTTPService,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.HTTPService.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.J2EEService,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.J2EEService.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.LCDSService,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.PHPService,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.PHPService.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.StaticContentService,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.StaticContentService.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.WEBService,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.WEBService.derived,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.services.WEBService.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.standalone,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.standalone.e36,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.standalone.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.tengine,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.tengine.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.ui,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.ui.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.utils.osnative,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexbuilder.utils.osnative.win,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.amt,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.as.core,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.as.core.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.communityhelp,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.communityhelp.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.css.core,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.css.core.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.designitems,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.editorcore,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.editorcore.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.editors.derived.e35,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.embeddedplayer,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.exportimport,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.exportimport.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.externaleditors,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.externaleditors.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.fcproject,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.fcproject.nl1,4.5.0.308971
No repository found containing: org.eclipse.update.feature,com.adobe.flexide.feature,4.5.0.308971
No repository found containing: org.eclipse.update.feature,com.adobe.flexide.feature.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.fonts,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.launching,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.launching.multiplatform,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.launching.multiplatform.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.launching.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.multiplatform.android,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.multiplatform.android.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.multiplatform.ios,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.multiplatform.ios.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.multisdk.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.mxml.core,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.mxml.core.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.nativelibs,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.playerview,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.project.multiplatform,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.project.multiplatform.nl1,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.refactoring.core,4.5.0.308971
No repository found containing: osgi.bundle,com.adobe.flexide.refactoring.core.nl1,4.5.0.308971
No repository found containing: org.eclipse.update.feature,com.adobe.flexide.utils.feature,4.5.0.308971
Thank you for your time!
A: What you most likely has encountered is a bug in Eclipse.
The solution is to force Eclipse to download metadata from the update site again. This can be done by changing the url, such as adding a '/', or by removing and adding the update site again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fetching data from mysql using an android based client I have a server, that is developed using JAVA (netbeans), and a client which is an ANDROID device, I have a very simple database in mysql which runs on the server, all I want to do is to fetch the data using my android client, from the remote sever. where server and client are connected via Wifi.
A: You could create a RESTful web service on your server that would take HTTP requests from the Android client and return HTTP responses using JSON.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Count Uppercase letters Ok i have to pass a string to the main method which is obviously stored in args[0].Then count the amount of times an uppercase letter occurs. For some reason i do not seem to be counting the uppercase occurrence properly. This is homework, any ideas? Thanks in advance.
package chapter_9;
public class Nine_Fifteen {
public static void main(String[] args) {
int caps = 0;
for(int i = 0;i < args.length;i++) {
if (Character.isUpperCase(args[0].codePointCount(i, i))){
caps++;
}
System.out.println("There are " + caps + " uppercase letters");
}
}
}
A: The problem is your use of String.codePointCount:
Returns the number of Unicode code points in the specified text range of this String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1. Thus the length (in chars) of the text range is endIndex-beginIndex. Unpaired surrogates within the text range count as one code point each.
That's not what you want - you're passing that into Character.isUpperCase, which isn't right.
Do you definitely need to handle non-BMP Unicode? If not, your code can be a lot simpler if you use charAt(i) to get the char at a particular index instead. You also want to loop from 0 to args[0].length() as Kevin mentioned. I would suggest extracting the args[0] part to a separate string variable to start with, to avoid the confusion:
String text = args[0];
for (int i = 0; i < text.length(); i++) {
// Check in here
}
I won't complete the code for you as it's homework, but hopefully this will be enough to get you going.
A: args.length is the number of args you have (so, most likely, 1), but you want to parse the length of args[0] (args[0].length)
Also, use charAt(i) to test for uppercaseness.
A: *
*Check that your for loop really loops over what you think you loop.
*Don't use codePointCount(), there's a method with a much shorter name that gives you the character at a position
*You probably don't want to print out the number of caps on every loop iteration
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to find out which file contains a javascript function I've taken over a project which involves a lot of javascript (AJAX and whatnot). In tracking down functions, is there a way to find out which included .js file contains a specific function?
I'm hunting through Firebug but can't find where it isolates the specific file which contains the javascript function. What am I missing?
A: The Web Developer plugin (for FF and Chrome http://chrispederick.com/work/web-developer/) has a "View JavaScript" feature that shows all of the JS that a page is referencing on a single page. CTRL-F from there to find the function.
A: Fiddler will let you search through all requests, so you could load the page in Fiddler, then search for your function.
http://www.fiddler2.com/fiddler2/
A: Certain text editors, including Notepad++, allow you to search all files in a directory. You can use that to search for "function foo(" and that should pull it up.
Of course, that assumes the function is declared like that. It could also be assigned, which would be a bit more difficult. You'd have to search for something like "foo\s*=" (using Regex search).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Determine if statically named JavaScript function exists to prevent errors I have a script on my website that calls a statically named function when called:
childLoad();
The childLoad() function is not always defined though it is always called. How can I prevent the script from calling this function if it does not exist?
A: if(typeof childLoad == 'function') {
childLoad();
}
A: if ( typeof childLoad == 'function' ) {
childLoad();
}
A: You could use short circuit evaluation:
childLoad && childLoad();
EDIT
('childLoad' in this) && childLoad && childLoad();
This will make sure childLoad can be referenced, makes sure it's not undefined, then call the function. It doesn't check to make sure it is a function, but I personally feel that is not needed.
NOTE: this might not be the context you are referring to if you are using call or apply. It really depends on the rest of your code.
A: You can simply check:
if (childLoad)
childLoad()
A: You could surround it in a try catch!
A: <script>
/* yourfunction */
if(typeof yourfunction == 'function') {
yourfunction();
}
function yourfunction(){
//function code
}
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: If no value selected from dropdown, allow textbox to add to database VB.net I have a dropdown list that will add new titles to my database, however I would like to add a textbox that will allow the user to type in a new title if there is nothing in the dropdown that makes any sense for what they are trying to add.
I have the dropdown dynamically getting titles from the database. Unfortunately, this means that the first value in the dropdown list is not a default that says "Select an option." I don't know how to get the dropdown to have the first option listed as "Select" when the values are being pulled from the database. I can't add Select an option to the database so how would this even work?
What can I add to my codebehind that will allow the textbox to insert into the database if the dropdown list is not inserting anything? Right now I don't have any codebehind for the textbox but I do have the dropdown list inserting the correct information.
<li class="alternatingItem">
<asp:LinkButton ID="DescButton" runat="server">Description</asp:LinkButton>
<asp:Panel ID="DescPanel" runat="server" CssClass="modalPopup" Style="display:none">
<div class="PopupHeader">Add a Description</div>
Title:<asp:DropDownList ID="ddlDescription" runat="server" DataSourceID="dsNewDescription" DataTextField="Title" DataValueField="Title">
</asp:DropDownList><br />
New Title:<asp:TextBox ID="NewDescTitle" runat="server"></asp:TextBox><br />
Description:<asp:TextBox ID="Description" runat="server" TextMode="MultiLine">
</asp:TextBox><br />
<asp:Button ID="submitDescription" runat="server" Text="Submit" />
<asp:Button ID="CancelSubmitDesc" runat="server" Text="Cancel" />
</asp:Panel>
<asp:ModalPopupExtender ID="DescModal" runat="server" DropShadow="True"
DynamicServicePath="" Enabled="True" PopupControlID="DescPanel"
TargetControlID="DescButton">
</asp:ModalPopupExtender>
</li>
Protected Sub submitDescription_Click(ByVal sender As Object, ByVal e
As System.EventArgs) Handles submitDescription.Click
DescModal.Hide()
'SQL INSERT: Marketing Table
Dim strSQL As String = "INSERT INTO Picklist (Title, Data)
VALUES (@Title, @Data);
INSERT INTO Marketing
(ProductID, MarketingTypeID, MarketingTitle, MarketingData)
VALUES (@ProductID ,2, 'Description', scope_identity())"
Using cn As New SqlConnection
(System.Configuration.ConfigurationManager.ConnectionStrings
("LocalSqlServer").ConnectionString)
Using cmd As New SqlCommand(strSQL, cn)
cmd.Parameters.Add(New SqlParameter("@Title",
ddlDescription.SelectedValue))
cmd.Parameters.Add(New SqlParameter("@Data",
Description.Text))
cmd.Parameters.Add(New SqlParameter("@ProductID",
ProductID.Value))
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Response.Redirect(Request.RawUrl)
End Sub
WORKING CODE
Title:<asp:DropDownList ID="ddlDescription" runat="server"
DataSourceID="dsNewDescription" DataTextField="Title" DataValueField="Title"
enableViewstate="False" AutoPostBack="True" AppendDataBoundItems="True">
<asp:ListItem Text="Select below or enter new" Selected="True"></asp:ListItem>
If ddlDescription.SelectedValue <> "Select below or enter new" Then
cmd.Parameters.Add(New SqlParameter("@Title", ddlDescription.SelectedValue))
Else
cmd.Parameters.Add(New SqlParameter("@Title", NewDescTitle.Text))
End If
A: You can try something like this:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" onblur="validateSelection(this)" ...>
<asp:ListItem Text="" Value="" />
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server" style="display:none;" ... />
Your JavaScript function (not positive, but it should be close):
validateSelection = function(selectList){
var input = document.getElementById("<%=TextBox1.ClientID%>");
if (input){
input.style.display = selectList.selectedIndex > -1 ? "block" : "none";
if (selectList.selectedIndex > -1){
input.focus();
}
}
}
And in your code-behind:
string description = TextBox1.Text;
if (!String.IsNullOrEmpty(DropDownList1.SelectedValue))
description = DropDownList1.SelectedValue;
A: Enforce that the user has either an item selected in the dropdown, or valid value typed into the textbox, but not both. (Implement this using ASP validators, or your favorite home-grown approach). With that protection in place, it's easy:
Within your button event handler, evaluate whether ddlDescription has a selected value: if so, use it as the parameter (just like your code is already doing). If not, use the value of your text box.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add "Share" action to feed dialog? Does anyone know how to make the "Share" option appear next to the "Like" and "Comment" actions in posts generated through the feed dialog?
I can see that the "actions" property might support this, but I don't see any "share" dialog that could be plugged into the link (and the "send" dialog only sends private messages).
What I am looking for is a way to generate a standard Facebook "share" link (with full public/private sharing options) as an "action" property.
Here is our current feed dialog code:
<a href='https://www.facebook.com/dialog/feed?app_id=126736467765&
link=https://apps.facebook.com/karmalyze/?reqtype=action%26actno=$actno&
picture=$post_pict&caption=karmalyze...%20your%20life!&name=$share_act_title&
description=$share_act_description&message=Yummy%20Karma!&
redirect_uri=https://apps.facebook.com/karmalyze/?reqtype=action%26actno=$actno'
title='Share This'><img class='vmidimage floatright' src='images/icon_kk_fb.png' alt='Like Icon' /></a>
I see the "Share" option on many posts. Is this just for posts that Facebook generates, or has someone cracked this code for the rest of us? Thanks!
A: There is an approach that is messy but will do the job: use the action argument for the feed dialog.
function fbShare() {
//call the API
var obj = {
method: 'feed',
link: myLink,
picture: pic,
name: myNme,
caption: myCaption,
redirect_uri: 'http://facebook.com',
actions: {"name":"Share","link": url},
description: myDescription,
};
function callback(response) {
console.log(response);
}
FB.ui(obj, callback);
}
The actions url should be pretty much the same url as you are showing.
Drawbacks: you aren't given the option to post to someone else's wall and the redirect_uri, which must be present, winds up taking the user away from their wall.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JavaScript, Typescript switch statement: way to run same code for two cases? Is there a way to assign two different case values to the same block of code without copy and pasting? For example, below 68 and 40 should execute the same code, while 30 is not related.
case 68:
//Do something
break;
case 40:
//Do the same thing
break;
case 30:
//Do something different
break;
Is it incorrect to think something like this should work (even though it obviously doesn't)?
case 68 || 40:
//Do something
break;
case 30:
//Do something else
break;
A: Cleaner way to do that
if ([68, 48, 22, 53].indexOf(value) > -1)
//Do something
else if ([44, 1, 0, 24, 22].indexOf(value) > -1)
//Do another
You can do that for multiple values with the same result
A: case 68:
case 40:
// stuff
break;
A: Yes, you just put the related case statements next to each other, like this:
case 40: // Fallthrough
case 68:
// Do something
break;
case 30:
// Do something different
break;
The Fallthrough comment is there for two reasons:
*
*It reassures human readers that you're doing this deliberately
*It silences warnings from Lint-like tools that issue warnings about possible accidental fallthrough.
A: Just put them right after each other without a break
switch (myVar) {
case 68:
case 40:
// Do stuff
break;
case 30:
// Do stuff
break;
}
A: Switch cases can be clubbed as shown in the dig.
Also, It is not limited to just two cases, you can extend it to any no. of cases.
A: You should use:
switch condition {
case 1,2,3:
// do something
case 4,5:
// do something
default:
// do something
}
Cases should be comma-separated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "77"
}
|
Q: Parsing arguments from command line for shell script I am still a junior with the linux shell script and would like help with a certain script.
I would run a sample shell script such as the following from the command line that takes in a directory as an argument:
./script.sh /some_dir/some_exe
How can I parse out the "some_dir" in my shell script?
Thanks.
A: The dirname command extracts the directory name from a string; so
THEDIR=`basename "$1"`
should do the trick.
A: If you are using Bash, it should be stored in $1. I'm pretty sure it's the same for other shells.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C# Problem with a List Displaying in a Textbox I have a small application that has several checkboxes, a submit button, and a textbox. I want the user to be able to check what they want, click the submit button, and have the results display in the textbox. The application runs but instead of the values displaying I get "System.Collections.Generic.List`1[System.String]" displayed in the textbox. I am very new to this and would appreciate any help. My code is as follows...
namespace MY_App
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> ls = new List<string>();
private void Checkbox1_CheckedChanged(object sender, EventArgs e)
{
ls.Add( "P.C. ");
}
private void Checkbox2_CheckedChanged(object sender, EventArgs e)
{
ls.Add( "WYSE Terminal" );
}
private void Checkbox3_CheckedChanged(object sender, EventArgs e)
{
ls.Add("Dual Monitors ");
}
private void button1_Click(object sender, EventArgs e)
{
string line = string.Join(",", ls.ToString());
textBoxTEST.Text = line;
}
private void textBoxTEST_TextChanged(object sender, EventArgs e)
{
}
A: ls.ToString() calls Object.ToString, i.e., the List class does not presume to know how you would like to print out its internal values. If you want to create a display string you will need to pass in an array of strings to String.Join, not the output of List<T>.ToString().
string line = string.Join(",", ls.ToArray());
textBoxTEST.Text = line;
A: You are trying to concat the object name, because of ls.ToString() will returns exactly what you've got in your TextBox.
Instead, use the following:
string line = string.Join(",", ls.ToArray());
textBoxTEST.Text = line;
Also, here is Linq solution:
ls.Aggregate((i, j) => i + ","+ j)
A: The first problem you have is with your CheckChanged events. They should probably only add to the List under two conditions. The first is the CheckBox.IsChecked == true and if they don't already exist in the list.
You shouldn't use string.Join with ls.ToString(). Use ToArray.
to handle the SelectionChanged:
private void myCheckBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
myTextBox.Text = myCheckBox.IsChecked ? myTextBox.Text = "The Value" : myTextBox.Text = string.Empty;
}
A: You would have to rewrite your button click event:
var sb = new StringBuilder();
Foreach( var item in ls)
{
sb.Append(String.Format("{0} , ",item));
}
textboxTEST.Text = sb.ToString();
You could even change this so that after your last item you don't get the " , " but i think you can solve that. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP Selecting multiple select options from MySQL I am trying to load a mulitple select from the database to edit.
I am storing the original data in an imploded string (ie "4, 6, 8, 9").
What I want to do is explode that string from the database, then have the values selected when the edit form is loaded. The values are Float, then 1-52.
Here is the code I have so far, but it does not select the values.
$listing->getWeeksAvail() is just a call that returns the WeeksAvail property in this case "4, 6, 8, 9)
<?php
$weeks_available = explode(",", $listing->getWeeksAvail());
if (in_array("Float", $weeks_available)) {
echo " selected='selected'";
}
?>
>Float</option>
<?php
for($float=0; $float<=52; $float++) {
echo "<option value=\"$float\"";
if (($listing instanceof listing) && $float == $listing->getWeeksAvail()) {
echo " selected='selected'";
}
echo ">$float</option>\n";
}
A: you can try
<?php
$week_available = explode(',', $listing->getWeeksAvail());
foreach ( range(1,42) as $week ) {
echo "<option value=\"$week\""
.(in_array($week,$week_available)?"selected=\"selected\"":"")
.">$week</option>";
}
A: The second part of your code should be like this:
<?php
for ($float=0; $float<=52; $float++) {
echo "<option value=\"$float\"";
if (in_array($float, $weeks_available))) {
echo " selected='selected'";
}
echo ">$float</option>\n";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Working with python dictionary notation I'm working on a program where the user inputs 3 values (one of which is in dictionary notation form).. but I'm having trouble finding out how to work with this special notation.
The user input will look like this:
{'X':'X+YF','Y':'FX-Y'}
which I store in a variable p. I know that with p.keys() I get ['X', 'Y'] and with p.values() I get ['X+YF', 'FX-Y'].
How can I relate 'X' to 'X+YF' to say, if the value of the first key in p is 'X', store 'X+YF' in a var, and if the value of the second key in p is 'Y', store 'FX-Y' in a var?
Is something like this also possible with the same approach stated in the answers below?
If x is found in some string :
swap out the X with the value p['X']
A: Are you asking how to get the value associated to a particular key? You can acess a value by putting its key in square brackets:
myDict = {'X':'X+YF','Y':'FX-Y'}
myXVal = myDict['X']
myYVal = myDict['Y']
print myXVal, myYVal
output:
X+YF FX-Y
If you want to have different behavior based on which keys exist in the dict, you can use in:
if 'X' in myDict:
#do some stuff with myDict['X'] here...
Edit in response to OP's edit:
My psychic debugging powers tells me that you're trying to implement an L System. You need to replace all instances of 'X' with 'X+YF', and all instances of 'Y' with 'FX-Y'. I would implement the function like this:
#path is the string that you want to do replacements in.
#replacementDict is the dict containing the key-value pairs mentioned in your post.
def iterateLSystem(path, replacementDict):
#strings aren't mutable, so we make a mutable list version of path
listPath = list(path)
for i in range(len(listPath)):
currentChar = listPath[i]
if currentChar in replacementDict:
listPath[i] = replacementDict[currentChar]
#glob listPath back into a single string
return "".join(listPath)
A: You can walk over the dictionary using its .items() method:
for key, value in p.items():
print key, value
# X X+YF
# Y FX-Y
# …
A: You can use .items() or .iteritems() to walk through the pairs:
>>> p = {'X':'X+YF','Y':'FX-Y'}
>>> for k, v in p.iteritems():
... print k, v
...
Y FX-Y
X X+YF
If you want to check the existence of some key, use in keyword:
>>> 'X' in p
True
>>> if 'Y' in p:
... print p['Y']
...
FX-Y
A: p = {'X':'X+YF','Y':'FX-Y'}
var = p['X']
Is that what you're looking for?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change animation speed of Jquery UI Accordion I'm using the Jquery UI Accordion, and I haven't found anywhere in the documentation on how to change the speed of the animation. I've found people suggest using option "animated: 'bounceslide'" but haven't been able to find what the different available options are for animated.
My current js is as follows
$( "#accordion" ).accordion({
event: "mouseover",
animate:"slow",
active:false
});
The "animate:"slow" is not correct and therefore not working. Any ideas?
A: This is currently not directly possible, although a feature request has been logged and is scheduled to implemented by the 1.9 milestone: http://bugs.jqueryui.com/ticket/3772. You can either wait for that release, or try the subclassing method described here: http://bugs.jqueryui.com/ticket/3533.
This boils down to:
$.extend($.ui.accordion.animations, {
fastslide: function(options) {
$.ui.accordion.animations.slide(options, { duration: 100 }); }
});
A: if you set the 'animated' to say swing then you can set the 'duration' of the animation in milliseconds.
e.g.
$( "#accordion" ).accordion({event: "mouseover", animated: 'swing', duration: 500, active:false
});
A: This works fine for me :
$("#accordion").accordion({
animate: {
duration: 500
}
});
A: Try using
speed: 50
Where 50 is the number of miliseconds
or
speed: 'slow'
instead of
animate:"slow",
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: provide a dialog to use browser inherent fullscreen on webapplications Is there a way to trigger a dialog to use browser built in Fullscreen? (And to leave fullscreen) (e.g. the mode of view that is usually accessible via f11)
Question Parameters:
I have a webGL webapplication where a common case of use is browsing the app for more than 10 minutes intensively.
During that time i would love to suggest fullscreen to users - so that the UI isn't interupted by browser differences and can use the most screen estate possible.
(There are several ways to create pop ups in Fullscreen - but that doesn't work on all browsers. In the best case: Non-modal Javascript accessable API to the browser functionality)
Chrome, Firefox, Opera, (IE) - solutions in that order of importance.
Please don't discuss question parameters if it can be avoided. Unless there is something important i have missed. =)
A: There are standards in the works, but don't count on that for another year or two... Standards approval are very slow. This is in part related to mouse locking, which is a nice feature being implemented currently on Chrome by Vincent Schieb from Google.
If you want to test the Fullscreen API working on Nightly Webkit browsers (e.g. Chrome Canary) here's the Javascript code that will make your page go fullscreen:
function fs() {
var elem = document.getElementById("test");
elem.onwebkitfullscreenchange = function () {
console.log ("We went fullscreen!");
};
elem.webkitRequestFullScreen ();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cron Process Keeps Being Killed in EngineYard I keep getting "FAILURE Process cron: is down" alerts in my engineyard application. A few minutes later I get a follow-up alert mentioning that the process is back up again. Has anyone ever noticed this issue before?
A: It turns out that engineyard is expecting a cron entry to touch a file every minute:
# This and the remote_file for cron_nanny go together
# Cron touches a file every minute
cron 'touch cron-check' do
minute '*'
hour '*'
day '*'
month '*'
weekday '*'
command 'touch /tmp/cron-check'
end
A compannion script called cron_nanny (/engineyard/bin/cron_nanny) checks the modification time of the touched file and if it is older than 120 seconds kills the crond process and restarts.
I happend to be deleting all cron entries in my custom chef-recipes, which caused the touch cron job to be removed, so every 120 seconds or so the cron_nanny script would restart the process.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: last modified file date in node.js I'm trying to retrieve the last modified date of a file on the server using node.js.
I've tried
file.lastModified;
and
file.lastModifiedDate;
both come back as undefined.
A: For node v 4.0.0 and later:
fs.stat("/dir/file.txt", function(err, stats){
var mtime = stats.mtime;
console.log(mtime);
});
or synchronously:
var stats = fs.statSync("/dir/file.txt");
var mtime = stats.mtime;
console.log(mtime);
A: Just adding what Sandro said, if you want to perform the check as fast as possible without having to parse a date or anything, just get a timestamp in milliseconds (number), use mtimeMs.
Asynchronous example:
require('fs').stat('package.json', (err, stat) => console.log(stat.mtimeMs));
Synchronous:
console.log(require('fs').statSync('package.json').mtimeMs);
A: With Async/Await:
const fs = require('fs').promises;
const lastModifiedDate = (await fs.stat(filePath)).mtime;
A: You should use the stat function :
According to the documentation :
fs.stat(path, [callback])
Asynchronous stat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. It looks like this:
{ dev: 2049
, ino: 305352
, mode: 16877
, nlink: 12
, uid: 1000
, gid: 1000
, rdev: 0
, size: 4096
, blksize: 4096
, blocks: 8
, atime: '2009-06-29T11:11:55Z'
, mtime: '2009-06-29T11:11:40Z'
, ctime: '2009-06-29T11:11:40Z'
}
As you can see, the mtime is the last modified time.
A: Here you can get the file's last modified time in seconds.
fs.stat("filename.json", function(err, stats){
let seconds = (new Date().getTime() - stats.mtime) / 1000;
console.log(`File modified ${seconds} ago`);
});
Outputs something like "File modified 300.9 seconds ago"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
}
|
Q: SSL cert failing to load only using Firefox Yesterday I moved a site to a new IIS7.5 server from an old IIS7.5 server.
The site contains an SSL cert. I exported it from the old server and imported it fine into the new enviroment.
Safari,Chrome & IE load the https ok however firefox keeps give me an error
Renegotiation is not allowed on this SSL socket.
(Error code: ssl_error_renegotiation_not_allowed)
What is wrong? why do all the other browsers work but not FF? I have stopped the site on the old server so I know its the new site been rendered.
Any suggestions?
A: This will happen if you have client authentication enabled for the website.
You need to click on the website -> SSL Settings -> Select Ignore under client authentication
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to enforce default value if user bypass non-required fields I have entity with email field like this, field is not required, I just do not want to have nulls in DB columns:
class Entity {
/**
* @ORM\Column()
* @Assert\NotNull()
*/
protected $email = '';
}
How can I enforce default value if user bypass this field in a form?
Now validator throws an error that field cannot be null.
A: If all you care about is not having nulls in the DB then a couple options:
*
*In the DB, assign a default value to the email column in the DB.
*In PHP, create a "NA" or similar value when the email is empty.
But your logic of having a non-required field unable to be blank does not make sense. You can either make it required or allow a null value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Zend Framework using IBM's DB2 and creating a standard connection in the application.ini file DB2 uses XML files as its basis for database tables, and I have been having a very difficult time finding any good references or examples of creating a standard connection to the database via the application.ini file. There are some examples from earlier versions using different connectors, but non that I could find that used the pdo_ibm adapter.
Any help or direction would be greatly appreciated.
A: Should be the same as any other database server:
resources.db.adapter = "PDO_IBM"
resources.db.params.host = "your.database.host"
resources.db.params.dbname = "database_name"
resources.db.params.username = "username"
resources.db.params.password = "password"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make SQLAlchemy COMMIT instead of ROLLBACK after a SELECT query I am developing an app together with a partner. I do the database part (PostgreSQL), my partner implements the app on the web-server with python using SQLAlchemy. We make heavy use of stored procedures. A SELECT query on one of those looks like this in the db log:
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SELECT col_a, col_b FROM f_stored_proc(E'myvalue');
ROLLBACK;
In the stored procedures I write certain input to a log table. The app queries by SELECT, SQLAlchemy only sees a SELECT statement and insists on a ROLLBACK. Logging fails. I need it to COMMIT instead. My partner claims there is no easy way, we would have to remove SQLAlchemy altogether. I think he must be wrong but lack the konwledge to claim otherwise.
Is there an easy way to make SQLAlchemy COMMIT instead of ROLLBACK?
What keeps me from just executing trans.commit()? Do I need to set autoflush=False for that?
I have scanned the FAQ, but did not find an answer there.
Searching SO revealed some related questions like here and here, but I am not in the clear.
Maybe this recipe would work?
A: If you're using SQLAlchemy's connection pooling, then what you're seeing is probably the automatic rollback that happens when a connection is closed after use. It's apparently necessary to guarantee that the connection is 'clean' for the next time it's pulled out of the pool. See this page for more info; search for 'pooling mechanism' near the top.
From what I recall (it's been a couple years since I last worked with this) changing the isolation level to autocommit won't solve the problem, since it won't see the SELECT statement as requiring a commit.
You really just want to wrap that statement in a transaction. I don't know how your code is structured, but you should just be able to use SQLAlchemy's connection.begin and connection.commit. You could even just execute the BEGIN and COMMIT as arbitrary SQL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: PHP Building array from traversing a nested tree model I have a typical nested tree model and I want to build an array with a 'children' array based on the levels or depths, but it doesn't seem to be working for me. Here's what I have now:
while($this->tax->getTreeNext($nodes))
{
$level = $this->tax->getTreeLevel($nodes);
if($level != 0){
echo $level . '-' . $current_level;
if($level > $current_level){
$terms[$i] = array(
'term_id' => $terms[$i-1]['term_id'],
'name' => $terms[$i-1]['name'],
'level' => $terms[$i-1]['level'],
'children' => array(
'term_id' => $nodes['row']['term_id'],
'name' => $nodes['row']['name'],
'level' => $level,
)
);
unset($terms[$i-1]);
}else{
$terms[$i] = array(
'term_id' => $nodes['row']['term_id'],
'name' => $nodes['row']['name'],
'level' => $level
);
}
$current_level = $level;
$i++;
}
}
This works for a single child, but not if the children have children... any suggestions how to fix this?
Thank you!
Edit:
This is the latest that appears to be close to working:
function process(&$arr, &$prev_sub = null, $cur_depth = 1) {
$cur_sub = array();
while($line = current($arr)){
if($line['depth'] < $cur_depth){
return $cur_sub;
}elseif($line['depth'] > $cur_depth){
$prev_sub = $this->process($arr, $cur_sub, $cur_depth + 1 );
}else{
$cur_sub[$line['term_id']] = array('term_id' => $line['term_id'], 'name' => $line['name']);
$prev_sub =& $cur_sub[$line['term_id']];
next($arr);
}
}
return $cur_sub;
}
The tree is passed into this with depth values associated to each node. The current problem is with the elseif($line['depth'] > $cur_depth). If a node has children, it only returns arrays for the children, but it does not include that nodes name or term_id.
Thank you!
A: Since I do not really get how your current data structures looks like, take a look at this trivial example of traversing a tree.
$treeRoot = $this->tax->getRoot();
$result = traverse($treeRoot, 0);
function traverse($root, $level){
$arr = array();
$arr['term_id'] = $root['row']['term_id'];
$arr['name'] = $root['row']['name'];
$arr['level'] = $level;
while($child = $root->getNextChild()){
$arr['children'][] = traverse($child, $level+1);
}
return $arr;
}
So you start at the tree root, and fill the first level of array. Then you continue with root's children, but you go one level deeper. You do exactly the same thing as with the root, you fill in the data and go to children's children. When you reach the bottom of the tree, the last (grandgrandgrand)child finds out it's got no children left, so it just returns itself(normal array) to its parent. That parent returns itself back to its parent, and so on, till you reach the root again.
And voilà, you've got yourself a nested array. Typically you'd leave this kind of structure as a tree, but since I do not know what exactly do you want your result to be (your provided no example), use the above code as a reference for your own implementation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Date range Question I want to show data from the last month (not form months past though), this month and any futures data in my report. In a SQL view, how can you do this with the date fields called date?
A: Alternatively in SQL Server you could use this simple comparison:
…
WHERE DateColumn >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0)
…
A: I'm assuming you are using SQL Server, in which case use the DATEDIFF function to see if the date in your table is within the range you want to display.
Information on the function can be found here: http://msdn.microsoft.com/en-us/library/ms189794.aspx
A: there is a built in function in SQL Server to add the date .. and for your date field named as date select it as [date]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Clicking on a flash button with Selenium I'm writing some tests with Selenium RC (on C#) for our project, which uses Ext.NET, and everything was fine, before I've faced the fact, that "Upload" button used for uploading files is made on Flash.
It is inserted like this:
<embed width="63" height="30" align="middle" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="opaque" allowscriptaccess="sameDomain" name="adaxuploaderaddon1317040891508" bgcolor="#FFFFFF" quality="high" src="/CuteWebUI_Uploader_Resource.axd?type=file&file=uploader10.swf&_ver=1317040891509" scale="exactfit" onerror="adaxuploaderaddon1317040891508_onerror()" style="z-index: 123454; width: 63px; height: 30px; opacity: 0.01; background-color: transparent;">
So, at first I've tried this:
selenium.Click("//embed[contains(@name, 'adaxuploaderaddon')]
Of course, it didn't worked :) Then I've tried several variations, like using mouseDown, mouseUp, using clickAt, location element with css (css=embed) - but still, no luck.
In Google people say, that it's possible to click the button with Javascript, but I haven't found any good examples.
Does anyone faced this problem before?
Thanks in advance.
A: you can communicate with 'IJavaScriptExecutor' & 'ExecuteScript' and pilote your flash (search about ExternalInterface for more details). For exemple i take a youtube page, and pause the video :
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://www.youtube.com/watch?v=2ac4hKSfQ9s");
driver.Manage().Window.Maximize();
((IJavaScriptExecutor)driver).ExecuteScript("var movie = window.document.getElementById('movie_player');"+
"console.log(movie);"+
"movie.pauseVideo();");
driver.Quit();
So, this is a solution but here you not click but directly calling the AS3 function on click.
Hope that help :)
A: You can use flashvars to communicate with the embedded swf file.
A: are you able to detect the upload button ?
if not use the object-id or class-id in the javascript that calling the flash used for flash upload button. Hope this may work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problem in including an external library while compiling a C++ program I'm using Dev C++ on windows 7, and WinPcap (developer's pack). Dev c++ is not able to find pcap.h apparently, even though I include the /include/ directory in project options, on compilation it displays an error saying "pcap.h: no such file or directory." (along with many other errors).
Here is my code:
#include <stdlib.h>
#include <stdio.h>
#include <pcap.h>
int main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
u_char packet[100];
return 0;
}
I've kept it simple. I was originally working in Visual Studio (C++), but distributing code compiled with Visual C++ requires Microsoft C Runtime library to be installed on the target system. I just want to be able to distribute the final executable and get it to work on any machine.
I checked the commmand line given to compiler. It did have the -I [path] option. Well is there anything I'm missing?
As a side note: I had compiled the above code with g++ (from dev c++ installation dir), and it compiled correctly. But when I tried to link it, the executable produced, just crashed on being run.
A: Your question is a little unclear, but your side-note makes it sound as if you could compile this (i.e. the pcap.h header was found) and your issues is with linking.
To add directories to the search path for libraries use -LPATH where PATH is the actual directory containing libpcap. To actually add it to the link use -lpcap in the linker call, e.g.
$ g++ -o main -LPATH main.o -lpcap
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails 3.1 Assets Problem in Dev mode I am developing a rails 3.1 application.
I put 7 images in app/assets/images//.
A page is supposed to show the 7 images. But my browser doesn't display all the images. Some images are not displayed randomly. Sometimes #1, 2, 3 images are not displayed and other times #6,7 images are not displayed.
If I type the image address in the address field, the image displays well.
This only happened in dev mode. Production mode displays them well.
Has anybody experienced the same thing?
Thanks.
Sam
A: This can sometimes happen if Sprockets' local cache gets corrupted or saves a blank image. Try deleting the tmp/cache/assets folder and restarting your app. Do a forced refresh on the browser to to ensure all images are refetched.
The cache-buster query string is not used in 3.1. This has been replaced with a fingerprinting system (see the asset pipeline guide for more).
If this is an upgraded app, check the settings in your environment files (from the guide) to make sure all the options are set correctly for each mode. Some combinations of setting can cause weird stuff to happen with images.
A: What webserver are you using?
I've encountered the same when using passenger. Found some posts advising to switch to thin, which solved the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python RuntimeWarning: overflow encountered in long scalars I am new to programming. In my latest Python 2.7 project I encountered the following:
RuntimeWarning: overflow encountered in long_scalars
Could someone please elaborate what this means and what I could do to fix that?
The code runs through, but I'm not sure if it is a good idea to just ignore the warning.
It happens during an append process like:
SomeList.append(VeryLongFormula)
A: Here's an example which issues the same warning:
import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a
yields
RuntimeWarning: overflow encountered in long_scalars
In the example above it happens because a is of dtype int32, and the maximim value storable in an int32 is 2**31-1. Since 10**10 > 2**32-1, the exponentiation results in a number that is bigger than that which can be stored in an int32.
Note that you can not rely on np.seterr(all='warn') to catch all overflow
errors in numpy. For example, on 32-bit NumPy
>>> np.multiply.reduce(np.arange(21)+1)
-1195114496
while on 64-bit NumPy:
>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848
Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals
In [47]: import math
In [48]: math.factorial(21)
Out[50]: 51090942171709440000L
According to numpy developer, Robert Kern,
Unlike true floating point errors (where the hardware FPU sets a
flag
whenever it does an atomic operation that overflows), we need to
implement the integer overflow detection ourselves. We do it on
the
scalars, but not arrays because it would be too slow to implement
for
every atomic operation on arrays.
So the burden is on you to choose appropriate dtypes so that no operation overflows.
A: An easy way to overcome this problem is to use 64 bit type
my_list = numpy.array(my_list, dtype=numpy.float64)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "86"
}
|
Q: iPhone Programming converting IplImage coordinates to UIImage coordinates I am making an application that shows the video feed in real time and I am processing the frames using OpenCV to detect faces present in them. To do this, I need to convert the frames into UIImage and then IplImage. Then I run the face detection and everything so far works great except that the coordinates captured when a face is detected are those for an IplImage and the origin starts at the bottom right corner... and I need coordinates with a top left origin.
In other words, I need to convert the coordinate points I have with a bottom right origin to coordinates with a top left origin. Does anyone know if there is a function to do this in Xcode? or where I can start to look to create one?
I need the coordinate points and cannot draw directly over the IplImage and convert back to UIImage to display because I am using the coordinate points I get from the face detection to do further processing.
Any help will be greatly appreciated :)
Thanks!
A: If the UIImage and IPLImage are the same height can't you just subtract the y coordinate from the image's height?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL Shorten Query - SELECT with mutliple OR choices Here is the query I have
SELECT FB_TEXT
FROM `FB_DATA`
WHERE `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID = 1
What I want to do is allow multiple FB_TYPEID's so the query should be like:
AND FB_TYPEID = 1,2,7
1, 2, and 7 are the numbers I need allowed. How can I write that without making a long query saying:
SELECT FB_TEXT
FROM `FB_DATA`
WHERE `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID = 1 OR `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID = 2 OR `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID = 7
A: Use IN instead of = :
WHERE `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID IN (1,2,7)
A: The IN() operator is the right answer but if you dont want (or can't) use IN() you dont need to repeat the model id. This query is equivilent to the IN() solution.
SELECT FB_TEXT
FROM `FB_DATA`
WHERE `FB_MODELID` = "'.$sku_modelid.'" AND (FB_TYPEID = 1 OR FB_TYPEID = 2 OR FB_TYPEID = 7)
A: Use IN():
WHERE `FB_MODELID` = ? AND FB_TYPEID IN (1,2,7)
(ps use placeholders in your queries to prevent SQL injection attacks)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can you submit data from a web page to Flurry Analytics? We have developed an iPhone, Android, and BlackBerry app for our product. We also have an ASP.NET MVC mobile website that provides the same content as the native apps for any of the sorry folks who don't have a device that supports one of the native apps.
We are successfully using the Flurry SDKs to submit data for our iPhone, Android, and Blackberry apps but would also like to submit and track the same data for our mobile website. Each platform has the exact same screens as the other, so it makes sense to have all of the analytic data recorded in the same manner, and reported in the same interface.
We are aware of Google Analytics and Google Analytics for Mobile but again, we want our clients to be able to view report on all platforms from the same system.
Is it possible to submit data to Flurry without using a native mobile SDK? It seems they only give you options to add a native application in the "Add an Application" configuration on their site - how would you add a mobile website?
If someone has done this before, I would love to hear the details. Thanks.
A: Flurry released their Mobile Web SDK 1.0.0 on 06/27/2013.
You can download the documentation by creating a new project and choosing "Mobile Web" then visiting the Download SDK page.
The API is in Javascript.
However, Flurry support specified by email that
The Mobile Web SDK is no longer updated and the support we provide for this
SDK is limited.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: median of three values strategy What is the median of three strategy to select the pivot value in quick sort?
I am reading it on the web, but I couldn't figure it out what exactly it is? And also how it is better than the randomized quick sort.
A: The common/vanilla quicksort selects as a pivot the rightmost element. This has the consequence that it exhibits pathological performance O(N²) for a number of cases. In particular the sorted and the reverse sorted collections. In both cases the rightmost element is the worst possible element to select as a pivot. The pivot is ideally thought to me in the middle of the partitioning. The partitioning is supposed to split the data with the pivot into two sections, a low and a high section. Low section being lower than the pivot, the high section being higher.
Median-of-three pivot selection:
*
*select leftmost, middle and rightmost element
*order them to the left partition, pivot and right partition. Use the pivot in the same fashion as regular quicksort.
The common pathologies O(N²) of sorted / reverse sorted inputs are mitigated by this. It is still easy to create pathological inputs to median-of-three. But it is a constructed and malicious use. Not a natural ordering.
Randomized pivot:
*
*select a random pivot. Use this as a regular pivot element.
If random, this does not exhibit pathological O(N²) behavior. The random pivot is usually quite likely computationally intensive for a generic sort and as such undesirable. And if it's not random (i.e. srand(0); , rand(), predictable and vulnerable to the same O(N²) exploit as above.
Note that the random pivot does not benefit from selecting more than one element. Mainly because the effect of the median is already intrinsic, and a random value is more computationally intensive than the ordering of two elements.
A: Think simple... Python example....
def bigger(a,b): #Find the bigger of two numbers ...
if a > b:
return a
else:
return b
def biggest(a,b,c): #Find the biggest of three numbers ...
return bigger(a,bigger(b,c))
def median(a,b,c): #Just dance!
x = biggest(a,b,c)
if x == a:
return bigger(b,c)
if x == b:
return bigger(a,c)
else:
return bigger(a,b)
A: The median of three has you look at the first, middle and last elements of the array, and choose the median of those three elements as the pivot.
To get the "full effect" of the median of three, it's also important to sort those three items, not just use the median as the pivot -- this doesn't affect what's chosen as the pivot in the current iteration, but can/will affect what's used as the pivot in the next recursive call, which helps to limit the bad behavior for a few initial orderings (one that turns out to be particularly bad in many cases is an array that's sorted, except for having the smallest element at the high end of the array (or largest element at the low end). For example:
Compared to picking the pivot randomly:
*
*It ensures that one common case (fully sorted data) remains optimal.
*It's more difficult to manipulate into giving the worst case.
*A PRNG is often relatively slow.
That second point probably bears a bit more explanation. If you used the obvious (rand()) random number generator, it's fairly easy (for many cases, anyway) for somebody to arrange the elements so it'll continually choose poor pivots. This can be a serious concern for something like a web server that may be sorting data that's been entered by a potential attacker, who could mount a DoS attack by getting your server to waste a lot of time sorting the data. In a case like this, you could use a truly random seed, or you could include your own PRNG instead of using rand() -- or you use use Median of three, which also has the other advantages mentioned.
On the other hand, if you use a sufficiently random generator (e.g., a hardware generator or encryption in counter mode) it's probably more difficult to force a bad case than it is for a median of three selection. At the same time, achieving that level of randomness typically has quite a bit of overhead of its own, so unless you really expect to be attacked in this case, it's probably not worthwhile (and if you do, it's probably worth at least considering an alternative that guarantees O(N log N) worst case, such as a merge sort or heap sort.
A: This strategy consists of choosing three numbers deterministically or randomly and then use their median as pivot.
This would be better because it reduces the probability of finding "bad" pivots.
A: We can understand the strategy of median of three by an example, suppose we are given an array:
[8, 2, 4, 5, 7, 1]
So the leftmost element is 8, and rightmost element is 1. The middle element is 4, since for any array of length 2k, we will choose the kth element.
And then we sort this three elements in either ascending order or descending order which gives us:
[1, 4, 8]
Thus, the median is 4. And we use 4 as our pivot.
On the implementation side, we can have:
// javascript
function findMedianOfThree(array) {
var len = array.length;
var firstElement = array[0];
var lastElement = array[len-1];
var middleIndex = len%2 ? (len-1)/2 : (len/2)-1;
var middleElement = array[middleIndex];
var sortedArray = [firstElement, lastElement, middleElement].sort(function(a, b) {
return a < b; //descending order in this case
});
return sortedArray[1];
}
Another way to implement it is inspired by @kwrl, and I'd like to explain it a little bit clearer:
// javascript
function findMedian(first, second, third) {
if ((second - first) * (third - first) < 0) {
return first;
}else if ((first - second) * (third - second) < 0) {
return second;
}else if ((first - third)*(second - third) < 0) {
return third;
}
}
function findMedianOfThree(array) {
var len = array.length;
var firstElement = array[0];
var lastElement = array[len-1];
var middleIndex = len%2 ? (len-1)/2 : (len/2)-1;
var middleElement = array[middleIndex];
var medianValue = findMedian(firstElement, lastElement, middleElement);
return medianValue;
}
Consider the function findMedian, first element will be return only when second Element > first Element > third Element and third Element > first Element > second Element, and in both cases: (second - first) * (third - first) < 0, the same reasoning apply to the remaining two cases.
The upside of using the second implementation is that it could have a better run time.
A: Think faster... C example....
int medianThree(int a, int b, int c) {
if ((a > b) ^ (a > c))
return a;
else if ((b < a) ^ (b < c))
return b;
else
return c;
}
This uses bitwise XOR operator. So you would read:
*
*Is a greater than exclusively one of the others? return a
*Is b smaller than exclusively one of the others? return b
*If none of above: return c
Note that by switching the comparison for b the method also covers all cases where some inputs are equal. Also that way we repeat the same comparison a > b is the same as b < a, smart compilers can reuse and optimize that.
The median approach is faster because it would lead to more evenly partitioning in array, since the partitioning is based on the pivot value.
In the worst case scenario with a random pick or a fixed pick you would partition every array into an array containing just the pivot and another array with the rest, leading to an O(n²) complexity.
Using the median approach you make sure that won't happen, but instead you are introducing an overhead for calculating the median.
EDIT:
Benchmarks results show XOR is 32 times faster than Bigger even though I optimized Bigger a little:
You need to recall that XOR is actually a very basic operator of the CPU's Arithmetic Logic Unit (ALU), then although in C it may seem a bit hacky, under the hood it is compiling to the very efficient XOR assembly operator.
A: An implementation of Median of Three I've found works well in my quick sorts.
(Python)
# Get the median of three of the array, changing the array as you do.
# arr = Data Structure (List)
# left = Left most index into list to find MOT on.
# right = Right most index into list to find MOT on
def MedianOfThree(arr, left, right):
mid = (left + right)/2
if arr[right] < arr[left]:
Swap(arr, left, right)
if arr[mid] < arr[left]:
Swap(arr, mid, left)
if arr[right] < arr[mid]:
Swap(arr, right, mid)
return mid
# Generic Swap for manipulating list data.
def Swap(arr, left, right):
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
A: I think rearranging the values in the array is not necessary for just three values. Just compare all of them by subtracting; then you can decide which one is the median value:
// javascript:
var median_of_3 = function(a, b, c) {
return ((a-b)*(b-c) > -1 ? b : ((a-b)*(a-c) < 1 ? a : c));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: DDD: Model local identity inside agregate root after reading the blue book (Eric Evan's Domain Driven Design) and starting applying the DDD concepts in a simple blog like application I have the following question, how do you model a local identity of an entity inside an aggregate root??
Let's say for the sake of simplicity, I have a simple blog model that has the following entities and scenarios:
A registered user can publish a post, a post can have one or more tags associated and a registered or unregistered user can publish a comment on a post.
In this scenario, the entities are User, Post, and Comment, the aggregate roots are User na Post being comment an aggregate inside Post aggregate root.
So since the comment entity has a local identity inside Post how do I model its local identity?? I.E. I cannot differenciate a comment just by it's attributes since I can have twho different comments for the same post published by the same user with the same content...
I first thought of the order of the comment inside the post's comment list to identify the comment inside the post, but this becomes very complex in concurrent environments, like a web application where two clients can post comments on blogs and I would have collisions until I store them in the database. Besides that I need to keep the logic for restoring the comment list from repository in the same order the post was saved to the repository...
Then having a unique identifier counter inside the Post and autoincrement it with every comment published, but in concurrent environment becomes complex, so how do I model the local identity inside an aggregate root??
Thanks
Pablo
A: Good question. From Eric Evan's book:
ENTITIES inside the boundary have local identity, unique only within
the AGGREGATE.
...only AGGREGATE roots can be obtained directly with database queries. All other objects must be found by traversal of associations.
I think that the second part is what is important. You should be treating Comment Id as local identity. In other words you should not retrieve Comments bypassing its Aggregate Root (Post), reference Comments from the outside etc. Technically, Commend Id can be the same AUTOINCREMENT field generated by database, like you would have for User and Post (or any other id generator from hibernate). But conceptually Comment will have local identity. It is the job of the Aggregate Root to resolve it.
A: I'm no DDD expert, but I would argue that perhaps Comment should be a value object. A value object has no "conceptual identity," but it can certainly have a persistence identity. Usually, you should prefer using value objects over entities because the latter typically has more overhead.
Don't confuse persistence identity with conceptual identity. I had trouble understanding that in the beginning.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Extracting words from domain I have a bunch of domains I would like to explode into words. I downloaded wordlist from wordlist.sourceforge.net and started writing brute-force type of script to run each domain through dictionary list.
The problem is that I can't get it to produce good enough results. The simple script I did looks like this:
foreach($domains as $dom) {
$orig_dom = $dom;
foreach($words as $w) {
$pos = stristr($dom,$w);
if($pos) {
$wd[$orig_dom][] = $w;
}
}
}
$words is dictionary array and domains is just an array of domain names.
Results looks like this:
[aheadsoftware] => Array
(
[0] => ahead
[1] => head
[2] => heads
[3] => soft
[4] => software
[5] => ware
Technically it works but the thing I don't know how to code is the trick to get the script to understand that if you match 'ahead', you don't have 'head' or 'heads' anymore. It should also understand to pick 'software' instead of 'soft' and 'ware'. Yes I know, world of linguistic computing is pure pain ;)
A: A naive solution could be every time you have a match and before you add the word in to the results do another stristr lookup and see if the word you are trying to put in to the results is contained in any of the words already in there. If it is, don't add it in.
This would not work for example if the domain contains 'heads' and your dictionary lists 'head' first. You may rather have 'heads' added in to the results instead of 'head'.
You can get around that limitation by checking to see which one is longer. If the word contained in your results is longer, do not add the new word in. If the new word is longer, remove the one already in the results and add the new one in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Eliminate duplicates within a same table I want to get an email list from a table for specific dates.
Select email FROM clients
WHERE MONTH(created)=08
GROUP BY email
I would like to eliminate the email if it already existed before in the table. so if he was created before the month 08. (an email can be created multiple times because I work for a login site). Can anybody help me out.
Thank you
A: You could first build a list of unique emails with their earliest created dates, then select from that list picking only those that were created in the month you want:
SELECT
email
FROM (
SELECT
email,
MIN(created) AS created
FROM clients
GROUP BY
email
) s
WHERE MONTH(created)=08
A: This works in MySql:
DROP TEMPORARY TABLE IF EXISTS p;
CREATE TEMPORARY table p (email VARCHAR(50));
INSERT INTO p
SELECT email FROM client
WHERE MONTH(created) = 8
GROUP BY email;
DELETE FROM client
WHERE email IN
(SELECT * FROM p)
AND MONTH(Created) < 8
Anyway, you could have problems with creation year...
EDITED: if you want to get only emails that weren't createed before month=8, try this:
DROP TEMPORARY TABLE IF EXISTS p;
CREATE TEMPORARY table p (email VARCHAR(50));
INSERT INTO p
SELECT email FROM client
WHERE MONTH(created) < 8
GROUP BY email;
SELECT email FROM client
WHERE
MONTH(created)=8 AND
email NOT IN (SELECT * FROM p)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Raising control event to be handled by completely separate part of .Net Web application Folks,
I have a feeling there's a classic design pattern that covers this case, but I don't have a reference handy.
I have a situation where a user clicks a button and another part of the web page responds. What's unusual (or at least inconvenient) is that the button and the reponding part of the web page are in very different control hierarchies, both in terms of distance to common ancestor and in terms of application concern. They're both inner parts of a series of (separate) black boxes.
I have not been able to come up with an elegant way for the one to trigger the other. I do not want to have to raise a series of events up to the top of the control hierarchy and then call a series of nested methods to make the desired effect happen. ("effect" != visual effect; I can't solve this with jQuery) I want the event and the responder to remain ignorant of each other: I will not violate separation of concerns by having the latter know about and directly subscribe to an event generated by the former. I've considered a number of other inelegant solutions, but I won't bore you by listing them off.
Basically I guess I need a way to implement a publisher-subscriber model for events in which anything can subscribe to anything.
I'm using .Net 4.0. Any nice frameworks that do this? Any easy ways to implement it?
Thanks a lot,
Ann L.
A: Sounds like you need an EventAggregator. You should find the implementation in the Composite Application Library.
The EventAggregator allows you to register to notifications and raise them from completely separated parts of the application.
A: For server side events you can use:
The Reactive Extensions (Rx)...
http://msdn.microsoft.com/en-us/data/gg577609
For Client side events you can use:
Backbone JS
http://documentcloud.github.com/backbone/
Knockout JS
http://knockoutjs.com/
You mentioned you couldn't use jQuery may I ask why?
A: I'm not sure if I understand you correctly, but it sounds like you want to assign multiple buttons to the same event handler, which you can do like this:
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button_Click" ... />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClick="Button_Click" ... />
In the code-behind:
protected void Button_Click(object sender, EventArgs e)
{
if (sender.Equals(Button1))
{
//Button1 logic
}
else if (sender.Equals(Button2))
{
//Button2 logic
}
}
EDIT
Based on your comment, it sounds like you might need an event handler. If so, try something like this:
public event EventHandler ButtonClick;
protected void Button_Click(object sender, EventArgs e)
{
if (this.ButtonClick != null)
this.ButtonClick(sender, e);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VSTO 4.0 Runtime Download Missing from MS? We have code that checks for the presence of the VSTO 4.0 runtime and downloads it, if missing. This has worked fine until today. It seems the VSTO runtime file has gone missing from MS. Does anyone know anything about this? Can we tell our clients it's an MS problem and will be cleared up shortly? Google doesn't find any comments about the file being removed.
Thanks.
A: Here is latest link: VSTO 2010 Runtime
EDIT: This is a 'permalink' and should always take you to latest and greatest
A: Note: the latest update to the VSTO Runtime (from November 2012) has merged the VSTO Runtime packages from two files (x86 and x64) to just one file. The download location has also moved. Follow this link for the latest version of the download page: http://go.microsoft.com/fwlink/?LinkId=140384 (referenced by MSDN documentation, such as http://msdn.microsoft.com/en-us/library/ms178739(v=vs.110).aspx).
If you're looking for a persistent link to the latest version of the runtime, you can use the same link that's referenced by the VSTOR Bootstrapper (used by ClickOnce installation). That link is http://go.microsoft.com/fwlink/?LinkId=158918.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Array object values not being added to ajax call The goal here is to have MVC framework recognize and populate a field in my action that is a FormCollection object. I can get it to work if I handle all the serialization myself but so far no dice if I leave it to jquery/javascript.
Question: What is causing the following array to be serialized as if it contained no data?
I checked the variable and it contains one item just as expected (set elsewhere in code).
var formVars = new Array();
for (var item in gd["FormVariables"])
{
if (gd["FormVariables"][item] != null)
{
formVars[item.toString()] = gd["FormVariables"][item];
}
}
var args = {
Req: {
SelectedColId: gd["SelectedColId"],
CurrentPage: gd["CurrentPage"],
PageSize: gd["PageSize"],
RecordCount: gd["RecordCount"],
NumberOfPages: numOfPages,
MultipleSelection: gd["MultipleSelection"],
FormVariables: formVars
}
};
The issue with this is the behavior of the array ... if I do an alert(formVars); it appears empty even though it contains all the key/value pairs. Likewise, the FormVariables parameter is empty after JSON.stringify() does its work.
$.ajax(
{
traditional: true,
type: 'POST',
contentType: 'application/json',
dataType: 'json',
url: gd["Route"],
data: JSON.stringify(args),
success: function (data, textStatus, jqXHR)
{
},
error: function (jq, status, err)
{
alert(status);
}
});
}
serialized output:
'{"Req":
{
"SelectedColId":"",
"CurrentPage":1,
"PageSize":15,
"RecordCount":0,
"NumberOfPages":2,
"MultipleSelection":false,
"FormVariables":[]
}
}'
what is going wrong here?
EDIT: gd contents
{
Height: 300,
FetchType: 1,
Route: '../GetTrainingDocuments/',
SelectedColId: '',
PageSize: 15,
CurrentPage: 1,
RecordCount: 0,
HasMoreRecords: true,
NumberOfPages: 1,
MultipleSelection: false,
FormVariables: function()
{
if (this.array == 'undefined')
{
this.array = [];
}
return this.array;
}
}
The Model it should bind to:
public ActionResult GetTrainingDocuments(GridRequest req)
{
//...
}
public class GridRequest
{
public string SelectedColId { get; set; }
public int CurrentPage { get; set; }
public int PageSize { get; set; }
public int RecordCount { get; set; }
public int NumberOfPages { get; set; }
public string Widths { get; set; }
public bool MultipleSelection { get; set; }
public FormCollection FormVariables { get; set; }
public GridRequest()
{
}
}
A: You have declared the formVars variable as array an yet here: formVars[item.toString()] you are trying to address it by some value that is probably not an integer. In javascript array must have 0 based integer indexes. So instead of:
formVars[item.toString()] = gd["FormVariables"][item];
if you want to use an array you need:
formVars.push(gd["FormVariables"][item]);
or if you wanted to preserve the item as key:
formVars.push({ key: item, value: gd["FormVariables"][item] });
If you want FormVariables to be an object (i.e. an associative array in javascript) then:
var formVars = {};
for (var item in gd["FormVariables"])
{
if (gd["FormVariables"][item] != null)
{
formVars[item.toString()] = gd["FormVariables"][item];
}
}
It really depends on what view model you are trying to bind this on the server side.
UPDATE:
Now that you have posted your gd variable, looking at the FormVariables property, it looks very strange:
FormVariables: function() {
if (this.array == 'undefined') {
this.array = [];
}
return this.array;
}
This will always return an empty array which limits the usefulness of such structure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Show the Windows Media Player on a Windows Form (or Show the output of a process on a WinFom) I am trying to launch Windows Media Player through Process.Start. I am able to start the wmplayer.exe and with filename as argument its playing the file. But it is playing in Media Player Window. I need to show the media instead on my own form. Is it possible to do it? MPlayer, an opensource media player has an option called "-wid" which will tell Mplayer to show output inside our form. I am trying to do something same with WMP.
I know WMP has activex control and we can embed it on a winforms to play any video. But I have encountered some problems with this way. So thinking to launch WMP as a process and play the media on my forms.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Submit button's value disappears onClick I have a simple form that takes in a user's e-mail address (the form appears when "E-mail" link clicked on). Everything appears to function correctly, except that the value for the submit button disappears onClick or onSubmit. I can't seem to track down the issue. Please reference here. This issue only appears to affect IE. I'd prefer not to show PHP processing - but if necessary I'll show what I can. Basically, just wondering if anyone can spot any syntax errors that might be causing this, or if anyone has a solution.
Form:
<div id="formContainer">
<form action="http://www.example.com/catalog/scripts/email.php" method="post" id="contactForm">
<input type="text" name="email" value="E-mail Address" id="email" style="padding-left:5px; font:bold 11px Arial;"/>
<input type="text" name="last" value="" id="last" />
<input type="hidden" name="id" value="'.$_GET['id'].'">
<input type="submit" value="Submit" id="contactSubmit"/>
</form>
</div>
JS:
<script>
$(document).ready(function() {var options = {target: '#alert'};
$('#contactForm').ajaxForm(options); });
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to do a query where a new column is added with with match results? How can I do a query where I fetch all items from table1 and than I compare each of table1 column2 items with table2 column2 items?
The final query would contain an extra column3 with a value 1 or 0 if a matched was found. Please see below example tables and expected result.
*
*table1:
_id col1 col2
--- ------- ----
0 Jon 25
1 Tim 24
2 Frank 38
3 Josh 234
4 Lettuse 23
5 Whally 12
*table2:
_id col1 col2
--- ----- ----
0 House 45
1 Dog 23
2 Pat 24
3 Lake 123
4 Water 43
5 Hot 2
*newTable1Results:
_id col1 col2 col3
--- ------- ---- ----
0 Jon 25 0
1 Tim 24 1
2 Frank 38 0
3 Josh 234 0
4 Lettuse 23 1
5 Whally 12 0
A: I think you're looking for something like this:
select t1._id, t1.col1, t1.col2, t2.col2 is not null as col3
from table1 t1
left outer join table2 t2 on t1.col2 = t2.col2
order by t1._id
SQLite's booleans are just zero and one so a simple t2.col2 is not null in your SELECT will give you your zero or one.
The above should give you this:
_id | col1 |col2 | col3
----+--------+-----+-----
0 | Jon | 25 | 0
1 | Tim | 24 | 1
2 | Frank | 38 | 0
3 | Josh | 234 | 0
4 | Lettuse| 23 | 1
5 | Whally | 12 | 0
A: You could use LEFT JOIN and compute the col3 column based on whether there was a match:
SELECT
t1.*,
CASE
WHEN t2._id IS NULL THEN 0
ELSE 1
END AS col3
FROM table1 t1
LEFT JOIN table2 t2 ON t1.col2 = t2.col2
In case table2.col2 could possibly contain duplicates, the above query might give you duplicates as well. You could try a different approach then:
SELECT
t1.*,
CASE
WHEN EXISTS (
SELECT *
FROM table2
WHERE col2 = table1.col2
)
THEN 1
ELSE 0
END AS col3
FROM table1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I write German language on a web page? I have to build a web page in German language. When I use some characters like ü (note the dots above the letter), it shows up like a question mark or black sign in the browser.
How do I solve this?
A: You could either use UTF-8 all throughout your project or instead of writing the ü you could write the htmlentity ü (also analogue: ä Ä etc ... And ßfor ß
PS: As a German myself... Our language is called Germ a n :)
A: The problem is that you're using the wrong encoding. Make sure that you're saving your web site as UTF-8 and put the following in your HTML <head> tag:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
A: Use utf8 encoding by adding the following header to your webpage:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
Also make sure your files are saved as utf8, this depends on your editor
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I override the Telerik MVC Grid editor popup when using ClientTemplates and AjaxBinding I've got a list of user roles that I'm trying to display in my grid column and trying to set up a custom template for in the edit pop-up.
I tried taking the tac of using the display/editor templates but found out that ajax binding doesn't support these (As the model is always null). So the fix for the column side is using .ClientTemplate on the column in question... which works in the following simplified example of my table...
@( Html.Telerik().Grid<UserSearchModel>()
.Name("Grid")
.DataKeys(keys => { keys.Add(p => p.UserId); })
.Columns(columns =>
{
columns.Bound(o => o.UserId).Visible(false) ;
if(Context.User.IsInRole("Admin")) columns.Bound(o=>o.CompanyName).Width(100);
columns.Bound(o => o.RolesModel).ClientTemplate("<strong><#= RolesModel.RoleName #></strong>");
columns.Command(commands =>
{
commands.Edit().ButtonType(type);
}).Width(180).Title("Commands");
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("_AjaxBinding", "Users")
.Update("Edit", "Users")
.Insert("Create", "Users")
)
.Resizable(resizing => resizing.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.Editable(editable => editable.Mode(GridEditMode.PopUp))
.Pageable(p=> p.PageSize(13))
.Sortable()
.Scrollable(scrolling => scrolling.Height("400px"))
.Groupable()
.Filterable()
)
But that doesn't pass over to the edit popup... so my question is how do I manage to override the popup to show a custom display for the column I've assigned the .ClientTemplate to?
I've tried using the WindowBuilder (.Window(w=>w.Content("...content stuff here...")) to no avail. The default edit window pops up each time.
A: For more information about editing of nested objects in ASP.NET MVC I will suggest you check this blog post.
Maybe this help topic will help too.
You can also specify partial view, which can be used as editor form:
.Editable(editing => editing.TemplateName("TemplateName"))
A: I was able to achieve the same functionality by using convention. I specified the GridEditMode as PopUp and then placed a view with the same name as my model at the following path
~/Views/Shared/EditorTemplate/ModelName.cshtml
I did this because the grid has children of the same type and I don't actually need to specify the template.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PL/SQL Exception Translation I am inserting a new object in my database table, but I keep on retrieving a exception that states....
ERROR:insertproperty:ORA-06553: PLS-103: Encountered the symbol "EXCEPTION" when expecting one of the following:
begin case declare exit for function goto if loop mod null
package pragma procedure raise return select separate type
update while with <an identifier>
<a double-quoted delimited-identifier> <a bind variable> <<
form table call close current define delete fetch lock insert
open rollback savepoint set sql execute commit forall merge
ORA-06553: PLS-103: Encountered the symbol "EXCEPTION" when expec
but all I am doing is a simple insert into...
function insert(...)
begin
begin
select table_seq.nextval
into nextval
from dual
begin
insert into table(id, ....)
values(nextval,....)
end
end
end
the dots are all optional so not really needed.
A: The error indicates that there is a syntax problem near the EXCEPTION keyword. But your code outline doesn't indicate that any of your blocks have an exception section. That makes it rather difficult for us to provide much assistance.
In a comment, you seem to indicate that at least one of the blocks in your outline has an exception section. Can you post the actual code (or at least a more detailed outline that includes the syntax of whatever exception block is generating the error)?
Additionally, in a comment, it sounds like you do have a RETURN statement in your function that is returning some sort of status code. It is almost always a mistake to use return codes from functions-- it is much more robust to simply throw an exception (or even better, allow the exception that was generated to propagate up). It is generally a mistake to write a function in PL/SQL that does DML-- if you're doing DML, you almost always want that to be done in a procedure.
A: Your function doesn't return a value. I think you want to make it a PROCEDURE (and add some semicolons, an "AS" keyword etc.):
CREATE OR REPLACE
PROCEDURE insert_proc(...)
AS
BEGIN
begin
select table_seq.nextval
into nextval
from dual;
begin
insert into table(id, ....)
values(nextval,....);
end;
end;
END insert_proc;
If you are using Oracle 11g, you can omit the call to the DUAL table:
CREATE OR REPLACE
PROCEDURE insert_proc(...)
AS
BEGIN
insert into table(id, ....)
values(nextvatable_seq.nextval,....);
END insert_proc;
N.B. You should add an exception section to handle any common exceptions that might occur, e.g. constraint violations etc.
Hope it helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Example of an elegant implementation of 'Defensive Copying' of a nullable java.util.Date in a JavaBean's getter/setter implementation? Is there an elegant Java implementation of Joshua Bloch's defensive copying techniques using the example below? The nullChecking is really the issue I think, but perhaps there is a much simpler way to achieve defensive copying.
public class Audit {
private Date dateCompleted;
...
public Audit() {
super();
}
//defensive copy of dateCompleted
public final Date getDateCompleted() {
if (dateCompleted != null){
return new Date(dateCompleted.getTime());
}else{
return null;
}
}
public final void setDateCompleted(Date dateCompleted) {
if (dateCompleted != null){
this.dateCompleted = new Date(dateCompleted.getTime());
}else{
this.dateCompleted = null;
}
}
...
}
A: Well you can have a convenience method in a utility class:
public class DateUtils {
public static Date defensiveCopy(Date date) {
return date == null ? null : new Date(date.getTime());
}
}
Then:
public final void setDateCompleted(Date dateCompleted) {
this.dateCompleted = DateUtils.defensiveCopy(dateCompleted);
}
Static imports can hide the DateUtils part if you want.
Alternatively, you can use Joda Time which mostly uses immutable types and is a much better API in general :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Analyzing log file in node.js is there any node module that I can use to analyze the log file? similar to Splunk but free. :)
By the way, I have 5 servers, each put its log into its server. what is the best wayto combine them all?
A: Perhaps something like Log.io is what you want? http://logio.org/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there an easy way to find the "javascript equivalent" of jQuery code? I am doing a presentation on jQuery for some co-workers and I would like to demonstrate how certain tasks in javascript can be made easier using jQuery.
I have come up with a small jQuery function that does some element selection/animation and I was hoping to show them the javascript equivalent of this code.
My problem is that my javascript is a bit rusty and I'd rather not try to figure out how to implement this using javascript. Does anyone know of a way to generate javascript from jQuery? If not, can anyone recommend a good resource for finding side by side comparisons of equivalent javascript vs jQuery?
My code:
var move = 200;
$('#clickme').click(function() {
$('#main div:even').animate({
left:"+="+move
}, 2000);
move = -move;
});
A: This article has a good presentation that shows off exactly what you are trying to show your coworkers.
It shows how this :
var example = null; // object
function doMove() {
example.style.left = parseInt(example.style.left)+1+'px';
setTimeout(doMove,20); // call doMove in 20msec
}
function init() {
example = document.getElementById('example'); // get the "example" object
example.style.left = '0px'; // set its initial position to 0px
doMove(); // start animating
}
window.onload = init;
Can be turned into this :
$("#element").animate({ left: 100px; });
A: Because jQuery is implemented in JS, and not translated to it (like CoffeeScript or whatever), there's no accurate way to show one vs the other.
You could get at the same idea by profiling the jQuery and showing the result - "look at all the code the jQuery team wrote for us, and we get to use basically for free!" or by showing the definition of $().attr or another, similar method that hides a bunch of browser-specific quirks.
A: The simplest way if you don't already know how to accomplish a task in straight JavaScript is to look at the source code, see what it's doing, and write JavaScript that does the same thing.
A: here is some documentation on Javascript Animation The other javascript you will be implementing here is about selecting elements like selecting by tag name
A: Well I think you can try
document.querySelector('#clickme')
This is essentially similar to jquery $(' ') but this will the previous will return only one element .
There is no direct way as if you go through source of jquery , you will realize that node selection is parsed using regex which is not easy to implement for each code you want to write ,
Also there is a direct relation between the methods called :
For example here :
.click(function) -> .addEventListener('click',function,false);
A: I'd consider just showing them a bunch of examples of how easy it is to do things in jquery - animation, DOM manipulation, etc. If they have any understanding of javascript they'll have an idea of how much work it's saving and if they don't why are they making the decision?
A big point I would bring up is that everything in jquery just works, no more cross-browser issues.
A: The selector is simple enough that it translates to getElementById, though if it had been more complex the Sizzle library would have been invoked to get the elements.
Click is an alias for bind, with click specified. Bind works by adding an event. Here's a snippet from the source code:
add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
} else if ( !handler ) {
// Fixes bug #7229. Fix recommended by jdalton
return;
}
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the function being executed has a unique ID
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure
var elemData = jQuery._data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
if ( !elemData ) {
return;
}
var events = elemData.events,
eventHandle = elemData.handle;
if ( !events ) {
elemData.events = events = {};
}
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
}
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data };
// Namespaced event handlers
if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
if ( !handleObj.guid ) {
handleObj.guid = handler.guid;
}
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = jQuery.event.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = [];
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add the function to the element's handler list
handlers.push( handleObj );
// Keep track of which events have been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
}
Note that there are various clever things going on there so that this works no matter what.
Animate works like this:
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p,
display, e,
parts, start, end, unit;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) {
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height
// animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout ) {
this.style.display = "inline-block";
} else {
display = defaultDisplay( this.nodeName );
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( display === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ]();
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
});
}
Again, a lot of cleverness to ensure this does what you expect.
In real life, a getElementById, with an event listener, then a loop that uses setStyle on the element repeatedly to get an animation would work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Java enum set custom ordinals The other day I tried to do this, but it doesn't work:
enum MyEnum {ONE = 1, TWO = 2}
much to my surprise, it doesn't compile!!! How to se custom ordinals???
A: This is how you could do it manually:
enum MyEnum {
ONE(1),
TWO(2);
private int val;
private MyEnum(int val) {
this.val = val;
}
}
A: You can't. Ordinals are fixed by starting at 0 and working up. From the docs for ordinal():
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
You can't assign your own values. On the other hand, you can have your own values in the enum:
public enum Foo {
ONE(1), TWO(2);
private final int number;
private Foo(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
A: The order in which you define the enums will determine the ordinals.
enum MyEnum {
Enum1, Enum2;
}
Here, Enum1 will have ordinal 1 and Enum2 will have ordinal 2.
But you can have custom properties for each enum:
enum MyEnum {
Enum1(1), Enum2(2);
private int ord ;
MyEnum(int ord) {
this.ord = ord;
}
public int getOrd() {
return this.ord;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: Is there a way to make npm install (the command) to work behind proxy? Read about a proxy variable in a .npmrc file but it does not work. Trying to avoid manually downloading all require packages and installing.
A: This worked for me-
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
npm set strict-ssl=false
A: Finally i have managed to solve this problem being behinde proxy with AD authentication. I had to execute:
npm config set proxy http://domain%5Cuser:password@proxy:port/
npm config set https-proxy http://domain%5Cuser:password@proxy:port/
It is very important to URL encode any special chars like backshlash or #
In my case i had to encode
*
*backshlash with %5C so domain\user will be domain%5Cuser
*# sign with %23%0A so password like Password#2 will be Password%23%0A2
I have also added following settings:
npm config set strict-ssl false
npm config set registry http://registry.npmjs.org/
A: $ npm config set proxy http://login:pass@host:port
$ npm config set https-proxy http://login:pass@host:port
A: Though i set proxy with config, problem was not solved but after
This one worked for me:
npm --https-proxy http://XX.AA.AA.BB:8080 install cordova-plugins
npm --proxy http://XX.AA.AA.BB:8080 install
A: vim ~/.npmrc in your Linux machine and add following. Don't forget to add registry part as this cause failure in many cases.
proxy=http://<proxy-url>:<port>
https-proxy=https://<proxy-url>:<port>
registry=http://registry.npmjs.org/
A: I tried all of these options, but my proxy wasn't having any of it for some reason. Then, born out of desparation/despair, I randomly tried curl in my Git Bash shell, and it worked.
Unsetting all of the proxy options using
npm config rm proxy
npm config rm https-proxy
And then running npm install in my Git Bash shell worked perfectly. I don't know how it's set up correctly for the proxy and the Windows cmd prompt isn't, but it worked.
A: On Windows system
Try removing the proxy and registry settings (if already set) and set environment variables on command line via
SET HTTP_PROXY=http://username:password@domain:port
SET HTTPS_PROXY=http://username:password@domain:port
then try to run npm install. By this, you'll not set the proxy in .npmrc but for that session it will work.
A: npm config set proxy <http://...>:<port_number>
npm config set registry http://registry.npmjs.org/
This solved my problem.
A: After tying different answers finally, @Kayvar answers's first four lines help me to solve the issue:
npm config set registry http://registry.npmjs.org/
npm config set proxy http://myusername:mypassword@proxy.us.somecompany:8080
npm config set https-proxy http://myusername:mypassword@proxy.us.somecompany:8080
npm config set strict-ssl false
A: This worked for me.
Set the http and https proxy.
*
*npm config set proxy http://proxy.company.com:8080
*npm config set https-proxy http://proxy.company.com:8080
A: For me even though python etc will all work though our corporate proxy npm would not.
I tried
npm config set proxy http://proxyccc.xxx.ca:8080
npm config set https-proxy https://proxyccc.xxx.ca:8080
npm config set registry http://registry.npmjs.org/
as instructed but kept getting the same error.
It was only when I removed
https-proxy https://proxyccc.xxx.ca:8080
from the .npmrc file
that
npm install electron --save-dev worked
A: In my case, I forgot to set the "http://" in my config files (can be found in C: \Users \ [USERNAME] \ .npmrc) proxy adresses. So instead of having
proxy=http://[IPADDRESS]:[PORTNUMBER]
https-proxy=http://[IPADDRESS]:[PORTNUMBER]
I had
proxy=[IPADDRESS]:[PORTNUMBER]
https-proxy=[IPADDRESS]:[PORTNUMBER]
Which of course did not work, but the error messages didnt help much either...
A: There is good information on curl's page on SSL and certificate issues.
I base most of my answer on the information there.
Using strict-ssl false is bad practice and can create issues. What we can do instead is add the certificate that is being injected, by the "man in the middle" certificate.
How to solve this on Windows:
*
*Download the CA Certificates from curl based on Mozilla's CA bundle. You can also use curl's "firefox-db2pem.sh" shellscript to convert your local Firefox database.
*Go to a webpage using https, for example Stackoverflow in Chrome or Internet Explorer
*Click the lock icon, click View certificates or "Valid" in Chrome
*Navigate to the Certification path. The top certificate, or the root certificate is the one we want to extract. Click that certificate and then "view certificate"
*Click the second tab, "Details". Click "Copy to file". Pick the DER format and make note of where you save the file. Pick a suitable filename, like rootcert.cer
*If you have Git installed you will have openssl.exe. Otherwise, install git for windows at this stage. Most likely the openssl executable will be at C:\Program Files\git\usr\bin\openssl.exe. We will use openssl to convert the file to the PEM format we need for NPM to understand it.
*Convert the file you saved in step 5 by using this command:
openssl x509 -inform DES -in **rootcert**.cer -out outcert.pem -text
where rootcert is the filename of the certificate you saved in step 5.
*Open the outcert.pem in a text-editor smart enough to understand line-endings, so not notepad.
*Find -----BEGIN CERTIFICATE----- lots of characters -----END CERTIFICATE----- and copy all text between them and also including the BEGIN / END lines
*Now we will paste that content to the end of the CA Cert bundle made in step 1. So open the cacert.pem in your advanced texteditor. Go to the end of the file and paste the content from previous step to the end of file. (Preserve the empty line below what you just pasted)
*Copy the saved cabundle.pem to a suitable place. Eg your %userprofile% or ~. Make note of the location of the file.
*Now we will tell npm/yarn to use the new bundle. In a commandline, write
npm config set cafile **C:\Users\username\cacert.pem**
where C:\Users\username\cacert.pem is the path from step 10.
*Optionally: turn on strict-ssl again, npm config set strict-ssl true
Phew! We made it! Now npm can understand how to connect. Bonus is that you can tell curl to use the same cabundle.pem and it will also understand HTTPs.
A: I solved this problem this way:
*
*I run this command:
npm config set strict-ssl false
*Then set npm to run with http, instead of https:
npm config set registry "http://registry.npmjs.org/"
*Then I install packages using this syntax:
npm --proxy http://username:password@cacheaddress.com.br:80 install packagename
Skip the username:password part if proxy doesn't require you to authenticate
EDIT: A friend of mine just pointed out that you may get NPM to work behind a proxy by setting BOTH HTTP_PROXY and HTTPS_PROXY environment variables, then issuing normally the command npm install express (for example)
EDIT2: As @BStruthers commented, keep in mind that passwords containing "@" wont be parsed correctly, if contains @ put the entire password in quotes
A: Use below command at cmd or GIT Bash or other prompt
$ npm config set proxy "http://192.168.1.101:4128"
$ npm config set https-proxy "http://192.168.1.101:4128"
where 192.168.1.101 is proxy ip and 4128 is port. change according to your proxy settings. its works for me.
A: Try to find .npmrc in C:\Users\.npmrc
then open (notepad), write, and save inside :
proxy=http://<username>:<pass>@<proxyhost>:<port>
PS : remove "<" and ">" please !!
A: A lot of applications (e.g. npm) can use proxy setting from user environment variables.
You can just add to your environment following variables HTTP_PROXY and HTTPS_PROXY that will have the same value for each one
http://user:password@proxyAddress:proxyPort
For example if you have Windows you can add proxy as follow:
A: There has been many answers above for this question, but none of those worked for me. All of them mentioned to add http:// prefix. So I added it too. All failed.
It finally works after I accidentally removed http:// prefix. Final config is like this:
npm config set registry http://registry.npmjs.org/
npm config set http-proxy ip:port
npm config set https-proxy ip:port
npm config set proxy ip:port
npm set strict-ssl false
I don't know the logic behind this, but it worked. If none of answers above works for you, maybe you can have a try on this way. Hope this one is useful.
A: Here are the steps that I've followed (Windows):
*
*Edit the following file C:\Users\<WIN_USERNAME>\.npmrc
*Export the certificate to your file system from the following address:https://registry.npmjs.org
*Navigate to the exported certificate location and issue the following command:
npm config set cafile npm_certificate.cer
*Add the following changes to the file:
registry=https://registry.npmjs.org/
strict-ssl=false
https-proxy=http://[proxy_user]:[proxy_password]@[proxy_ip]:[proxy_port]/
cafile=npm_certificate.cer
Now you should be ready to go!
A: Just open the new terminal and type npm config edit and npm config -g edit. Reset to defaults. After that close terminal, open the new one and type npm --without-ssl --insecure --proxy http://username:password@proxy:8080 install <package> if you need globally just add -g.
It worked for me, hope it`ll work for you :)
A: Have you tried command-line options instead of the .npmrc file?
I think something like npm --proxy http://proxy-server:8080/ install {package-name} worked for me.
I've also seen the following:
npm config set proxy http://proxy-server:8080/
A: Setup npm proxy
For HTTP:
npm config set proxy http://proxy_host:port
For HTTPS:
use the https proxy address if there is one
npm config set https-proxy https://proxy.company.com:8080
else reuse the http proxy address
npm config set https-proxy http://proxy.company.com:8080
Note: The https-proxy doesn't have https as the protocol, but http.
A: Though there are already many good advice, for my environment(Windows 7, using PowerShell) and the last version available of node.js ( v8.1.2 ) all the above did not worked, except when I followed brunowego settings.
So check your settings with :
npm config list
Settings behind a proxy:
npm config set registry http://registry.npmjs.org/
npm config set http-proxy http://username:password@ip:port
npm config set https-proxy http://username:password@ip:port
npm config set proxy http://username:password@ip:port
npm set strict-ssl false
Hope this will save time to someone
A: when I give without http/http prefix in the proxy settings npm failed even when the proxy host and port were right values. It worked only after adding the protocol prefix.
A: My issue came down to a silly mistake on my part. As I had quickly one day dropped my proxies into a windows *.bat file (http_proxy, https_proxy, and ftp_proxy), I forgot to escape the special characters for the url-encoded domain\user (%5C) and password having the question mark '?' (%3F). That is to say, once you have the encoded command, don't forget to escape the '%' in the bat file command.
I changed
set http_proxy=http://domain%5Cuser:password%3F@myproxy:8080
to
set http_proxy=http://domain%%5Cuser:password%%3F@myproxy:8080
Maybe it's an edge case but hopefully it helps someone.
A: This works for me in Windows:
npm config set proxy http://domain%5Cuser:pass@host:port
If you are not in any domain, use:
npm config set proxy http://user:pass@host:port
If your password contains special characters such as ",@,: and so on, replace them by their URL encoded values. For example "->%22, @->%40, :->%3A. %5C is used for the character \.
A: To setup the http proxy have the -g flag set:
sudo npm config set proxy http://proxy_host:port -g
For https proxy, again make sure the -g flag is set:
sudo npm config set https-proxy http://proxy_host:port -g
A: When in doubt, try all these commands, as I do:
npm config set registry http://registry.npmjs.org/
npm config set proxy http://myusername:mypassword@proxy.us.somecompany:8080
npm config set https-proxy http://myusername:mypassword@proxy.us.somecompany:8080
npm config set strict-ssl false
set HTTPS_PROXY=http://myusername:mypassword@proxy.us.somecompany:8080
set HTTP_PROXY=http://myusername:mypassword@proxy.us.somecompany:8080
export HTTPS_PROXY=http://myusername:mypassword@proxy.us.somecompany:8080
export HTTP_PROXY=http://myusername:mypassword@proxy.us.somecompany:8080
export http_proxy=http://myusername:mypassword@proxy.us.somecompany:8080
npm --proxy http://myusername:mypassword@proxy.us.somecompany:8080 \
--without-ssl --insecure -g install
=======
UPDATE
Put your settings into ~/.bashrc or ~/.bash_profile so you don't have to worry about your settings everytime you open a new terminal window!
If your company is like mine, I have to change my password pretty often. So I added the following into my ~/.bashrc or ~/.bash_profile so that whenever I open a terminal, I know my npm is up to date!
*
*Simply paste the following code at the bottom of your ~/.bashrc file:
######################
# User Variables (Edit These!)
######################
username="myusername"
password="mypassword"
proxy="mycompany:8080"
######################
# Environement Variables
# (npm does use these variables, and they are vital to lots of applications)
######################
export HTTPS_PROXY="http://$username:$password@$proxy"
export HTTP_PROXY="http://$username:$password@$proxy"
export http_proxy="http://$username:$password@$proxy"
export https_proxy="http://$username:$password@$proxy"
export all_proxy="http://$username:$password@$proxy"
export ftp_proxy="http://$username:$password@$proxy"
export dns_proxy="http://$username:$password@$proxy"
export rsync_proxy="http://$username:$password@$proxy"
export no_proxy="127.0.0.10/8, localhost, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16"
######################
# npm Settings
######################
npm config set registry http://registry.npmjs.org/
npm config set proxy "http://$username:$password@$proxy"
npm config set https-proxy "http://$username:$password@$proxy"
npm config set strict-ssl false
echo "registry=http://registry.npmjs.org/" > ~/.npmrc
echo "proxy=http://$username:$password@$proxy" >> ~/.npmrc
echo "strict-ssl=false" >> ~/.npmrc
echo "http-proxy=http://$username:$password@$proxy" >> ~/.npmrc
echo "http_proxy=http://$username:$password@$proxy" >> ~/.npmrc
echo "https_proxy=http://$username:$password@$proxy" >> ~/.npmrc
echo "https-proxy=http://$username:$password@$proxy" >> ~/.npmrc
######################
# WGET SETTINGS
# (Bonus Settings! Not required for npm to work, but needed for lots of other programs)
######################
echo "https_proxy = http://$username:$password@$proxy/" > ~/.wgetrc
echo "http_proxy = http://$username:$password@$proxy/" >> ~/.wgetrc
echo "ftp_proxy = http://$username:$password@$proxy/" >> ~/.wgetrc
echo "use_proxy = on" >> ~/.wgetrc
######################
# CURL SETTINGS
# (Bonus Settings! Not required for npm to work, but needed for lots of other programs)
######################
echo "proxy=http://$username:$password@$proxy" > ~/.curlrc
*Then edit the "username", "password", and "proxy" fields in the code you pasted.
*Open a new terminal
*Check your settings by running npm config list and cat ~/.npmrc
*Try to install your module using
*
*npm install __, or
*npm --without-ssl --insecure install __, or
*override your proxy settings by using npm --without-ssl --insecure --proxy http://username:password@proxy:8080 install __.
*If you want the module to be available globally, add option -g
A: Go TO Environment Variables and Either Remove or set it to empty
HTTP_PROXY and HTTPS_PROXY
it will resolve proxy issue for corporate env too
A: I just have have my share of fight with npm and proxy settings and since I do not like other answers I like to share how I think this should be resolved (compromising security is not an option).
What docs says
First of all you have to be aware what are important settings available for npm related to proxy:
*
*proxy A proxy to use for outgoing http requests. If the HTTP_PROXY or http_proxy environment variables are set, proxy settings will be honored by the underlying request library.
*https-proxy A proxy to use for outgoing https requests. If the HTTPS_PROXY or https_proxy or HTTP_PROXY or http_proxy environment variables are set, proxy settings will be honored by the underlying request library.
*noproxy A comma-separated string or an array of domain extensions that a proxy should not be used for.
*cafile A path to a file containing one or multiple Certificate Authority signing certificates. Similar to the ca setting, but allows for multiple CA's, as well as for the CA information to be stored in a file on disk.
Now since default values for proxy, https-proxy are based on environment variables it is recommended way to properly configure those variables so other tools could work too (like curl).
Note that for v6 noproxy documentation doesn't say anything about environment variables and since v7 NO_PROXY environment variable is mentioned. My environment
wasn't configured to verify how this variable works (if lower case version is covered).
Proper configuration
Now I was configuring docker image which should be used behind a proxy and this entries were needed in Dockerfile:
COPY certs/PoroxyCertificate.crt /usr/local/share/ca-certificates/
COPY certs/RootCa.crt /usr/local/share/ca-certificates/
RUN update-ca-certificates
# here all tools like curl were working
RUN ["/bin/bash", "-c", "set -o pipefail && curl -sSL https://deb.nodesource.com/setup_14.x | bash -"]
RUN apt-get -y update && apt-get install -y nodejs
RUN npm config set cafile /etc/ssl/certs/ca-certificates.crt -g
Now interesting thing is that I needed two certificate files. RootCa.crt is self signed certificate for all corporate servers and PoroxyCertificate.crt contains that certificate, but it also has an extra middle SubCA certificate. Proxy was responding with certificate chain of length 3.
Now update-ca-certificates scans directory /usr/local/share/ca-certificates/ for new certificates and updates /etc/ssl/certs/ca-certificates.crt which will contain much more then those custom certificates.
Feeding this /etc/ssl/certs/ca-certificates.crt to cafile of npm config resolve all problems with certificates when proxy was used.
Important note
with npm v6 certificate errors quite often lead to npm ERR! Maximum call stack size exceeded what is very confusing (I even broke certificate on purpose to verify this issue), log file contained something like this:
RangeError: Maximum call stack size exceeded
at isDepOptional (/usr/lib/node_modules/npm/lib/install/deps.js:417:24)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:441:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
at failedDependency (/usr/lib/node_modules/npm/lib/install/deps.js:457:9)
I've found some some issue about that, but this will not be fixed in v6.
A: to use proxy in npm install forget all the npm config stuffs and just simply set a http proxy in proxy environment variables and then do the npm i
export https_proxy=http://proxy.address.com:1090/
export http_proxy=http://proxy.address.com:1090/
this always works for me.
im not sure why but npm seems like doesn't works well with socks proxies but it works great with http proxies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "327"
}
|
Q: Internet Explorer 6 and Opacity This isn't a pressing issue, but everything that I've read indicates that these CSS opacity rules should work in Internet Explorer 6:
.videos img {
zoom: 1;
margin: 0 auto;
}
.videos a.video img {
opacity: 0.5;
filter: alpha(opacity=50);
}
.videos a.video:hover img {
opacity: 1.0;
filter: alpha(opacity=100);
}
I have created this jsFiddle to share the code. I am testing using IETester on Windows 7, and the technique works in IE 7-9, but not IE 6.
A: OK, it seems we've found the solution. IETester is not fully reliable; in this particular case, filters didn't work because OP didn't run IETester as administrator.
It's always better to use "native" versions of IE, for example IE running in virtual machine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: MapController calls do not work inside of event handler? I'm trying to move the map with a 3-finger gesture, rather than one.
If I do a scrollBy() or setMapCenter() in my main activity, things seem to work as expected.
Howevver, if I make these calls inside of my ACTION_MOVE, for example, they seem to have no effect.
Posting doesn't really work well either.
There's another issue - the event.getX/Y() are floats, and the mapController.scrollBy() takes ints - as real-time dragging at normal speeds seems to require the sub-int resolution, making real-time updading hard to do.
And it seems really odd which methods are on the mapView and which on the mapController.
UPDATE : scrollBy() when executed in the event handler will move any overlays, but not the underlying map
So basicially what I want to be able "return true" form ACTION_MOVE and so have my code rather than the base code handle map tracking via user gesture
A: You may have to post a slight delay,
Something like:
Handler handler = new Handler();
// Method Block
{
handler.postDelayed(new Runnable()
{
// Code etc
}, 500);
}
// End code block
When ever I play with map stuff, allot of the controller actions have to have be fired after the map has stopped being touched.. (I know that sounds like a pain).
I have written quite a bit of map library stuff (Android Map Library) and know what you mean where nothing seems to happen. Or the map just seems to ignore inputs, the only way I have managed it was with delayed controller commands.
Let me know your thoughts and I might be able to help a bit more.
Cheers,
Chris
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: inject parameters in cgi-bin through shell My current problem is that I'm developing a embedded system that uses a binary Cgi inside cgi-bin folder. For some obscure reason, when I access the browser and type /cgi-bin/Cgi?AjaxAction=settings&variable=0 everything works fine. So I would like to let a script boot with my application something like:
./Cgi < echo AjaxAction=settings&variable=0
But all my tries didn't worked out. I have PARTS of the Cgi code, and I know that it has no argc argv. Any thoughts on how to inject these parameters? I use PPC linux.
A: You should try setting the environment variable "QUERY_STRING":
setenv QUERY_STRING "AjaxAction=settings&variable=0"
and later that, simply execute the script:
./Cgi
Lot of cgi scripts uses that env variable to read the params sent in the url.
The script maybe use that way to read the vars.
Anyway, you should try to read the cgi code to see how it works... if you paste some here, maybe more people will be able to help you.
Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get an element from an array using xpath I have the following SimpleXML object:
SimpleXMLElement Object
(
[@attributes] => Array
(
[status] => ok
)
[a] => SimpleXMLElement Object
(
[b] => Array
(
[0] => SimpleXMLElement Object
(
[c] => Google
[d] => GOOG
[e] => http://www.google.com
)
[1] => SimpleXMLElement Object
(
[c] => Yahoo
[d] => YHOO
[e] => http://www.yahoo.com
)
[2] => SimpleXMLElement Object
(
[c] => Microsoft
[d] => MSFT
[e] => http://www.microsoft.com
)
Given d I want to get e - Since b is an array, is there any way to do this without looping through the entire array?
<stk status="ok">
<a>
<b>
<c>Yahoo</c>
<d>YHOO</d>
<e>http://www.yahoo.com</e>
</b>
<b>
<c>Google</c>
<d>GOOG</d>
<e>http://www.google.com</e>
</b>
<b>
<c>Microsoft</c>
<d>MSFT</d>
<e>http://www.microsoft.com</e>
</b>
</a>
</stk>
A: You could use an XPath query asking for the e elements that are children of b elements having d elements with the text YHOO.
Remember that SimpleXMLElement::xpath() will return an array of elements, even if the XPath only finds one: hence $urls[0] to get the first (only) one.
$xml = '<stk status="ok"><a><b><c>Yahoo</c><d>YHOO</d><e>http://www.yahoo.com</e></b><b><c>Google</c><d>GOOG</d><e>http://www.google.com</e></b><b><c>Microsoft</c><d>MSFT</d><e>http://www.microsoft.com</e></b></a></stk>';
$stk = simplexml_load_string($xml);
$urls = $stk->xpath('/stk/a/b[d="YHOO"]/e');
$yhoo = (string) $urls[0];
echo $yhoo;
A: Iterate over all //d.
For each one, evaluate following-sibling::e[1].
I think that's what Marc B meant.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: News/Update Drop Down Section I've recently gotten into web programming, and I am completely overwhelmed. I've started off with the basics, html, css, and javascript. On my first webpage, I'm interested in implementing a drop down news section for where I post updates. The best example I can give is the way Riot Games does it:
http://na.leagueoflegends.com/
You see, under the latest news section? For the life of me I can't figure out where to begin implementing something such as that. Any advice?
Thanks!
A: Just a tip that helped me a lot: download an extension called FireBug for Firefox. This add-on will allow you to right click on any element in a page and "inspect" that element - see it's source code. You can track down any CSS styles involved in styling the element and also search the included JavaScript files for an id, name, or class that was assigned to the element in which you are interested.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: fade fade out effect need for existing javascript code provided Is it possible to apply a fade in fade out effect to javascript code please?
At the moment it just pops up an image and disappears with no effect applied. Thank you in advance.
A: Since your site is already using jQuery, look into using jQuery fadeIn() and fadeOut() functions.
$('div').fadeOut();
A: FadeIn() and FadeOut() needs a duration set, like FadeIn("slow"); or FadeOut("fast"); or even in milliseconds like FadeIn(3000); otherwise the fade effect is'nt really a fade effect as it happens instantly.
The setInterval() function only loops the fades.
A: try the below script
function gradient(id, level)
{
var box = document.getElementById(id);
box.style.opacity = level;
box.style.MozOpacity = level;
box.style.KhtmlOpacity = level;
box.style.filter = "alpha(opacity=" + level * 100 + ")";
box.style.display="block";
return;
}
function fadein(id)
{
var level = 0;
while(level <= 1)
{
setTimeout( "gradient('" + id + "'," + level + ")", (level* 1000) + 10);
level += 0.01;
}
}
function centerPopup()
{
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
//alert(windowWidth); alert(windowHeight);
var popupHeight = 300;
var popupWidth = 400;
//alert(windowHeight/2-popupHeight/2); alert(windowWidth/2-popupWidth/2);
document.getElementById(AnyElement).style.top = windowHeight/2-popupHeight/2 + 'px';
document.getElementById(AnyElement).style.left = windowWidth/2-popupWidth/2 + 'px';
}
function openbox(fadin)
{
var box = document.getElementById(AnyElement);
document.getElementById(AnyElement).style.display = 'block';
if(fadin)
{
gradient("box", 0);
fadein("box");
centerPopup();
}
else
{
box.style.display='block';
}
}
function closebox()
{
document.getElementById(AnyElement).style.display = 'none';
document.getElementById(AnyElement).style.display = 'none';
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem Customizing the Navigation Menu from Silverlight Business Application I'm using the Silverlight Business Application Template but I need to customize the MainPage layout to match the client's existing ASP.NET projects pattern. I was able to create the Navigation menu which highlights the selected item. But when a MouseEnter event occurs, the selected menu item's style becomes that of MouseOver VisualState. And on MouseLeave, the selected menu item turns to Normal VisualState. This behavior worked for the solution's default menu but something may be missing from my modification. The code definition are as follows. Thanks!
<Style x:Key="NavMenuItem" TargetType="HyperlinkButton">
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontSize" Value="11"/>
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Padding" Value="20,10,20,10" />
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="MinHeight" Value="40"/>
<Setter Property="MinWidth" Value="150"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="HyperlinkButton">
<Grid Margin="20,20,0,0">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<DoubleAnimation BeginTime="0" To="1" Duration="00:00:00.01"
Storyboard.TargetName="MenuItemBorder"
Storyboard.TargetProperty="Opacity" />
<DoubleAnimation BeginTime="0" To="1" Duration="00:00:00.01"
Storyboard.TargetName="MenuItemBorder"
Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.ShadowDepth)" />
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<DoubleAnimation BeginTime="0" To="1" Duration="00:00:00.01"
Storyboard.TargetName="MenuItemBorder"
Storyboard.TargetProperty="Opacity" />
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="LinkStates">
<VisualState x:Name="InactiveLink"/>
<VisualState x:Name="ActiveLink">
<Storyboard>
<DoubleAnimation BeginTime="0" To="1" Duration="00:00:00.01"
Storyboard.TargetName="MenuItemBorder"
Storyboard.TargetProperty="Opacity" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border Name="MenuItemBorder" CornerRadius="10,0,0,10" Opacity="0"
MinHeight="{TemplateBinding MinHeight}" MinWidth="{TemplateBinding MinWidth}">
<!--BorderBrush="Silver" BorderThickness="1"-->
<Border.Background>
<LinearGradientBrush StartPoint="0.5, 0" EndPoint="0.5, 1">
<GradientStop Color="White" Offset="0.6"/>
<GradientStop Color="Silver" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<Border.Effect>
<DropShadowEffect x:Name="BorderShadow" ShadowDepth="5" Color="#FF484848" Opacity="0.5" BlurRadius="5"/>
</Border.Effect>
</Border>
<ContentPresenter x:Name="ContentPresenter"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Margin="{TemplateBinding Padding}" Content="{TemplateBinding Content}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<HyperlinkButton Style="{StaticResource NavMenuItem}" NavigateUri="/Home" TargetName="ContentFrame"
MouseEnter="HyperlinkButton_MouseEnterLeave" MouseLeave="HyperlinkButton_MouseEnterLeave" />
private void HyperlinkButton_MouseEnterLeave(object sender, MouseEventArgs e) {
HyperlinkButton hb = sender as HyperlinkButton;
if (hb.NavigateUri.ToString() == ContentFrame.CurrentSource.ToString())
VisualStateManager.GoToState(hb, "ActiveLink", true);
}
A: Maybe you could try to set the MouseOver VisualSatate of your button on the EventHandler if it Event is MouseEnter and reset it if it is a MouseLeave Event.
And i think i would set up two event handlers and not only one for both events, then you can easily set the MouseOver state and the ActiveState too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to correctly deserialize a JSON string into the class that contains a nested List of another class I have the following object graph and I'm using Jquery's $.Ajax() to send this identical "View" object in JSON (stringified) from the browser to a Page Method on ASP.Net. The JAvascript deserialization works for all of the strings and int's in the View class but My List<DataItem> is empty.
What I tried: Using chrome dev tools, I took the stringified JSON, created a unit test and used both the DataContractJsonSerializer and the JavaScriptSerializer. The DataContractJsonSerializer object deserialized my object graph correctly but the JavaScriptSerializer dumped my List. How can I get the correct deserialization on my page method ?
public class View
{
public string Text { get; set; }
public string AnotherText { get; set; }
public Int SomeInt { get; set; }
public List<DataItem> { get; set; }
}
public class DataItem
{
public Person person {get;set}
}
public class Person
{
public int Age {get;set}
}
var dataa = {mqvm: mqvmJSON };
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify( dataa ),
url: "GoHere.aspx/WebMethodName",
success: function(data) {
alert(data.d);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText + ' ' + errorThrown);
}
});
Instead of this (the view obj as a param).
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public static string CreateResponseReview(View mqvm)
{
return "Success";
}
how can I get this? (the string param)
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public static string CreateResponseReview(string mqvm)
{
//do manual JSON deserialization here.
return "Success";
}
My JSON looks like this.
{
"Text": "6",
"AnotherText":"wow"
"SomeInt": 5,
"DataItem":[
{
"person":{
"Age":23
}
},
{
"person":{
"Age":42
}
}
]
}
A: Try using the following:
Deserialisation Code
string json = "{\"text\":\"some text\",\"anotherText\":\"some more text\", \"someInt\":1, \"dataItems\":[{\"person\":{age:25}},{\"person\":{age:20}}]}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
View view = serializer.Deserialize<View>(json);
Classes
public class View
{
public string Text { get; set; }
public string AnotherText { get; set; }
public int SomeInt { get; set; }
public List<DataItem> DataItems { get; set; }
}
public class DataItem
{
public Person person { get; set; }
}
public class Person
{
public int Age {get;set;}
}
JSON
{
"text":"some text",
"anotherText":"some more text",
"someInt":1,
"dataItems":
[
{"person":{age:25}},
{"person":{age:20}}
]
}
A: I figured it out.
I didn't want to use the JavascriptSerializer class because it dumped my nested list so I forced it to pass me the object as a string and then I manually deserialized it. I also kept getting "no parameterless constructor defined for type of u0027system.string u0027"
Remember that U0027 is an apostrophe so the runtime might be thinking that there is an actual type named "System.string" and not System.string. My problem was - I wasn't correctly delimiting the parameters in the item below called data2. I had to put \' ticks \' around the key and the value.
function requestHtmlFromServer(mqvmJSON) {
var mqvmstring = JSON.stringify(mqvmJSON);
var data2 = "{\'mqvm\':\'" + mqvmstring + "\' }"; \\<--the problem
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data2,
url: "MedicalInformation.aspx/CreateResponseReview",
success: function(data) {
alert(data.d);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText + ' ' + errorThrown);
}
});
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public static string CreateResponseReview(string mqvm)
{
string noNewLines = mqvm.Replace("\n", "");
View viewModel = ToObjectFromJSON<View>(noNewLines);
//do my other stuff here
return "Success";
}
public static T ToObjectFromJSON<T>(string jsonString)
{
var serializer = new DataContractJsonSerializer(typeof(T));
var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
var newObject = (T)serializer.ReadObject(memoryStream);
memoryStream.Close();
return newObject;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Sorting excel sheet in reverse order on basis of created time / reversing the excel sheet I'm using Microsoft interop excel to automate the excel workboook
in which i have many worksheets(say 40) which have been created at in seconds gap or even less
now i have to present the worksheet in reverse order i.e the sheet which was created first should come first while opening(currently it comes last) in short I have to sort the excel sheet in reverse order or by time of creation
any help in this matter
thnx
A: As far as I know, Excel doesn't store the date and time of creation of each sheet. Yet, every new sheet is added at the end of every sheets of the workbook.
So, you can reverse the order based on this hypothesis.
Here is a VBA macro to do this, you just have to adapt it to interop or C#:
Sub reverseOrder()
Dim i As Integer
For i = Worksheets.Count - 1 To 1 Step -1
Worksheets(i).Move After:=Worksheets(Worksheets.Count)
Next i
End Sub
It parses sheets from one sheet before the last one to the first one and move each sheet to the last position.
A: Workbook wb = app.Workbooks.Open(Form1.strRecentFilename, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp, temp);
int count = wb.Worksheets.Count;
Worksheet ws, lastws;
lastws = (Worksheet)wb.Worksheets[count];
MessageBox.Show(lastws.Name);
for (int i = count - 1; i >= 1; i--)
{
lastws = (Worksheet)wb.Worksheets[count];
ws = (Worksheet)wb.Worksheets[i];
ws.Move(System.Reflection.Missing.Value, lastws);
}
A: So, if you have a Worksheets of Workbook in excel file and you need to sort Worksheets alphabet:
public void SortWs()
{
List<Worksheet> for_sort = new List<Worksheet>();
foreach (Worksheet ws in wb.Worksheets)
{
for_sort.Add(ws);
}
for_sort.Sort(delegate(Worksheet wst1, Worksheet wst2)
{
return wst1.Name.CompareTo(wst2.Name);//sort by worksheet's name
});
Worksheet ws1, ws2;
for (int i = 0; i < for_sort.Count; i++)
{
for (int j = 1; j <= wb.Worksheets.Count; j++)
{
ws1 = (Worksheet)wb.Worksheets[j];
if (for_sort[i].Name == ws1.Name)
{
ws2 = (Worksheet)wb.Worksheets[i+1];
ws1.Move(ws2, Type.Missing);
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Finding x values for peaks in graph I am trying to find the hours where my server load goes high (peak hours). As per what I know and have read, I can employ shape matching to find a peak, and for that I can use neural networks, etc.
But this will only tell me that the input is a peak or not. I wont be able to pass in a graph of my daily server usage and have it tell me the peak hours.
Pardon me, if the question is too idiotic, but trust me I have no leads on how this might be done. All my research is pointing to ways to find a peak, whereas I need to find where the peak exists in a data set, and there might be more than one such peaks too.
A: So, you have an algorithm to detect peaks but you don't know how to find peak hours. The obvious idea is to collect peak rate per hour and build a histogram. Then find peaks in that histogram.
Or am I missing something?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where cell is not equal to.. MySQL query (!=) Can someone tell me how I can do a MySQL query that selects all row with an id != 1?
Please give me example of it.
A: In standard ANSI SQL, not equal is represented as: <>
A: Try this one:
SELECT * FROM pages WHERE id <> 1
You also can use != instead of <>
SELECT * FROM pages WHERE id != 1
A: Use <> or !=, both works for MySQL
A: You didn't provide much detail, but it seems your own title answers the question: use WHERE id != 1. It works in MySQL, but the SQL standard is <>, not !=.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to signal when AJAX completes I have two ajax $.get() requests that I need to synchronize.
Essentially
var signal1 = false;
var signal2 = false;
$.get(url,
{},
function (data) {
signal1 = true;//callback complete.
},'json');
$.get(url2,
{},
function (data) {
signal2 = true;//callback complete.
},'json');
when(signal1 && signal2 == true)
$.get(url3...
How can I, should I accomplish this type of task? (Bonus, what's the AJAX signature for failure callback?)
A: Look at the jquery deferred/promise methods, they are for exactly what you are trying to do.
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are the results of your two calls.
});
http://api.jquery.com/jQuery.when/
http://api.jquery.com/deferred.promise/
A: You do it like this:
$.when(
$.get(url, {}, function(data) {
// signal 1 complete
}, 'json'),
$.get(url2, {}, function(data) {
// signal 2 complete
}, 'json')
).then(function() {
// success after both methods finish
}, function() {
// failure method
});
See jQuery.when: http://api.jquery.com/jQuery.when/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Single-sign-on in Extjs 4 How can we implement Single-sign-on in Extjs4 where there are two different domains
*
*domain1.com
*domain2.com.
A: There are many approaches to Single Sign-On, but it is unlikely that Ext can help you with them. Since the final authentication takes place on the server, your SSO solution needs to focus on how the two servers can confirm the identity of the client.
Here are a few stackoverflow questions
*
*Here someone suggests OpenID
*If you are using Tomcat, there is a Tomcat feature that may help
*Here someone discusses SSO with LDAP
Anyway the bottom line is (as pef commented) you shouldn't be looking for an Ext SSO solution, you should look at what you're doing on the server and think about SSO from that viewpoint.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Regular expression for validating year starting from 2020 I am writing a regular expression to validate year starting from 2020.
The below is the regular expression I wrote,
^(20-99)(20-99)$
It doesn't seem to work. Can anyone point out where did I get it wrong?
A: Regular expressions don't take ranges like that. You'll want to do something like:
if( year >= 2020 )
presto
I'm being flippant because you're trying to use a regular expression where you can just use a straight-forward comparison. If you have a string, convert the string into an integer first (if you even need to do that with Python). Otherwise, you're going to have some really ugly regular expression that's hard to maintain.
Edit: If you're really keen on using a regular expression (or three), your problem can be broken up into three regular expressions: ^20[2-9]\d$, ^2[1-9]\d\d$, ^[3-9]\d{3}$ for four-character years. You could combine these into ^(20[2-9]\d|2[1-9]\d\d|[3-9]\d{3})$.
But note that the regular expression is a) ugly as hell, and b) only accepts years up to 9999. You can mitigate this with judicious use of the +, so something like:
^(20[2-9]\d+|2[1-9]\d{2,}|[3-9]\d{3,})$
...could work.
But I hope you'll find that just doing year >= 2020 is a lot better.
Edit 2: Hell, that regex is wrong for years greater than 9999. You'll probably want to use:
^(20[2-9]\d|2[1-9]\d{2}|[3-9]\d{3}|[1-9]\d{4,})$
And that still doesn't work if you enter a year like 03852.
A: Not certain about python but w.r.t. to regex it doesn't work like you are thinking...ranges are for a single character. So if for some reason you must have a regexp (ie: some sort of regexp data-filled validation engine):
^20[2-9][0-9]|[2-9][1-9][0-9][0-9]$
Any number from 2020-2099 or 2100-9999.
A: Here is a significantly shorter regex that does what you want:
^(?![01]|20[01])\d{4}$
Validation:
>>> regex = re.compile(r'^(?![01]|20[01])\d{4}$')
>>> all(regex.match(str(x)) if x >= 2020 else not regex.match(str(x)) for x in xrange(10000))
True
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: fwrite function not working I am trying to write a simple program that opens the content of a binary file into a buffer and the searches that buffer for the occurrence of string which is '+' characters. It seems like to does find these characters even though my algorithm is a little flaky. Once it finds them it changes the character to some other character. Then it writes the same buffer back to file. It does not work as I tried opening the file in a hex editor and could not find the new string with the new characters. The file that gets modified prints out the string that I am trying to modify using fread and fwrite.
Here is the code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
using namespace std;
char XyZ[] = "++++++++++++++++++++++++++"; //26 count
int main()
{
int error = 0;
FILE * pFile;
unsigned int lSize;
char * buffer;
size_t result;
int i = 0, j = 0;
bool bfound = false;
int count = 0;
int startLocation = 0;
pFile = fopen ( "E:\\DEVS\\Projects\\JustTesting\\FOpen\\Release\\Test.exe", "rb+" );
if (pFile==NULL)
{
cout << "Unable to open Test.exe" << endl;
cout << GetLastError() << endl;
}
else
{
cout << "Successfully opened the file" << endl;
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
cout << "Number of file size is " << lSize << endl;
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
cout << "Total bytes read into our buffer is " << result << endl;
if (result != lSize)
{
cout << "Error in reading the file" << endl;
}
else
{
for(i = 0; i < lSize; i++)
{
if(buffer[i] == '+') // '+'
{
//cout << "Found first one" << endl;
startLocation = i;
//j = i + 1;
//cout << "Found the next one" << endl;
while(buffer[++i] == '+')
{
buffer[i] = '@';
cout << "Found the next one" << endl;
count++;
}
}
}
cout << "Found our string with count " << count << endl;
}
//for(int k = startLocation; k < startLocation + 5; k++)
// buffer[k] = '@';
int value = fwrite (buffer , 1 , lSize , pFile );
cout << "bytes written to file is :" << value << endl;
fclose (pFile);
free (buffer);
}
return 0;
}
A: The first problem is your while:
while(buffer[++i] == '+')
So you've found your +, but in the while you first increase the position and then test whether the value is still +. That fails if you only have one + (and if you have several, the first is not overwritten). Instead, replace it with:
for ( ; (buffer[i] == '+') && (i < lSize) ; i++)
The next problem is that after fread, the file position is at the end. Your call to fwrite will thus append the modified buffer. To actually overwrite the file you first need to call rewind(pFile); again.
A final note on fread/fwrite: you read and write lSize items, each 1 byte in size. That's pretty slow (try it with a one megabyte file). Instead you likely want the opposite:
result = fread(buffer, lSize, 1, pFile);
Note that result will then merely have 1 on success. The same applies for fwrite.
A: Note that you would be trying to write the modified contents at the end of the file. Besides, switching between read and write operations need certain function calls in between to switch the operation mode. Try adding
fseek( pFile, 0, SEEK_SET );
right before doing fwrite. Note that there may still be something wrong
A: You open the file in rb (for reading), then write to it... I am not sure it will do what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i sort this dict per datetime? How can i sort this dict per datetime?
Is it possible?
{
1: {'l':{'created_on': datetime.datetime(2011, 9, 29, 17, 39, 26)}},
2: {'l':{'created_on': datetime.datetime(2011, 9, 23, 17, 39, 26)}},
3: {'l':{'created_on': datetime.datetime(2011, 9, 30, 17, 39, 26)}}
}
A: You can call the sorted() function on the values, with the datetime as the comparison key:
sorted(d.values(), key=lambda item: item["l"]["created_on"])
A: You can get a sorted list of keys for your dictionary d (dictionaries cannot be sorted by themselves):
>>> sorted(d.keys(), key=lambda k: d[k]['l']['created_on'])
[2, 1, 3]
PS: If you really need a dictionary with sorted keys, the now standard OrderedDict type is your friend (as described in the comments by rocksportrocker and agf after Frédéric's answer).
A: You can not sort a dict() itself. The dict has no implict order:
>>> print dict(a=3, b=2, c=1)
{'a': 3, 'c': 1, 'b': 2}
If you want to keep the full structure of your dict, you have to flatten your dict dd into a list li first. Then you can sort with the datetime value as a key:
import operator
dd = { 1: ..... }
li = []
for (i, it) in dd.items():
for (l, it1) in it.items():
for (c, dt) in it.items():
li.append((i, l, c, dt))
li.sort(key=operator.itemgetter(3))
print li
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to break up an HTML List using CSS Only I would like to create a list that adds columns as necessary depending on how many list elements are present. Currently I only know how to do this using a table, which I would like to avoid. Is there a way to do this using CSS only?
I have created an example of how I currently do it with tables on JSFiddle.net ...
http://jsfiddle.net/9W33K/
A: There's two ways I can think of that you can go about it.
*
*Use Floats
*Use CSS3 Columns
With floats you will get a pattern like this:
Item 1 Item 2
Item 3 Item 4
With CSS3, you don't get very much browser support (no IE support until IE10).
Fiddle with both examples: http://jsfiddle.net/DThhT/1/
A: There is a pretty thorough (albeit a bit older) guide I've looked at before here: CSS Swag: Multi-Column Lists
A: You can mimic a HTML table using css display:table property. You'll be able to replace those <tr> and <td> with <div>.
More info here: http://www.w3.org/TR/CSS2/tables.html#table-display
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: EF 4.1 code-first: How to select an entity with it's collection-property's count I have an entity named Tag with a navigation property (collection) named Articles. The Tag has a ignored-property named ArticleCount that used to save tha associated Article s count (just in run-time and to use in views- ignored against the DB). See:
public class Tag{
public int Id { get; set; }
public int Title { get; set; }
public virtual ICollection<Article> Articles { get; set; }
[NotMapped]
public int ArticleCount { get; set; }
}
How can I select all Tag s (or one) with it's ArticleCount in ONE query against the dataBase -in entity framework 4.1 code-first, with lambda expressions please?
A: var tagsAndCounts = from tag in context.Tags
where ...
select new { tag, count = tag.Articles.Count() }
var tagsWithCount = tagsAndCounts.ToList()
.Select(x =>
{
x.tag.ArticleCount = x.count;
return x.tag;
};
(I would design this differently - ArticleCount should not be part of the model, or it should be a projection on Articles, which you could eager-load using Include(). But this does what you want)
Update: my design.
public class Tag
{
...
public int ArticleCount { get { return Articles.Count; } }
}
var tagsWithEagerLoadedArticles = context.Tags.Include(x => x.Articles)
.Where(...).Etc();
Of course, whether this performs well or not depends on the the expected article count per tag. If it's a few dozen, this will work reasonably, while being cleaner than the other approach. If it's hundreds, the other one is better.
Now, if that's the case, you should use an anonymous or named presentation type instead of reusing the entity.
A: Example for all tags:
var result = context.Tags
.Select(t => new
{
Tag = t,
ArticleCount = t.Articles.Count()
});
foreach (var a in result)
a.Tag.ArticleCount = a.ArticleCount;
var tags = result.Select(a => a.Tag).ToList();
This is only one query and the copy happens in memory. I believe that there is no other way than copying the ArticleCount from the anonymous result objects into the tags because you cannot project directly into an entity, so you can't use Select(t => new Tag { ... });. You could use another named type instead of the anonymous type but not an entity type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Drupal 7 & Rules - How to update a node field every time a comment is edited/posted I would like update a field in one of my nodes to reflect the average of all the fivestar ratings I have. However, I want it to be indexed and searcable by search api/solr.
So I thought I could use a Rule to average all of the rating fields after a new comment is added (nodes are rated by the Fivestar field in a comment) and then update an integer field of the node with this new average.
Of course i would need to also re-index this node using search api - so if you tips for that as well, that would be great!
A: What you want is already implemented in the FiveStarVoting Module.
Have a look here:
http://drupal.org/node/1308114
Unfortunately there's a bug which you can follow here:
http://drupal.org/node/1245700
I hope that helped you out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamic Alert View Text Body Can you edit the contents of an UIAlertView once it has been shown? I would like to be able to update the text in it without having to dismiss and show a new one every time.
Thanks in advance,
Jonathan
A: There is a UIAlertView delegate called didPresentAlertView:. It is fired once the UIAlertView is presented on the view. Inside there you can set any of its properties. Here is an example:
- (void)viewDidLoad {
[super viewDidLoad];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"my message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert setDelegate:self];
[alert show];
[alert release];
}
- (void)didPresentAlertView:(UIAlertView *)alertView
{
[alertView setTitle:@"My new title"];
[alertView setMessage:@"My new message"];
}
A: Declare your UIAlertView in the .h , initiate it once (maybe in the viewDidLoad) . Show it only when it is first needed and than try changing its contents when you need to with:
[alertView setTitle:@"new title"];
[alertView setMessage:@"new message"];
A: Go through this . I guess the MBProgressHUD library's mode switching display will suit your requirements better than messing up with alert views. That particular mode/component in the library shows multiple messages sequentially and you also have the provision to set timers for each message in the sequence.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7559718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.