text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Is it possible to use fluent migrator in application_start? I'm using fluent migrator to manage my database migrations, but what I'd like to do is have the migrations run at app start. The closest I have managed is this:
public static void MigrateToLatest(string connectionString)
{
using (var announcer = new TextWriterAnnouncer(Console.Out)
{
ShowElapsedTime = true,
ShowSql = true
})
{
var assembly = typeof(Runner).Assembly.GetName().Name;
var migrationContext = new RunnerContext(announcer)
{
Connection = connectionString,
Database = "SqlServer2008",
Target = assembly
};
var executor = new TaskExecutor(migrationContext);
executor.Execute();
}
}
I'm sure I had this working, but I've not looked at it for sometime (hobby project) and it's now throwing null reference exceptions when it gets to the Execute line. Sadly there are no docs for this and I've been banging my head on it for ages.
Has anyone managed to get this kind of thing working with FluentMigrator?
A:
PM> Install-Package FluentMigrator.Tools
Manually add a reference to:
packages\FluentMigrator.Tools.1.6.1\tools\AnyCPU\40\FluentMigrator.Runner.dll
Note that the folder name will vary on version number, this illustration uses the current 1.6.1 release. If you need the .NET 3.5 runner use the \35\ directory.
public static class Runner
{
public class MigrationOptions : IMigrationProcessorOptions
{
public bool PreviewOnly { get; set; }
public string ProviderSwitches { get; set; }
public int Timeout { get; set; }
}
public static void MigrateToLatest(string connectionString)
{
// var announcer = new NullAnnouncer();
var announcer = new TextWriterAnnouncer(s => System.Diagnostics.Debug.WriteLine(s));
var assembly = Assembly.GetExecutingAssembly();
var migrationContext = new RunnerContext(announcer)
{
Namespace = "MyApp.Sql.Migrations"
};
var options = new MigrationOptions { PreviewOnly=false, Timeout=60 };
var factory =
new FluentMigrator.Runner.Processors.SqlServer.SqlServer2008ProcessorFactory();
using (var processor = factory.Create(connectionString, announcer, options))
{
var runner = new MigrationRunner(assembly, migrationContext, processor);
runner.MigrateUp(true);
}
}
}
Note the SqlServer2008ProcessorFactory this is configurable dependent upon your database, there is support for: 2000, 2005, 2008, 2012, and 2014.
A: I have actually accomplished running migrations in the application_start however it is hard to tell from that code what could be wrong... Since it is open source I would just grab the code and pull it into your solution and build it to find out what the Execute method is complaining about. I found that the source code for Fluent Migrator is organized pretty well.
One thing that you might have to be concerned about if this is a web app is making sure that no one uses the database while you are migrating. I used a strategy of establishing a connection, setting the database to single user mode, running the migrations, setting the database to multi user mode, then closing the connection. This also handles the scenario of a load balanced web application on multiple servers so 2 servers don't try to run migrations against the same database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
}
|
Q: How do I submit a JSON to SOLR using Zend_Client? How do I submit a JSON to SOLR using Zend_Client?
Assume the JSON I am using is (It was taken from the SOLR WIKI, so I assume it is right).
$JSON ='[{"id" : "3", "title" : "test3","description":"toottoto totot ototot "}]';
I see no error in the solr error log, this is the code I use to submit
DOES NOT WORK
$url = 'http://localhost:8983/solr/update/json';
$Client = new Zend_Http_Client($url);
$Client->resetParameters();
$Client->setMethod(Zend_Http_Client::POST);
$Client->setHeaders('Content-type','application/json');
$Client->setParameterPost($JSON);//***** WRONG *****
$Client->setRawData($JSON); //* **** RIGHT FROM ANSWER BELOW, STILL NEED TO ENCODE IT!
$response = $Client->request();
THIS WORKS FROM THE COMMAND LINE!
sudo curl http://localhost:8983/solr/update/json -H 'Content-type:application/json' -d '
[{"id" : "3", "title" : "test3","description":"toottoto totot ototot "}]'
A: The setParameterPost() method takes two arguments, the parameter name and its value like this:
$client->setParameterPost('name', 'john'); // results in name=john
Try using setRawData() instead, this will let you set raw post data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to remove controls with runat="server" specified in asp.net I have a webpage with server accessible controls, see 'FileIconLink' below:
<body>
<p class="FirstTitle style5">Downloads:</p>
<div id="BreadcrumbDiv">
<p style="padding-left:5px; ">Page Loading...</p>
</div><!--/BreadcrumbDiv-->
<div id="DirLinksDiv">
<p><span class="SecondTitle">Files:</span></p>
<a runat="server" href="#" id="FileIconLink">File</a>
<% WriteFileLinks(); %>
<p><span class="SecondTitle">Folders:</span></p>
<a runat="server" href="#" id="FolderIconLink">Folder</a>
</div><!--/DirLinksDiv-->
</body>
<%RemoveHTMLTemplates(); %>
Both 'FileIconLink' and 'FolderIconLink' are templates of web controls which are copied by my code - such as <% WriteFileLinks(); %> above. How could these templates be permanently removed from the web page at run-time on the server without causing the error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Thanks in advance!
A: This is because you have <% %> inside the control you're trying to change. Instead of using <% %> in the aspx page, I would modify the code behind to add a literal control or something to the div, like:
DirLinks.Controls.Add(new LiteralControl(WriteFile()));
You should then be able to modify your control form the code behind.
A: Your inline code is executed during render.
But you probably want to get rid of the templates during Load.
Which means that the two techniques conflict.
A: Ultimately I realised my approach was wrong, as Cade Roux was alluding to, I needed to make up my mind where the templates were going to be used.
My solution was as follows:
*
*Make controls for containing the results of my (previously inline) code.
*Use templates in Page_Load to fill the controls described above.
*Delete templates in Page_Load.
*Do nothing inline.
A: The Page object has another function apart from Page_Load function called Page_PreRender, this function gets executed before Page_Load. So please try remove logic in this Page_PreRender function.
Please refer this link http://msdn.microsoft.com/en-us/library/system.web.ui.control.prerender.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Not showing facebook connect button with Facebooker 2.0 I'm developing a rails application with Facebooker 2.0, my problem is that the facebook login button only appears when the user's in not already logged in in his facebook account, if the user is logged in, it disappears.
I'm using this code to show the button:
<%= fb_login_and_redirect("/users/create_facebook_user", :perms => 'email,user_birthday,offline_access') %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to do this operation in UITextView (iphone) In My textView there is a default value of "First name "
I want to implement such operation in it..
1) it should be shown "first name" firstly
2) when I start editing it should became nil
3)when I am complete with my editing if the field is still nil then it should be shown as "first name" again
can anyone help me with this?
//*This is now what I am doing now**//
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
if (first_name.text=@"") {
first_name.text=@"First Name(Required)";
}
// Any new character added is passed in as the "text" parameter
if ([text isEqualToString:@"\n"]) {
// Be sure to test for equality using the "isEqualToString" message
[textView resignFirstResponder];
// Return FALSE so that the final '\n' character doesn't get added
return FALSE;
}
// For any other character return TRUE so that the text gets added to the view
return TRUE;
return TRUE;
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
NSLog(@"textViewShouldBeginEditing");
textView.scrollEnabled=NO;
if (textView == first_name) {
first_name.text=nil;
}
return YES;
}
A: All the delegate methods you can use to implement this concept can be found in the UITextViewDelegate Protocol Reference.
A: You need to overlay a UILabel on top of the text view with the text you want, set its userInteractionEnabled to NO and on the text field delegate method shouldBeginEditing you hide the UILabel before returning YES and unhide it on shouldFinishEditing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Writing multiple content types to web part Page response stream Is it possible to write more than one content type to a Page's response stream in ASP.NET?
I'm working on a web part in a Sharepoint application which first writes some HTML to the page response stream in order to close a modal dialog and then writes a byte array for a Word document as an attachment to be opened in the browser.
The following code illustrates what I would like to do:
var response = Page.Response;
response.ContentType = "text/html";
response.Write(
"<script type=\"text/javascript\">//javascript</script>");
response.Flush();
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition",
"attachment; filename=WordFile.docx");
response.BinaryWrite(byteArray);
response.End();
This code gives an exception with the message:
Server cannot set content type after HTTP headers have been sent
Which makes sense for this code. Is there any way I can work around this?
A: No, there isn't, given that the content type is sent in the HTTP response, and that you are sending one response, the content type can only be one type.
That said, you will have to have your client issue two separate requests, one to get the HTML content, then once to get the Word document.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C++ member function pointers in class and subclass I have one base class which holds a map for function pointers like this
typedef void (BaseClass::*event_t)();
class BaseClass {
protected:
std::map<std::string, event_t> events;
public:
// Example event
void onFoo() {
// can be added easily to the map
}
};
Handling this works prefect, but now i want to make BaseClass an abstract base class to derive from like this:
class SpecificClass : public BaseClass {
public:
void onBar() {
// this is gonna be difficult!
}
};
Although i can access the map from SpecificClass i am not able to add onBar because the event_t type is only defined for the BaseClass! Is there any possibility (maybe with templates?) which does not lead to define the event_t for each class i will use...
(It is not neccessary to use templates! Any good/suitable approach would be nice.)
More background information:
This whole thing is for a text based RPG. My base class could be called Location and the specifc one any location e.g. CivicCenter. Each Location object subscribes to my EventSystem which notifies all neccessary objects when i fire an event. Therefore i want to store in a map some pointers to private functions holding the actions with their "name" like onSetOnFire (xD) as the key.
A: You have to use static_cast:
event_t evt = static_cast<event_t>(&SpecificClass::onBar);
This is because it is slightly dangerous to cast to event_t, you could accidently apply it to a BaseClass instance.
How it works (for the skeptical):
class BaseClass {
public:
typedef void (BaseClass::*callback_t)(); // callback method
void doSomething(callback_t callback) {
// some code
this->*callback();
// more code
}
void baseCallback(); // an example callback
};
class DerivedClass : public BaseClass {
public:
void derivedCallback();
void doWhatever() {
// some code
doSomething(&BaseClass::baseCallback);
// more code
doSomething(static_cast<callback_t>(&DerivedClass::derivedCallback));
// et cetera
};
Here is what you should avoid, and why this is potentially dangerous:
void badCodeThatYouShouldNeverWrite()
{
BaseClass x;
// DO NOT DO THIS IT IS BAD
x.doSomething(static_cast<callback_t>(&DerivedClass::derivedCallback));
}
The requirement for a static_cast makes it so you can't "accidentally" pass DerivedClass method pointers in. And if you think this is dangerous, just remember that it's a pointer, and pointers are always dangerous. Of course, there are ways you can do this that involve creating helper classes, but that requires a lot of extra code (possibly making a class for every function you want to pass as a callback). Or you could use closures in C++11, or something from Boost, but I realize that a lot of us do not have that option.
A: This can't be done with your current map as it stands. Think about what would happen if you could put a child method into the map. Then you could pull a pointer-to-child-member (masquerading as base) out of the map, call it on a base class instance pointer, and then how would it call a derived class on a base class instance which obviously couldn't work.
Would a polymorphic approach work?
A: Yes; stop using member pointers.
The more correct way of doing what you want is to have an event type and an object pointer. So an event fires on a specific object. The event type would be a non-member function (or a static member). It would be passed the object pointer. And it would call some actual member function of that object.
Nowadays, the event type could be a std/boost::function. However, since the function parameters have to stay the same type for all events, this doesn't really fix your problem. You can't call SpecificClass::onBar from a BaseClass pointer unless you do a cast to a SpecificClass. And the event calling function would not know to do this. So you still can't put SpecificClass::onBar in the std/boost::function object; you still need some standalone function to do the cast for you.
This all just seems to be a terrible use of polymorphism. Why does SpecificClass need to derive from BaseClass at all? Can't they just be two unrelated classes?
A: After some thought and a redesign i was able to achieve what i wanted. Although i am stubborn and still using inheritance i have reimplemented the map. This is how it works now:
class Location {
// ...
protected:
std::map<std::string, std::function<void(void)>> m_mEvents;
};
And now i can handle it like this:
class CivicCenter : public Location {
public:
CivicCenter() {
// this is done by a macro which lookes better than this
this->m_mEvents["onTriggerSomething"] =
std::bind(&CivicCenter::onTriggerSomething, this);
}
void onTriggerSomething() {
// ...
}
// ...
};
With easy use of std::bind i am able to implement generic function pointers. When using parameters like in std::function<void(int, int)> remeber to use either boost's _1 and _2 or lambda expressions like me:
std::function<void(int,int)> f = [=](int a, int b) {
this->anotherFunctionWithParams(a, b);
};
But this is just pointed out due to completeness of my solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Silverlight and MVC: post object to controller method I have an MVC project in which a controller action returns some JSON data (i.e. via /Home/GetData URL). This action also takes a custom object as a param.
This signature for the action is JsonResult GetData (MyCustomObject o)
I also have a client Silverlight project in which I'm constructing MyCustomObject and trying to call this URL (/Home/GetData/) via HttpWebRequest. However, I'm having trouble figuring out how to post in my object in this call. Do I need to serialize it to Json in order to pass it in?
Thanks so much!
A: MVC can accept and bind the submitted data to your MyCustomObject object, regardless of whether it is submitted as JSON, XML, a query string, a standard form POST, etc.
MVC does not require the object to be submitted in a particular fashion. That is up to you as the designer to determine what works best under the particular circumstances, given all of your requirements.
When submitted, MVC will use the ValueProvider suitable to the form of the data submitted, and the DefaultModelBinder will attempt to use the values in the ValueProvider to bind to your model.
A: Thanks for your help! Since the web app handles this with a getJSON call, I ended posting the object as a query string param i.e. I'm making a web request to http://../controller/action/view.aspx?custObject.property1=<value>&custObject.property2=<value> etc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: php problem with function and eval on array I have function:
function selects($sql,$tmpl) {
preg_match_all('/{[^}]*}/', $tmpl, $m);
foreach($m[0] as $key => $val) {
$find[] = $val;
$replace[] = '$row[\''.str_replace(array('{','}'),"",$val).'\']';
}
eval($replace);
while($row = mysql_fetch_array($sql))
{
$selects .= str_replace($find, $replace, $tmpl)."\n";
}
return $selects;
}
echo selects($country_sql,'<option value="{id}">{name}</option>');
It outputs:
<option value="$row['id']">$row['name']</option>
It should output:
<option value="1">something</option>
<option value="2">something</option>
...
Any ideas ?
I wrote this function because I have many different selects and I need different templates for them.
Thanks.
A: This works for me considering $country_sql is a sql statement
<?php
function selects($sql,$template) {
preg_match_all('/{([^}]*)}/', $template, $matches);
$result = mysql_query($sql); //were missing this?
$select = '';
while($row = mysql_fetch_assoc($result)){
$aux = $template;
for($i = 0; $i < count($matches[0]); $i++){
$aux = str_replace($matches[0][$i], $row[$matches[1][$i]],$aux);
}
$select .= $aux."\n";
}
return $select;
}
echo "<select>";
echo selects($country_sql,'<option value="{id}">{name}</option>');
echo "</select>";
?>
You could add the <select> part to the function but that's up to you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Grails global styling I was wondering how one would apply a global stylesheet to their entire site? I want to add twitter bootstrap, and a select number of other global styles, so that all the visuals are consistent.
Would I add a <link> to the layouts/main.gsp file?
UPDATE
Seems it's the css/main.css file that I'm interested in. Along with the layouts/main.gsp's reference to it. Could someone confirm this?
A: By default grails will use the "main" layout for scaffolding. So yes, those are the two files you are interested in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how do you copy a url into variable I'm trying to copy a url that looks like this: http://domain.com/myfile.php?test-main
So I'm trying to get the url so I can add variable r to the end like so: http://domain.com/myfile.php?test-main?r=stuff
When I use $_SERVER['REQUEST_URI'] it just copies the file name myfile.php and not the other variables. Any one how I can copy the entire url?
A: $addr = "http://".$_SERVER['SERVER_NAME']."/".$_SERVER['REQUEST_URI']."?".$_SERVER['QUERY_STRING']."&r=stuff";
And you might want to filter variables for a possible XSS attack
A: Build it yourself out of the provided parts.
Do a print_r($_SERVER); to see all available
The main one you want to add is HTTP_HOST
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Namespaces and Mixins I'm trying to clean up our namespaces. Basically our setup is somewhat like
class myClass
include myModule1
include myModule2
@important_var #critical instance variable
Basically @important_var is a telnet handler that almost all methods need to get at. This works fine with the way it is setup right now. Unfortunately myModule1 & myModule2 are getting huge. So I keep running into namespace collisions for the methods.
I'd love to access methods with a module wrapper eg:
myClass_instance.myModule1.a_method
But I can't figure out how to do this or some other cleaner name spacing idea?
A: Based on the idea to build a naming convention for the methods inside the modules I prepared a automated version:
module MyModule1
def m; "M1#m <#{@important_var }>"; end
#method according naming convention
def m1_action; "M1#m1 <#{@important_var }>"; end
end
module MyModule2
def m; "M2#m <#{@important_var }>"; end
#method according naming convention
def m2_action; "M2#m2 <#{@important_var }>"; end
end
class MyClass
#add prefix to each method of the included module.
def self.myinclude( mod, prefix )
include mod
#alias each method with selected prefix
mod.instance_methods.each{|meth|
if meth.to_s[0..prefix.size-1] == prefix
#ok, method follows naming convention
else #store method as alias
rename = "#{prefix}#{meth}".to_sym
alias_method(rename, meth)
puts "Wrong name for #{mod}##{meth} -> #{rename}"
end
}
#define a method '<<prefix>> to call the methods
define_method(prefix){ |meth, *args, &block | send "#{prefix}#{meth}".to_sym *args, &block }
end
myinclude MyModule1, 'm1_'
myinclude MyModule2, 'm2_'
def initialize
@important_var = 'important variable' #critical instance variable
end
end
###################
puts "-------Test method calls--------"
m = MyClass.new
p m.m1_action
p m.m2_action
p m.m #last include wins
puts "Use renamed methods"
p m.m1_m
p m.m2_m
puts "Use 'moduled' methods"
p m.m1_(:m)
p m.m2_(:m)
myinclude includes the module and checks, if each method begins with a defined prefix. If not the method is defined (via alias). In addition you get a method called like the prefix. This method forwards the call to the original module-method. See example in the code end.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TFS not updating development Server We just started using TFS, what's happening is that when a developer modify a code file TFS updates it automatically, but when i go to development server to move files from Development server, files dates are not updated. Is there any easier way of moving files from TFS to staging and production ? or may be any easier way that TFS can update development server automatically?
A: Why don't you use MSDeploy to deploy your web application throught the different servers?
http://msdn.microsoft.com/en-us/library/dd465322.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Struts2+Spring 3 validations issue I am trying to use struts2 validations. I have a setup with Struts2.2.3 and Spring 3.0.5. I have a -validation.xml in place. Fields are getting validated and error message is getting displayed on the server console, but its not getting displayed on the UI. Also action is not getting forwarded to the results specified for the "input" tag.
My action class does not extend from ActionSupport instead it implements Preparable. Is this could be the problem?
So I also tried with my Action class define as
public class CandidateAction extends ActionSupport implements Preparable
on hitting the page i am getting following error
Invalid action class configuration that references an unknown class named [candidateAction]
even though i have a bean defined with name "candidateAction" in the application context.xml
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="dao" class="org.kovid.dao.impl.DaoImpl" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/xyz" />
<property name="username" value="abc" />
<property name="password" value="abc" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="baseAction" scope="prototype" class="org.kovid.action.BaseAction">
</bean>
<bean id="candidateAction" scope="prototype"
class="org.kovid.matrimony.action.CandidateAction">
<constructor-arg ref="dao" />
</bean>
<bean id="simpleSearchAction" scope="prototype"
class="org.kovid.matrimony.action.SimpleSearchAction">
<constructor-arg ref="dao" />
</bean>
<bean id="advanceSearchAction" scope="prototype"
class="org.kovid.matrimony.action.AdvanceSearchAction">
<constructor-arg ref="dao" />
</bean>
<bean id="imageAction" scope="prototype"
class="org.kovid.matrimony.action.ImageAction">
<constructor-arg ref="dao" />
</bean>
</beans>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: alternative to htmlspecialchars We can use htmlspecialchars to stip out html tags.
$name = $_POST['inputbox1'];
$name = htmlspecialchars($name);
echo "Welcome".$name;
Is there another alternative?
A: PHP's strip_tags(..) might be what you're looking for.
A: If you're looking to actually strip the tags, check out strip_tags(), but if you're looking for a semi-equivalent function, have a look at htmlentities().
A: You can use dedicated alternative function called strip_tags.
And remember, php.net is Your friend :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Load content via ajax in plone page I'm working on a website which has been developed in plone. Now I'm facing an issue, I would like to load certain content from a template via an ajax call on normal Plone page(on some event trigger).
Do I need to create any python script??If yes where has it to be placed? and moreover how do I integrate it with TAL(I guess that would be needed) but I'm not sure how.
Could anyone guide me on this with necessary pointers/docs that I should look into?It would of great help to come over my issue and get things rolling.
Thanks,
Avinash
A: In the "Plone Developer Documentation" there's a section for Javascripting in Plone that perfectly fits your needs
A: Your question is a bit vague:
From your question, it seems that you just want your ajax call to return html to populate data on the page somewhere then?
Also, it sounds like you want to do the development TTW in the ZMI? Most developers would would use an add-on product and return your ajax response.
However, you can do it TTW with page templates just fine.
*
*Create the new page template
*populate it with the template code that gives you the desired output when called within the context of content on a site. For example, http://mysite.com/plone/page/my-template
*in your javascript, use a url that in the ajax call: $.ajax({url: 'http://mysite.com/plone/page/my-template', success: function(data){ $('#content').append(data);}})
It's not really anything special to do ajax within plone--just use the tools available and piece it together.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Shebang Notation: Python Scripts on Windows and Linux? I have some small utility scripts written in Python that I want to be usable on both Windows and Linux. I want to avoid having to explicitly invoke the Python interpreter. Is there an easy way to point shebang notation to the correct locations on both Windows and Linux? If not, is there another way to allow implicit invocation of the Python interpreter on both Windows and Linux without having to modify the script when transferring between operating systems?
Edit: The shebang support on Windows is provided Cygwin, but I want to use the native Windows Python interpreter on Windows, not the Cygwin one.
Edit # 2: It appears that shebang notation overrides file associations in Cygwin terminals. I guess I could just uninstall Cygwin Python and symlink /usr/bin/python to Windows-native Python.
A: Read up on the Python Launcher for Windows in the docs, which was initially described in PEP 397. It lets
you define custom shebang configurations in "py.ini" (e.g. to use pypy),
and out of the box you can use virtual shebangs such as #!/usr/bin/env python3, or shebangs with real paths such as #!"C:\Python33\python.exe". (Quoting is required for paths containing spaces.) You can also add command-line options to a shebang. For example, the following shebang adds the option to enter interactive mode after the script terminates: #!/usr/bin/python3 -i.
The installer associates .py (console) and .pyw (GUI) script file types with the respectively named launchers, py.exe and pyw.exe, in order to enable shebang support for scripts in Windows. For an all-users installation, the launchers are installed to the Windows folder (i.e. %SystemRoot%). For a per-user installation, you may need to manually add the installation directory to PATH in order to use py.exe in the shell (*). Then from the command line you can run Python via py -2, py -3, py -2.6, py -3.3-32 (32-bit), and so on. The launcher is handy when combined with -m to run a module as a script using a particular version of the interpreter, e.g. py -3 -m pip install.
(*) The new installer in 3.5+ defaults to "%LocalAppData%\Programs\Python\Launcher" for a per-user installation of the launcher, instead of installing it beside "python.exe", and it automatically adds this directory to PATH.
A: Unless you are using cygwin, windows has no shebang support. However, when you install python, it add as file association for .py files. If you put just the name of your script on the command line, or double click it in windows explorer, then it will run through python.
What I do is include a #!/usr/bin/env python shebang in my scripts. This allows for shebang support on linux. If you run it on a windows machine with python installed, then the file association should be there, and it will run as well.
A: Short answer:
The easiest way is to install git for windows wich comes with GitBash. Then add shebang lines in your scripts to indicate they should be run with python when executed.
#!/usr/bin/env python
More info:
Unlike Cygwin, git bash uses your native windows applications and lets you use bash scripts without any configuration.
It will automatically treat any file with a shebang line as executable the same way Linux shells do.
eg: #!/usr/bin/env php or #!/usr/bin/env node or any other application you want will work as long as you add the paths to your windows ENV path.
You can edit env vars in windows by hitting start and typing env should be the first option.
Git bash also installs git and hooks it up with a credentials manager for you and makes it super easy to sign into 2fa-enabled svn services and a ton of other handy developer features.
Git bash is IMO a must on every developer's machine.
Another option:
Install WSL (Windows Subsystem for Linux) which will work the same.
WSL also lets you install native Linux versions of all your command line applications if you prefer.
Linux binaries will take precedence over windows ones if installed but you can still choose to run the windows version of commands any time you want by specifically adding .exe on the end.
A: Install pywin32. One of the nice thing is it setups the file association of *.py to the python interpreter.
A: sorry for open old topic.
I create one file py.cmd and place it in the C:\Windows\System32 folder
py.bat:
@(
@set /p shebang=
)<%1
@set shebang=%shebang:#! =%
@%shebang% %1 %2 %3 %4 %5 %6 %7 %8 %9
py.bat file explain:
*
*Get the first line from *.py file
*Remove shebang characters "#! "
*Run python file using shebang python path
All windows python script must start with shebang line as the first line in the code:
#! c:\Python27\python.exe
or
#! c:\Python37\python.exe
Then run it:
cmd> py SomePyFile.py param1 param1 paramX
A: Not with shebang ... but you might be able to set up a file association, see this SO question which deals with Perl and the associated answers which will also be pertinent as there's known problems with Windows and stdin/out redirection...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "92"
}
|
Q: IE8 crashing after browsing a site for a few minutes All,
I've a problem with a site I coded. It works fine under other browsers, but IE8 crashes after clicking around a few times. It doesn't show any error message, just crashes.
I attached WinDbg and made a dump when it crashed. When analyzing the dump WinDbg show this:
This dump file has an exception of interest stored in it.
The stored exception information can be accessed via .ecxr.
(e58.1fa8): Access violation - code c0000005 (first/second chance not available)
eax=00000000 ebx=00000000 ecx=06c00050 edx=00000000 esi=06c00050 edi=06c00050
eip=3cf07b98 esp=016cdb38 ebp=016cdc48 iopl=0 nv up ei pl zr na pe nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00210246
mshtml!CDoc::OnUrlImgCtxChange+0x242:
3cf07b98 8b4308 mov eax,dword ptr [ebx+8] ds:0023:00000008=????????
0:008> .ecxr
eax=00000000 ebx=00000000 ecx=06c00050 edx=00000000 esi=06c00050 edi=06c00050
eip=3cf07b98 esp=016cdb38 ebp=016cdc48 iopl=0 nv up ei pl zr na pe nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00210246
mshtml!CDoc::OnUrlImgCtxChange+0x242:
3cf07b98 8b4308 mov eax,dword ptr [ebx+8] ds:0023:00000008=????????
Not sure if this is connected with JS, but I'm using jquery 1.6.2, jquery.fancybox 1.3.4, jquery.orbit 1.2.3, cufon, modernizr 2.0 and HTML5 Boilerplate.[1].
Any idea what it might be or what do try next?
A: Just to put my own comment as an answer:
This was caused by a JQuery bug #9823
See this other question on SE for more details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: turning pixels off got a question about turning pixels off on a screen. I can make a black image and show it full screen on my pc. Yet the screen looks black but the pixels aren't off. You can see the difference between an off screen and a black screen.
I am wordering if it would be possible to turn these pixels off via a program or is the best you can do: make them black?
I am looking for the delphi code to turn off the right half of my computer screen?
hope its clear!
thx
A: If I get it right, you want to turn off the power from the half of your monitor, what is impossible. It would have to be supported by your graphic card as well as by your monitor driver.
A: You can't turn off individual pixels, or parts of the screen. Either the screen is on or it's off.
This works a bit differently depending on what kind of screen it is, but nowadays LCD screens is the most common kind. An LCD screen has a backlight behind an LCD display; the backlight is always on, and shine through the LCD display when the crystals are transparent. Pixels are made black by making the crystals non-transparent, however they still let a fraction of the back light through. To make pixels completely black you would have to turn the backlight off, and you can only to that for the entire screen.
A: Turning off pixels can only work on new all-lead displays, except if you are switching off the computer, when all systems (including the screen) are off.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there any way to reverse NSNumericSearch so NSStrings with numbers in them can be ordered in 9, 8, 7, 6... etc? I have code that returns an NSComparisonResult. My codes works great for sorting my arrays in Ascending and Descending order when they are NSStrings with only alphabetic characters in them.
When the NSStrings have numbers in them, such as Seinfeld (Season 5) and Seinfeld (Season 6) they are sorting correctly Ascending in the order of 5 and then 6. But Descending it still sorts it as 5 and 6. Here's an example:
Ascending:
Batman,
Seinfeld (Season 5),
Seinfeld (Season 6),
Zoolander
Descending:
Zoolander,
Seinfeld (Season 5),
Seinfeld (Season 6),
Batman
The descending code I have looks like this to return the comparison:
return [(NSString *)secondString compare:(NSString *)firstString options:NSNumericSearch];
Any ideas on how to reverse NSStrings with numbers in them?
By the way, I can't use NSSortDescriptor in my case. The code I have requires a custom function to be built because I have to do some string appending, etc, before the sort occurs. I didn't include it all for simplicity.
A: Just return -(NSComparisonResult)
A: This code works for me:
NSArray *array = [NSArray arrayWithObjects:@"Batman",
@"Seinfeld (Season 5)",
@"Seinfeld (Season 6)",
@"Zoolander", nil];
//for ascending
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id firstString, id secondString) {
return [(NSString *)firstString compare:(NSString *)secondString options:NSNumericSearch];
}];
NSLog(@"========= %@================= ", sortedArray);
//for descending
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id firstString, id secondString) {
return [(NSString *)secondString compare:(NSString *)firstString options:NSNumericSearch];
}];
A: To expand on Benjamin Mayo's answer:
Let's say your "ascending" comparison function is this:
static NSComparisonResult compareAscending(id s1, id s2, void *context) {
return [s1 compare:s2 options:NSNumericSearch];
}
Then this should be your "descending" comparison function:
static NSComparisonResult compareDescending(id s1, id s2, void *context) {
return -compareAscending(s1, s2, context);
}
A: Essentially the same comment as above, but here's full source and output to prove it works (iOS 4.3 simulator tested):
NSArray * strings = [NSArray arrayWithObjects: @"Seinfeld (Season 6)", @"Batman", @"Seinfeld (Season 5)", @"Zoolander", nil];
NSArray * sorted1 = [strings sortedArrayUsingComparator: ^(id first, id second) {
return [(NSString *)first compare:(NSString *)second options: NSNumericSearch];
}];
NSArray * sorted2 = [strings sortedArrayUsingComparator: ^(id first, id second) {
return - [(NSString *)first compare:(NSString *)second options: NSNumericSearch];
// or (to be more clear, but less efficient)
// return -1 * [(NSString *)first compare:(NSString *)second options: NSNumericSearch];
}];
NSLog(@"starting: %@", strings );
NSLog(@"sort1: %@", sorted1 );
NSLog(@"sort2: %@", sorted2 );
output:
2011-10-19 02:09:07.557 test2222[16793:207] starting: (
"Seinfeld (Season 6)",
Batman,
"Seinfeld (Season 5)",
Zoolander
)
2011-10-19 02:09:07.558 test2222[16793:207] sort1: (
Batman,
"Seinfeld (Season 5)",
"Seinfeld (Season 6)",
Zoolander
)
2011-10-19 02:09:07.558 test2222[16793:207] sort2: (
Zoolander,
"Seinfeld (Season 6)",
"Seinfeld (Season 5)",
Batman
)
In answer to Ethan Allen, here's the output for a test with numbers in front:
2011-12-14 21:01:26.535 Test[7475:f803] starting: (
"2001 Seinfeld (Season 6)",
"1999 Batman",
"2112 Seinfeld (Season 5)",
"10 Zoolander"
)
2011-12-14 21:01:26.537 Test[7475:f803] sort1: (
"10 Zoolander",
"1999 Batman",
"2001 Seinfeld (Season 6)",
"2112 Seinfeld (Season 5)"
)
2011-12-14 21:01:26.537 Test[7475:f803] sort2: (
"2112 Seinfeld (Season 5)",
"2001 Seinfeld (Season 6)",
"1999 Batman",
"10 Zoolander"
)
A: So I know it may be painful however I believe it would be useful for you in the long run. I recommend writing your own sorting function and here what I would do. You might need two functions but this way you can tweak them to be exactly what you want.
In order to sort them I recommend looking at each characters ascii value and adding them all together and then comparing them against anothers ascii value all together and if descending return the lower one if ascending return the higher one. As for the sorting algorithm part You could use an bubble sort. That is the easiest however it is slow so if this is something that needs to be quick then I would recommend taking time to look at a mergesort. Anyways hope this helps. If you need help righting a sorting method ide love to help you, it looks like you are a pretty good coder though:)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Prompted for password on git pull origin [branch] When I attempt to git pull origin [branch] in order to pull in changes to the repo, I am prompted for a password. My system password and just hitting enter return: "fatal: Authentication failed".
The thing is, I never entered a password for this project in the past and this was not the case when I began it last week, nor any of the times I pushed and pulled since then. Speaking to my client, they thought it was something with my SSH keys.
I double checked the keys and made sure they were correct, running ssh git@github.com. I'm getting:
Hi bdkay! You've successfully authenticated, but GitHub does not provide shell access.
Connection to github.com closed.
which makes me think it succeeded. However, right before that a troublesome line reading: "PTY allocation request failed on channel 0" occurs. The client says I'm still added to the repo in github and they have not changed anything on their end. I'm still working on the same machine but cannot seem to find a fix through google or searching this site. Any help is greatly appreciated.
A: If you're being prompted for a password, and not your SSH key's passphrase, then you're not using the SSH URL. HTTPS asks for user/pass auth, SSH uses key/passphrase. Check your remote's URL with git remote -v, and if you need to fix it use git remote set-url.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How can I set the width of a button during run time? I want to set the button width during run time and I want it to be equal to 50% of the display width.
I used the following but I have a problem "nothing appears in emulator" and says
"Process stopped unexpectedly. Please try again"
.java
public class experiment extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Button btn = (Button) findViewById(R.id.btnmarwa);
btn.setWidth(width/2);
setContentView(R.layout.emailpopup);
}
}
When I commented this line
btn.setWidth(width);
There is no errors and the layout appears, So where to set the new width to the button in .java file??
A: Is not directly about your question, but you have to put this lines After setContentView() 'cause the findViewById method.
Like try this :
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.emailpopup);
Button btn = (Button) findViewById(R.id.btnmarwa);
btn.setWidth(width/2);
A: You should state what the exception in the log is, so that we can work out why it's crashing.
My guess is that btn is null, because findViewById is returning null, and so btn.setWidth() is causing a NullPointerException.
This is probably because you are setting setContentView after findViewById, so the view hasn't been inflated yet.
Change the order around, making sure setContentView has been called before you call findViewById.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery clueTip: show/hide on mouseover and sticky on click I'm using the cluetip plugin together with the jQuery FullCalendar to show event details which works quite good. I would like to have a link in each description that the user can click on. But I don't want to have the users have to click on each event to show the info.
Is there any option I can use to show the clueTip on mouseover, hide it on mouseout, but make it sticky on click? Didn't found one yet but I guess that would make very intuitive behaviour...
A: Updated to working example:
<a class="title" href="#" title="Test tooltip 1">test 1</a>
$(document).ready(function () {
var keepTooltip = false;
$('a.title').cluetip({ splitTitle: '|', sticky: true })
.mouseout(function () {
if (!keepTooltip) {
$('#cluetip').hide();
}
});
$('a.title').click(function (e) {
e.preventDefault();
keepTooltip = true;
});
});
A: (I'm not sure if you've tried this or if this will help but)
There is a 'hover' activation on cluetip:
activation: 'hover', // set to 'click' to force user to click
to show clueTip
http://plugins.learningjquery.com/cluetip/#options
A: Finally found a working way to solve my problem - by creating 2 cluetips... the 'mouseout' solution didn't work as expected :-/
var stickyTooltip = false;
var tooltipClass;
// ...
$(eventElement).attr('title', event.title+'\n'+info).cluetip({
splitTitle: '\n',
sticky: true,
activation: 'click',
closeText: 'Close',
onShow: function(ct, c) {
stickyTooltip = true;
$('#clickInfo').hide(); // #clickInfo is a span that tells user how to fix tooltips
tooltipClass = $(ct).attr('class');
},
onHide: function(ct, ci) {
stickyTooltip = false;
}
}).cluetip({
splitTitle: '\n',
sticky: false,
activation: 'hover',
onActivate: function(e) {
return !stickyTooltip;
},
onShow: function(ct, c) {
$('#clickInfo').show();
stickyTooltip = false;
},
onHide: function(ct, ci) {
$(ct).attr('class', tooltipClass).toggle(stickyTooltip);
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What are the best cross-platform application development tools? I have an application I built in Flash that runs with no problems on Windows and OSX. I'd like to extend it to mobile platforms and I want to be able to call programs written in the native language of each platform.
I understand that Flex can be used on mobile platforms and that it can call native code, but I'm a little confused by what I've read about Flex. Can I use the Adobe Flash development environment to build Flex applications? Will our users need the Adobe Air runtime to run the programs? And what the heck does Air add to the capabilities? We need strong audio and video capabilities, a built-in database is not a requirement.
Many thanks for your comments on this topic.
A:
I understand that Flex can be used on mobile platforms and that it can
call native code,
This is almost true. If you use Flex to build an application that targets Adobe AIR 3; then you can make use of Native Extensions which allow you to execute native code not the device. AIR 3 has a public release candidate and I expect we'll hear a lot more about this at Adobe Max next week.
Can I use the Adobe Flash development environment to build Flex
applications?
You can use Adobe Flash Builder to build Flex applications. It is possibly, although difficult and uncommon, to use Adobe Flash Professional to build Flex Application. They are two very different tools designed for a very different audience.
Will our users need the Adobe Air runtime to run the programs?
Maybe. AIR 3 introduces something called Captive runtime. This allows you to bundle up the AIR Runtime with your application, so that Adobe AIR is not required as a separate download. The use of captive runtime is the only way to deploy AIR applications to iOS. AIR 3 is the first release to expand that feature to other platforms.
If you choose not to compile your code using captive runtime, then your users will need the AIR runtime installed.
You could also target Adobe Flex in the browser on Android and Blackberry Playbook. In which case, the user would not need AIR installed at all.
And what the heck does Air add to the capabilities?
It really allows you to create mobile applications; as opposed to browser based apps. That's the big one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Header information, headers already sent. I have tried looking at the code and eliminating whitespace as suggested but it didn't work This error i can't get rid off on my debug output in wordpress.
Warning: Cannot modify header information - headers already sent by (output started at /home/zonafu54/public_html/www/wp-includes/functions.php:3382) in /home/zonafu54/public_html/www/wp-includes/pluggable.php on line 934
I posted something else in this post but i forgot to enter some information so i'm reposting hoping i provide enough information.
I may have deleted some plugins forcefully. Specially that pesky WPSQT that wouldn't let me unistall it. And also their database tables i deleted manually.
If you need more information, please ask.
A: It looks like it's being caused by a plugin - have you tried going through all your plugins, switching each one off one at a time, and every time one is switched off refresh and see if the error has gone?
When it does disappear, you'll know it was (most likely) the one your just switched off. A bit of trial and error should confirm this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reduce folder lists to lowest common folder I have a giant list of file paths that are simply too large for our SCM to process. I need to whittle them down based on the lowest common level folder. For example, given the following paths:
//folder1/folder2/folder2
//folder1/folder2/folder5
//folder1/folder3/folder6
//folderx/foldery/folder9
//folderx/foldery/folder10
Based on that, I would like to arrive at this:
//folder1/folder2
//folder1/folder3
//folderx/foldery
The folder list will be read from a text file, and is around 2M line long.
Any help would be greatly appreciated.
A: This looks to be a good use for split() and hashes:
use strict;
use warnings;
my %seen;
foreach my $path ( @paths ) {
$path =~ s|^//||; # Strip off leading //
my @elems = split( '/', $path );
$seen{$elems[0]}{$elems[1]}++;
}
foreach my $rootpath ( sort keys %seen ) {
foreach my $secondpath ( sort keys %{$seen{$rootpath}} ) {
print "//" . $rootpath . "/" . $secondpath . "\n";
}
}
If you only want to print out paths that have been seen twice or more, insert a next if $seen{$rootpath}{$secondpath} > 1; before the print().
I haven't tested this so there could be syntax errors, but the code gives the general gist.
A: How about:
#!/usr/local/bin/perl
use strict;
use warnings;
use 5.010;
my %out;
while(<DATA>) {
chomp;
m#^(//[^/]+/[^/]+)#;
$out{$1} = 1;
}
say for keys%out;
__DATA__
//folder1/folder2/folder2
//folder1/folder2/folder5
//folder1/folder3/folder6
//folderx/foldery/folder9
//folderx/foldery/folder10
output:
//folderx/foldery
//folder1/folder3
//folder1/folder2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get a part of CSS code to JavaScript/jQuery? I have asked a question few days ago and I got a answer, that wasn't truly answering it but it gave me an idea... The code below was in that answer and I quite understood it after a moment...Except one part. I wanted to animate some radial gradients and that guy made a jQuery plugin that wasn't doing what I wanted but it at least was some base. So the part that I don't understand is the one with command
.match(\d+/g))
He somehow (if I am right) got the RGB from the gradient and than used it to animate between the two colors. I tried to find something on google and jQ documentation but I wasn't able to find something startable with.
So my question is how can I get some stuff out of CSS like parts of gradients etc.? I want to make a gradient animating plugin for jQuery but I can't until I figure out how to change only parts of css attribs without changing the whole one as the guy did.
-- His example
jQuery.fx.step.gradient = function(fx) {
if (fx.state == 0) { //On the start iteration, convert the colors to arrays for calculation.
fx.start = fx.elem.style.background.match(/\d+/g); //Parse original state for numbers. Tougher because radial gradients have more of them
fx.start[0] = parseInt(fx.start[0]);
fx.start[1] = parseInt(fx.start[1]);
fx.start[2] = parseInt(fx.start[2]);
fx.end = fx.end.match(/\d+/g);
fx.end[0] = parseInt(fx.end[0]);
fx.end[1] = parseInt(fx.end[1]);
fx.end[2] = parseInt(fx.end[2]);
}
fx.elem.style.background = "-webkit-linear-gradient(rgb(" + [
Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")," + "rgb(0,0,0))";
}
$(this).animate({"gradient": "rgb(0, 255, 0)"});
--David
A: Well be careful, in his example the final code is actually
$(this).animate({"gradient": "rgb(" + c.join(",") + ")"});
You have what looks like a hard coded string in your question.
$.match() is a regex function that queries the object (fx.end or fx.elem.style.background) for the specified search string (/\d+/g). As he commented, he is parsing for numbers:
fx.start = fx.elem.style.background.match(/\d+/g); //Parse original state for numbers. Tougher because radial gradients have more of them
A regex pattern matching guide (one of gazillions) can be found here.
As far as assigning CSS values, in the end they are just strings. So you can retrieve any CSS value you want and parse it and plug it back in.
$('#myobject').css('<css property name>') // get value
$('#myobject').css('<css property name>', '<value'>) // set value
The logic you will have to work out yourself but it looks like the gentleman above has already pointed you in the right direction.
Or rather than just set the CSS property for gradient, in your case it seems you'd be using the animate plugin in jQuery UI along with his "gradient" method which does the CSS insertion for you.
$(this).animate({"gradient" : "<your parsed/calculated gradient value>"});
A: If you have a look at this JSFiddle, you'll see you can grab the gradient CSS for an element, however, it's the entire gradient definition instead of each value.
In the example above, FF6 spews out
-moz-radial-gradient(50% 50% 45deg, circle closest-side, rgb(255, 165, 0) 0%, rgb(255, 0, 0) 100%)
You could parse (sort of) with regex, but everyone writes their CSS differently so this would be pretty difficult.
There's a solution for setting the gradient, but not getting it. There should be good information in this answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django AJAX - suggestions I have made a functional site with django, but I have two forms which reside in separate pages. Since all the activities of the webapp will be centered around these forms, I want to put them both on the main page, to save space and preseve the "desktop" look and feel.
What would be the correct way to do it with Django?
To call the pages with the forms with Ajax call (I m thinking jQuery), thus maintaining the views relatively simple, or to merge the main page view with the forms views, which would result in messy code with lots of database hits, maybe unneccesary?
A: You could do this with Dajax (http://www.dajaxproject.com/), an awesome Django plugin for quick, simple AJAX implementation.
The index page could call a Dajaxice function with a callback javascript method for each of the forms. The Dajaxice function (a python method) would generate the html and the callback javascript method would write it to the screen element associated with that section.
I have a similar case where I have sections of data that all called separately by dajax, to populate a single edit screen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: web2py: How to rename a table? How do I rename a database table in web2py? If there is not a direct way, what is the best workaround to do this? All I found was this thread http://groups.google.com/group/web2py/browse_thread/thread/ef724508324347e2/7966a423c293bdec where the creator of web2py says he does not have an easy way.
A: To change the database schema while running web2py
db.executesql('ALTER TABLE old_name RENAME TO new_name;')
This will not change your code! Only you can change your code.
So, if you are only doing this once, say because you have an ugly or ambiguous table name and want to refactor your code, then it is likely best not to use web2py to change the table name in the database schema. Here is how I would do it.
*
*Stop the application
*Rename the table in the db schema using the sqlite3 console program, or whatever database management program you use instead. I guess this might be your real problem, because you are accustomed to using web2py as your database management program. Well, I guess you will have to learn how to use the sqlite3 console console program.
*Change the code in your model
*Restart the application.
However, if you really insist on using web2py only to manage your database, then something like this should work:
*
*Create a new controller, say 'table_rename' Add the line
db.executesql('ALTER TABLE old_name RENAME TO new_name;')
to the controller
*
*Brows to application/table_rename
*Stop the application
*Change your model code
*Remove table_rename
*Restart application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to remove actionPerformed methods in NetBeans When a JButton is added to a content pane, we can set an action by double clicking the button or Right click->Event->Action->actionPerformed.Let say, we set somthing to happen. Then we need to remove that function.It can be done easily by deleting the code we wrote in that buttton's actionPerformed. But the problem is, that button's actionPerformed method is still there even though it is not used any more and not needed.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//no function here.. but this code is still remaining. need to remove this code part as well
}
How can it be removed? I got the JButton for an example. Other components'action methods are like this.
A: Go to your JButton properties, Choose "Events", actionPerformed and choose "none" from the adjacent combobox. Your source code is cleaned!
Recent versions of Netbeans like 7.3, do not offer "none" as an option, but allow you to delete the actionPerformed method by deleting the name of the method or by pressing 1, 2 and 3 buttons:
A: If the button that the action was registered to is no longer in the form (this happened to me after I manually replaced the .form file with a previous backup) then you wont be able to do Costis Aivalis's solution. In this case you can open the .java file with another text editor and delete the event handler there.
A: In the latest version of netbeans click the button with the 3 periods [...] just to the right ov the combo box and a new control listing the handlers is displayed. Select the one to remove and press the [Remove] button.
A: Identify your .java file, then close Netbeans and edit your file directly from a text editor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Can't deploy Play application into Heroku I'm having issues deploying a Play application into Heroku. I've had no problems deploying other basic applications without modules, but this one is giving me the following error:
@ubuntu:~/$ git push heroku master
Counting objects: 812, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (699/699), done.
Writing objects: 100% (794/794), 2.00 MiB, done.
Total 794 (delta 145), reused 0 (delta 0)
-----> Heroku receiving push
-----> Play! app detected
-----> Installing ivysettings.xml..... done
-----> Building Play! application...
~ _ _
~ _ __ | | __ _ _ _| |
~ | '_ \| |/ _' | || |_|
~ | __/|_|\____|\__ (_)
~ |_| |__/
~
~ play! 1.2.3, http://www.playframework.org
~
1.2.3
Play! application root found at ./mods/playcopy/crud-1.2.3/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/use-gs-in-tags/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/demo/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/inline-dependency-declaring/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/jquery-ui/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/booking/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/less-and-coffee/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/chat/
./mods/playcopy/greenscript-1.2.6h/
./
Resolving dependencies: .play/play dependencies ./mods/playcopy/crud-1.2.3/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/use-gs-in-tags/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/demo/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/inline-dependency-declaring/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/jquery-ui/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/booking/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/less-and-coffee/
./mods/playcopy/greenscript-1.2.6h/samples-and-tests/chat/
./mods/playcopy/greenscript-1.2.6h/
./ --forceCopy --silent -Duser.home=/tmp/build_1hn7e8ahaqrso 2>&1
~ Resolving dependencies using /tmp/build_1hn7e8ahaqrso/mods/playcopy/crud-1.2.3/conf/dependencies.yml,
~
~
~ No dependencies to install
~
~ Done!
~
~ _ _
~ _ __ | | __ _ _ _| |
~ | '_ \| |/ _' | || |_|
~ | __/|_|\____|\__ (_)
~ |_| |__/
~
~ play! 1.2.3, http://www.playframework.org
~
/app/slug-compiler/lib/../language_packs/play/bin/compile: line 64: ./mods/playcopy/greenscript-1.2.6h/samples-and-tests/use-gs-in-tags/: is a directory
/app/slug-compiler/lib/../language_packs/play/bin/compile: line 65: ./mods/playcopy/greenscript-1.2.6h/samples-and-tests/demo/: is a directory
/app/slug-compiler/lib/../language_packs/play/bin/compile: line 66: ./mods/playcopy/greenscript-1.2.6h/samples-and-tests/inline-dependency-declaring/: is a directory
/app/slug-compiler/lib/../language_packs/play/bin/compile: line 67: ./mods/playcopy/greenscript-1.2.6h/samples-and-tests/jquery-ui/: is a directory
/app/slug-compiler/lib/../language_packs/play/bin/compile: line 68: ./mods/playcopy/greenscript-1.2.6h/samples-and-tests/booking/: is a directory
/app/slug-compiler/lib/../language_packs/play/bin/compile: line 69: ./mods/playcopy/greenscript-1.2.6h/samples-and-tests/less-and-coffee/: is a directory
/app/slug-compiler/lib/../language_packs/play/bin/compile: line 70: ./mods/playcopy/greenscript-1.2.6h/samples-and-tests/chat/: is a directory
/app/slug-compiler/lib/../language_packs/play/bin/compile: line 71: ./mods/playcopy/greenscript-1.2.6h/: is a directory
/app/slug-compiler/lib/../language_packs/play/bin/compile: line 72: ./: is a directory
! Failed to build Play! application
! Cleared Play! framework from cache
/app/slug-compiler/lib/language_pack.rb:35:in `block in compile': failed to compile Play! app (Slug::CompileError)
from /app/slug-compiler/lib/language_pack.rb:32:in `fork'
from /app/slug-compiler/lib/language_pack.rb:32:in `compile'
from /app/slug-compiler/lib/slug.rb:490:in `block in run_language_pack'
from /app/slug-compiler/lib/utils.rb:117:in `log'
from /app/slug-compiler/lib/slug.rb:727:in `log'
from /app/slug-compiler/lib/slug.rb:489:in `run_language_pack'
from /app/slug-compiler/lib/slug.rb:110:in `block (2 levels) in compile'
from /app/slug-compiler/lib/utils.rb:98:in `block in timeout'
from /usr/local/lib/ruby/1.9.1/timeout.rb:57:in `timeout'
from /app/slug-compiler/lib/utils.rb:98:in `rescue in timeout'
from /app/slug-compiler/lib/utils.rb:93:in `timeout'
from /app/slug-compiler/lib/slug.rb:99:in `block in compile'
from /app/slug-compiler/lib/utils.rb:117:in `log'
from /app/slug-compiler/lib/slug.rb:727:in `log'
from /app/slug-compiler/lib/slug.rb:98:in `compile'
from /app/slug-compiler/bin/slugc:85:in `block in <main>'
from /app/slug-compiler/lib/slug.rb:498:in `block in lock'
from /app/slug-compiler/lib/repo_lock.rb:44:in `call'
from /app/slug-compiler/lib/repo_lock.rb:44:in `run'
from /app/slug-compiler/lib/slug.rb:498:in `lock'
from /app/slug-compiler/bin/slugc:66:in `<main>'
-----> Discovering process types
Procfile declares types -> web
-----> Compiled slug size is 36.4MB
-----> Launching... done, v6
http://billeteo.herokuapp.com deployed to Heroku
To git@heroku.com:billeteo.git
53b789c..24f66a4 master -> master
Although I'm running from the root of my project, Heroku believes that my root is at:
Play! application root found at ./mods/playcopy/crud-1.2.3/
which, of course, doesn't contain the code and the process fails.
My application is standard Play app with the following dependencies.xml:
# Application dependencies
# Notes:
# play is an alias for play -> play $currentVersion
# play -> crud is an alias for play -> crud $currentVersion
# play -> secure is an alias for play -> secure $currentVersion
# Modules from the main repository use 'play' as organisation
require:
- play
- playcopy -> crud 1.2.3
- playcopy -> betterlogs 1.0
- playcopy -> cobertura 2.1
- playcopy -> mockito 0.1
- playcopy -> greenscript 1.2.6h
- custom -> useragentcheck 1.0
- org.hibernate -> hibernate-search 3.4.0.Final
repositories:
- localModules:
type: local
artifact: "${application.path}/mods/[organisation]/[module]-[revision]"
contains:
- playcopy
- custom
I'm using a local repository for some official Play modules as they may have some custom code (remove some unnecessary classes, change security, some logs, etc).
Anyone knows how to make Heroku find the right root? Could not find anything on Google...
A: The Play setup on Heroku didn't anticipate your particular setup here. Like you indicated, it's confused about where the root of your application is. I think we can push a fix to resolve this, but in the mean time, you should be able to work around it. Try this:
Zip your custom modules and change your dependencies.yml file to
...
repositories:
- localModules:
type: local
artifact: "${application.path}/mods/[organisation]/[module]-[revision].zip"
contains:
- playcopy
- custom
...
During dependency resolution, Play should unzip your custom modules and put them in the right place. Also, Heroku shouldn't get confused about where the root of your app is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can you enable auto-DataTemplate selection based on data type like you can with an items control? We're writing a very specialized ItemsControl which actually has three ContentPresenter's per 'row', each bound to a different object (think poor-man's grid) instead of the more common one, like a ListBox.
Now with a ListBox if you don't explicitly specify either an ItemTemplate or an ItemTemplateSelector, there seems to be some internal selector that applies the template based purely on data type. However, our ContentPresenter's aren't picking them up. We've also tried switching them to ContentControl's instead, but that hasn't worked either.
Now I know I can simply write my own DataTypeTemplateSelector that does this, but I'm wondering if that functionality is already 'baked in' somewhere considered its used with so many ItemsControl's (ListBox, TreeView, ComboBox', DataGrid, etc.) and according to this MSDN article...
http://msdn.microsoft.com/en-us/library/ms742521.aspx
...it should work by default! But again, it doesn't.
Here's our (pseudo) code...
<UserControl.Resources>
<!-- These all work when the relevant items are in a ListBox,
but not with stand-alone ContentPresenters or ContentControls -->
<DataTemplate DataType="local:SomeTypeA">
<TextBlock Text="{Binding Converter={c:DataTypeNameConverter}}" Foreground="Blue" />
</DataTemplate>
<DataTemplate DataType="local::SomeTypeB">
<TextBlock Text="{Binding Converter={c:DataTypeNameConverter}}" Foreground="Purple" />
</DataTemplate>
<DataTemplate DataType="local::SomeTypeC">
<TextBlock Text="{Binding Converter={c:DataTypeNameConverter}}" Foreground="Purple" />
</DataTemplate>
</UserControl.Resources>
<!-- These don't pick up the templates -->
<ContentControl Content="{Binding Field1}" />
<ContentPresenter Content="{Binding Field2}" />
<!-- This however does -->
<ListBox ItemsSource="{Binding AllItems}"
So... anyone want to take a stab at why not?
A: DataType, for whatever crazy reason, is of type Object, the DataTemplates hence have a string set in that property unless you use x:Type.
Edit: There is a very good reason for the property being an object, as always those who can (and do) read are clearly at an advantage:
If the template is intended for object data, this property contains the type name of the data object (as a string). To refer to the type name of the class, use the x:Type Markup Extension. If the template is intended for XML data, this property contains the XML element name. See the documentation remarks for details about specifying a non-default namespace for the XML element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Insights for pages that have been liked So I would think this would be an easy thing to do, but I'm completely lost right now. I have a website. It has a facebook page. That fb page has a bunch of likes and all is good. We also have the "like" button on various webpages throughout our website. If I go to those webpages individually, I can see how many people have hit the like button, but I have not found any where to see some reports. Ideally, I'd like to see:
*
*The most popular (liked) webpages on our website
*The total number of interactions (likes) across my domain
*The same basic demographic information that is available for our fb page
We have had the like button integrated for a few months now, but I'm not sure if it should be linked to our fb page or if I have to create a custom app to associate it with. Right now we have it assigned to our fb page.
Is this possible?
A: It's possible, but requires a few steps:
*
*Claim insights for your domain: http://developers.facebook.com/docs/insights/#claiming_a_domain
*Grab your domain ID: http://developers.facebook.com/docs/reference/fql/domain/
*Access insights using the graph API
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: looking up svn content by hash Content in the svn repository is uniquely identified using two pieces of information:
*
*repository path
*revision number
I am looking for a way to recover that information from a fixed-length message (say, 8 or 16 bytes). It is not enough to identify content in the repository from our fixed-length message by just storing the revision number. The path is variable length, and cannot fit in the message.
However, I was wondering if svn path+revision pairs can be accessed by hash, like how Git does it. Is there a mechanism for this already built into svn?
It would suffice if the path alone were accessible by hash, then I could store the revision number independently in the fixed-length message.
Would I have to keep an external database of used paths and their hashes, or does SVN provide a fast way to list all paths extant across all revisions that I can query on-demand?
Edit: This is practically the same question, but is inconclusive: SVN: translation between path and node ids?
A: SVN doesn't store files, it stores file systems. As such, the revision is used to access the correct revision of the file system, and then a portion of the path is used to access the file in question.
Internally SVN revisions inodes, with their own respective node ids. However, such "direct to the inode" access is typically not supported, as an inode lacks certain information that is generally necessary (like the file's name, owner, group, permissions, etc.).
Git on the other hand stores files, so it makes sense to find a better file id than the file name (which might stay the same for multiple revisions of the file), so Git uses a hash of the file's contents. Being file oriented, it's not uncommon to pull the file using its id (the hash).
Unfortunately, there's not an equivalent of pulling a file system by hash, because the hash's inputs would have to be based on the contents of the inode on a per-version of the inode basis. That would mean a way of hashing a tree's contents, which would be possible. Such a system would provide fast access to a particular historical version of a inode.
Probably the main reason it wasn't done this way is that fast client access of the inode isn't much of a concern in SVN. The SVN server already has the pointers and data structure to access the inodes on the server side, and it has knowledge of the remote repository's filesystem as transmitted by the client. This allows SVN to transmit the differences in the file systems to the client (not a full copy of the file system). Without a need to consistently pull full file systems, fast path access to a full file system pull isn't a priority.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Database Deployment issues I'm having a hard time deploying my website.
I got through some errors and they got resolved and I successfully published my website but when I try to open any page it gives me 404 or 500 Error
My host provider told me that if this page is using a database and it's not deployed then this is might be the problem
so I tried to deploy my database and I get the connectionString error.
The problem is that I'm not storing my connectionString in the web.config
It's stored in a property in my base DAL class and it's used by all the DAL classes
so I updated it but I get the same error
I dont know what's wrong, should I include the connectionString in the web.config ?
N.B When I build the package and I try to set the active mode to 'release' it returns the setting to 'debug'!
A:
"should I include the connectionString in the web.config ?"
Yes, your connection string should be defined in the <connectionStrings> section of the web.config for precisely this reason - so that you can easily change the setting to point to a different database environment when deploying your application to a different environment, without needing to recompile your code.
A: IIS recognizes your connection strings in the config file. I've seen it exposing them through the IIS management console when viewing a certain application. I had a similar problem once and it turned out it was an authentication issue. Applications on IIS run in a certain pool and under a certain user. If you specified to use windows authentication (integrated security) in your connection string then this user must have rights to access the database. If the user that runs the application doesn't have the necessary rights to connect to the database you should specify the username and password explicitly in the connection string.
In any case you can turn on includeExceptionDetailInFaults in your web.config and get a little bit more information on why your service is failing like so (msdn):
<serviceBehaviors>
<behavior>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
A: Assuming that your DAL is a class library, I would store the connection string in app.config. That way, you can easily change the connection string without having to put the connection string in every web application that uses the library.
A: "The problem is that I'm not storing my connectionString in the web.config It's stored in a property in my base DAL class and it's used by all the DAL classes so I updated it but I get the same error"
Yes, hard coding connection strings is a major problem. To answer your next question "should I include the connectionString in the web.config?", the answer is YES.
As for proper deployment of a database, you can look at this blog entry I created in 2008.
A: I'm sorry but all the answers advised me that I need to place the 'ConnectionString' in 'Web.config' but actually the whole problem was solved when I added my application to a virtual directory and I didn't need to change my DAL layer or add anything to the web.config
Of course I learned from your answers and I appreciate it but no I don't need to add anything in my web.config If I decided to have this design pattern.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Header Cache Expire - dynamic site and ad server clicks? I did some research on speeding up your php mysql site. We update new information on our site every 12 to 24 hours.
I found that Header Expire Cache Control in the browser helps speed up the site.
Here is my code:
Header("Cache-Control: must-revalidate");
$offset = 60 * 60 * 24 * 3;
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
Header($ExpStr);
I am wondering, how do I change this to 1 hour instead of 3 days, also --
How are my ads on our site getting effected with browser cache enabled? Does it still count impressions and clicks?
A: Just for the record, you can also use a string representation instead of adding seconds up:
Header("Cache-Control: must-revalidate");
$offset = strtotime('+42 hours'); // same as time() + 42 * 60 * 60
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", $offset) . " GMT";
Header($ExpStr);
A: Change $offset to:
$offset = 60 * 60; (60 seconds / minute * 60 minutes / hour) = 3600 seconds / hour = 1 hour
Generally ads are served off different servers and the requests for the ad content will have their own expiry headers. So whatever you change the cache settings to on your server's content won't affect the content loaded from the external ad servers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Set default syntax to different filetype in Sublime Text 2 How do I set a default filetype for a certain file extension in Sublime Text 2? Specifically I want to have *.cfg files default to having Ini syntax highlighting but I cannot seem to figure out how I could create this custom setting.
A: You can turn on syntax highlighting based on the contents of the file.
For example, my Makefiles regardless of their extension the first line as follows:
#-*-Makefile-*- vim:syntax=make
This is typical practice for other editors such as vim.
However, for this to work you need to modify the
Makefile.tmLanguage file.
*
*Find the file (for Sublime Text 3 in Ubuntu) at:
/opt/sublime_text/Packages/Makefile.sublime-package
Note, that is really a zip file. Copy it, rename with .zip at the end, and extract the Makefile.tmLanguage file from it.
*Edit the new Makefile.tmLanguage by adding the "firstLineMatch" key and string after the "fileTypes" section. In the example below, the last two lines are new (should be added by you). The <string> section holds the regular expression, that will enable syntax highlighting for the files that match the first line. This expression recognizes two patterns: "-*-Makefile-*-" and "vim:syntax=make".
...
<key>fileTypes</key>
<array>
<string>GNUmakefile</string>
<string>makefile</string>
<string>Makefile</string>
<string>OCamlMakefile</string>
<string>make</string>
</array>
<key>firstLineMatch</key>
<string>^#\s*-\*-Makefile-\*-|^#.*\s*vim:syntax=make</string>
*Place the modified Makefile.tmLanguage in the User settings directory:
~/.config/sublime-text-3/Packages/User/Makefile.tmLanguage
All the files matching the first line rule should turn the syntax highlighting on when opened.
A: In ST2 there's a package you can install called Default FileType which does just that.
More info here.
A: In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice].
Updated 2012-06-28: Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to Open all with current extension as... at the top of the menu.
Updated 2016-04-19: As of now, this also works for Sublime Text 3.
A: Go to a Packages/User, create (or edit) a .sublime-settings file named after the Syntax where you want to add the extensions, Ini.sublime-settings in your case, then write there something like this:
{
"extensions":["cfg"]
}
And then restart Sublime Text
A: The best solution for me turned out to be to used the ApplySyntax package.
The steps are as follows:
*
*Install the package via Package Control
*CTRL + SHIFT + P and enter ApplySyntax: Browse Syntaxes. Find your desired syntax here and note the exact line shown, e.g. I was looking to set it to Markdown from the Markdown Editing package, so for me the line was MarkdownEditing/syntaxes/Markdown.
*CTRL + SHIFT + P and enter ApplySyntax: Settings.
*On line "new_file_syntax": "XYZ", enter the line from Step 2.
See here for further documentation.
I found this to work better than the DefaultFileType package, because it isn't limited to just new files created by pressing CTRL + N and captured new tabs opened by clicking the empty space to the right of an open tab.
I hope is useful to someone 11 years after the original question was asked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "746"
}
|
Q: How to make a such animation of UItextView or TTTextView as shown in picture an App Shopper implement
As shown in picture:
there is a table item or a button "Read More..."
when click this button, the button animates to this piece of words' end to show all words up. As shown in picture 2
*
*Is it a UITextView?
*The "Button" is a UIButton or a Table Item?
*How to implement this animation?
A: I did something similar by simply having UILabels and UITextViews lined up vertically. For the button I use a transparent UIButton of type UIButtonTypeCustom. Then I change the frame & text of the labels / textviews (the one with the text, and the ones below it) in an animation block.
There is also a way to do this in a table view. There is an Apple sample code project with section headings that you can click to expand. But the section is still visible, so perhaps this is not the right approach for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there any difference between manually adding a DbSet or allowing the table to be automatically created? I have a type called TypeA and somewhere in TypeA there is a property of TypeB (which contains nothing other than an ID and String).
Using Entity Framework, I have created a DbSet of TypeA - public DbSet<TypeA>.
This creates the TypeB column in the database just fine - however, I now need to seed some data. As TypeB does not exist in the original DbContext, I am unable to seed data to it.
I therefore added public DbSet<TypeB> to my original DbContext and it didn't even detect a change/difference in the Database schema.
So, this got me wondering, and my question is, Is there any difference in creating a separate DbSet over one that is automatically created by a relation?
Sample Code
public class TypeA
{
public int id { get; set; }
public string name { get; set; }
public TypeB foo { get; set; }
}
public class TypeB
{
public int ID { get; set; }
public string name { get; set; }
}
A: Yes, there is a difference.
In design terms, the point of the DbSet class is to embody the Repository pattern:
Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.
Its purpose is to encapsulate CRUD for a given entity. In order to do this the repository can't limit itself to just one table. Sometimes it must work with an object tree in the DB.
In your case, having a DbSet for both types will give you a repository to directly access that entity. This will allow you to query directly for TypeB or directly create/update TypeB instances in the DB, rather than always having to always root your queries in TypeA.
Some of this depends on your associations, though. If you have a constraint on TypeB that requires a TypeA, then you can't create them without a TypeA. However you can still query for them directly.
You can still create or update TypeB instances without the DbSet<TypeB> - simply attach one to the TypeA instance and work against the the DbSet<TypeA>.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: c# Namespace already contains a definition for inherited class so how to add a constructor I am carefully treading into WCF attempting to follow tutorials and convert my ASMX project to a new WCF project and I've stumbled upon a mystery about coding of my constructor in WCF.
My ASMX webservice allowed me to have a constructor (see: same name, no return value):
namespace sdkTrimFileServiceASMX
{
public class FileService : System.Web.Services.WebService
{
Database db;
string g_EventSource = "CBMI-TrimBroker";
string g_EventLog = "Application";
public FileService()
{
try
{
if (!EventLog.SourceExists(g_EventSource))
EventLog.CreateEventSource(g_EventSource, g_EventLog);
}
catch (InvalidOperationException e)
{
e.ToString();
}
}
My attempt to convert this to a WCF service app gives this compiler complaint:
The namespace 'sdkTRIMFileServiceWCF' already contains a definition for 'FileService'
Here is the WCF code (beginning snippet):
namespace sdkTRIMFileServiceWCF
{
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class FileService : IFileService // err msg points to this line
{
Database db;
string g_EventSource = "CBMI-TrimBroker";
string g_EventLog = "Application";
public FileService()
{
try
{
if (!EventLog.SourceExists(g_EventSource))
EventLog.CreateEventSource(g_EventSource, g_EventLog);
}
catch (InvalidOperationException e)
{
e.ToString();
}
}
A: This isn't related to the existence of the constructor. I am fairly sure this is a copy/paste error- perform a search for the word "FileService" in any files in your application and you will find another class or a namespace declaration with that name (in the same namespace).
A: Some things you could do:
*
*do right mouse click > Find references on FileService.
*Try a full search (ctrl+f) and search for FileService.
*Check any partial classes for a second constructor.
*Try clean solution and then rebuild the solution, see if this makes
any difference.
*...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unable to get NSEnumerator to display next item in my array I am new to Objective-C and I have researched this online for weeks now. Almost every example is the same on every site and does not fully make it clear to me how to integrate it into my code for an Xcode 4 App.
The example seen everywhere is:
NSEnumerator* theEnum = [some_array objectEnumerator];
id obj; or id some_object = NULL;
while(obj = [theEnum nextObject]) {
//do something...
I think if I better understood what id some_object = NULL;/ id obj; represents I could figure it out on my own.
In my code I have three arrays. I want to be able to display one object in each array in a UILabel field every time the user clicks the Next button until all of them have been displayed.
NSArray1 = 1,2,3
NSArray2 = John, Jill, Josh
NSArray3 = boy, girl, boy
When the next button is pushed you would see 1, John and boy. The next time you would see 2, Jill and girl and finally 3, Josh and boy.
Below is basic example, not my actually code.
number = [[NSArray alloc] initWithObjects:@"1",@"2",@"3", nil];
name = [[NSArray alloc] initWithObjects:@"John",@"Jill",@"Josh", nil];
gender = [[NSArray alloc] initWithObjects:@"boy",@"girl",@"boy", nil];
NSEnumerator *enum = [number objectEnumerator];
id obj; (??What is this?? And how to connect to the statement below??)
while ((obj = [enumNumber nextObject])) {
self.numberItem.text = ??
self.nameItem.text = ??
self.genderItem.text = ??
Thanks
A: id obj is just the variable containing the current variable you're looking at. In this code, since your NSArrays all contain string, you could use NSString *obj instead.
An enumerator can only enumerate one collection at a time. If you want to loop through all three of them together, use a traditional for loop:
for(unsigned int i = 0; i < number.count; i++) {
self.numberItem.text = [number objectAtIndex:i];
self.nameItem.text = [name objectAtIndex:i];
self.genderItem.text = [gender objectAtIndex:i];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I speed-up the table reconstruction in MySQL when altering the schema? I have a relatively big MySQL InnoDB table (compressed), and I sometimes need to alter its schema (increasing column size or adding a field).
It takes around 1 hour for a 500 MB table with millions of rows, but the server doesn't seem to be very busy (CPU @5%, not much RAM used, and 2.5 MB/s as I/O).
The table is not used in production so there are no concurrent requests at the same time. There is only a primary index (on the first 5 columns) and one foreign key constraint.
Do you have any suggestion on how to speed-up the table alteration process?
A: Changing storage engine (to newer generation engines like TokuDB) seems the way to go, until InnoDB is "fixed".
A: Would be helpful to know the exact table and primary key/index definitions, and of lesser importance, the row count to the nearest million, although I would guess as the table is only 500mb it's probably less than 20 million rows. Also, your approach to changing the table - are you creating a new schema and inserting into it, or using a alter table etc.
I've had success in this area before with approaches like
*
*changing the index key composition, adding a unique key
*dropping the indexes first, then changing the table, then adding the indexes back. sometimes independent indexes can be a real performance killer if they are affected by the change.
*optimizing the table structure to remove unneeded or oversized columns
*separating out data (normally columns but you can vertically partition in some circumstances) that won't change from the core structure that might change, so you only churn a smaller part of your table
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Hibernate Criteria Transformers.aliasToBean is not populating correct values I am trying to create BO by joining my entity classes
Criteria criteria = session.createCriteria(Report.class,"r");
criteria
.createAlias("template", "t")
.createAlias("constituents", "rc")
.createAlias("rc.entity", "pe")
.createAlias("pe.model", "m")
.createAlias("pe.scenario", "s")
.setProjection(Projections.projectionList()
.add( Projections.property("r.Id"))
.add( Projections.property("t.Typ"))
.add( Projections.property("pe.bId"))
.add( Projections.property("m.model"))
.add( Projections.property("s.decay"))
).setMaxResults(100)
.addOrder(Order.asc("r.Id"))
.setResultTransformer(Transformers.aliasToBean(BO.class));
I am getting 100 empty BO i.e. all properties are null
My BO is as follows
public class BO implements Serializable {
private static final long serialVersionUID = 1L;
private int Id;
private String Typ;
private String bId;
private String model;
private String decay;
Getters and Setters
.....
When I remove the line aliasToBean and iterate over Object[] I could see the correct values fetched
Please guide me...
A: Try explicitly aliasing the ProjectionList items to match the field names in the bean, as follows:
Criteria criteria = session.createCriteria(Report.class,"r");
criteria
.createAlias("template", "t")
.createAlias("constituents", "rc")
.createAlias("rc.entity", "pe")
.createAlias("pe.model", "m")
.createAlias("pe.scenario", "s")
.setProjection(Projections.projectionList()
.add( Projections.property("r.Id"), "Id")
.add( Projections.property("t.Typ"), "Typ")
.add( Projections.property("pe.bId"), "bId")
.add( Projections.property("m.model"), "model")
.add( Projections.property("s.decay"), "decay")
).setMaxResults(100)
.addOrder(Order.asc("r.Id"))
.setResultTransformer(Transformers.aliasToBean(BO.class));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to pass console arguments to application in eclipse? I have the following line in a batch file.
java Client "127.0.0.1" 9876
It contains the name of my java class and two arguments. My application requires these arguments to run properly.
Is there any way to pass these arguments when running the application in eclipse? It would make debugging a lot easier. Of course I could resolve the problem by using the values of the arguments in the code but I'm curious.
A: Want to add something like, how to add multiple parameters.
*
*Right-click on your project.
*Debug > Debug Configurations
*Go to Arguments tab.
*Enter in your Program Arguments, each separated by a new line. (e.g 3 arguments in attached image)
*Click Apply or Debug
Hope it helps.
A: Instead of just hitting the "Run" icon, select the dropdown box next to it, and choose "Run Configurations". Find your application (or create a Run Configuration for it) and put the command line arguments in the "Arguments" tab. See the docs for more information. It should look like this:
A: From "Run" go to debug/run configurations. Click the tab called "Arguments". You can give the program arguments there.
A: Run configurations > Arguments tab. Just put "127.0.0.1" 9876 in the program arguments.
A: See the run configurations. You can specify arguments. You can even prompt the user for arguments, along with defaults:
${string_prompt:host:127.0.0.1} ${string_prompt:port:9876}
The first prompt is host, with default value 127.0.0.1 filled in. Second pop-up has the prmpt port, with 9876 filled in
A: *
*Right-click on your project.
*Go to Debug As > Debug Configurations or Run As > Run Configurations.
*Click the tab that says Arguments.
*Enter in your Program Arguments
*Click Apply or Debug
A: Run-> Run Configurations->Arguments->Enter your arguments separated by space->Apply->Run
Ensure that the right project name and it's main method are selected under "the Main" tab under run configurations
A: this work for me, in public static void main method.
public static void main(String argv[]) throws Exception {
int port_com = 2;
boolean debugMode = true;
int socket = 6789;
HasarMain hasarMain = new HasarMain();
// Check if a command line argument exists
if(argv.length != 3){
System.out.println("Missing, Port - socket - debugMode!");
System.exit(0);
}
port_com = Integer.parseInt(argv[0]);
socket = Integer.parseInt(argv[1]);
debugMode = Boolean.parseBoolean(argv[2]);
Run-> Run Configurations->Arguments->Enter your arguments separated by tab->
${string_prompt:argv:"2" "6789" "true"}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
}
|
Q: Looking for code sample for a Grouped UITableView that is populated from an an NSMutableArray of objects (NOT FROM CORE DATA and NSFetchedResults) Looking for code sample for a Grouped UITableView that is populated from an an NSMutableArray of objects (NOT FROM CORE DATA and NSFetchedResults).
Consider a rolodex of people contact information and the UITableView is grouped by the State where the people are from. Again, these people objects are stored in an nsmutablearray.
Does anyone have an example at the ready?
Thanks!
A: you might find some examples here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Setting an Error Message located in language file In a form I have a callback function that checks if a number is_available.
If it returns TRUE it shows an error message.
The callback is working but it displays : lang:shortcodes.not_unique instead of the content given in a separate file.
I can't figure out what is wrong and didn't find about that in the user guide.
Thank you for your help.
public function __construct()
{
parent::__construct();
// Load all the required classes
$this->load->model('shortcodes_m');
$this->load->library('form_validation');
$this->lang->load('shortcodes');
// Set the validation rules
$this->item_validation_rules = array(
array(
'field' => 'number',
'label' => 'lang:shortcodes.number',
'rules' => 'trim|max_length[100]|required|numeric'
),
array(
'field' => 'name',
'label' => 'lang:shortcodes.name',
'rules' => 'trim|max_length[100]|required|callback_shortcodes_check'
)
);
}
public function shortcodes_check($str)
{
if($this->shortcodes_m->is_available($str) == TRUE)
{
$this->form_validation->set_message('shortcodes_check','lang:shortcodes.not_unique');
return FALSE;
}
else
{
return TRUE;
}
}
A: You need to fetch the line from the language file. The docs don't make any mention of being able to use field name translation with the set_message() method. Use:
$this->lang->line('not_unique');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Stream video from ffmpeg and capture with OpenCV I have a video stream coming in on rtp to ffmpeg and I want to pipe this to my OpenCV tools for live streaming processing. The rtp linkage is working because I am able to send the incoming data to a file and play it (or play if via ffplay). My OpenCV implementation is functional as well because I am able to capture video from a file and also a webcam.
The problem is the streaming to OpenCV. I have heard that this may be done using a named pipe. First I could stream the ffmpeg output to the pipe and then have OpenCV open this pipe and begin processing.
What I've tried:
I make a named-pipe in my cygwin bash by:
$ mkfifo stream_pipe
Next I use my ffmpeg command to pull the stream from rtp and send it to the pipe:
$ ffmpeg -f avi -i rtp://xxx.xxx.xxx.xxx:1234 -f avi -y out.avi > stream_pipe
I am not sure if this is the right way to go about sending the stream to the named pipe but it seems to be accepting the command and work because of the output from ffmpeg gives me bitrates, fps, and such.
Next I use the named pipe in my OpenCV capture function:
$ ./cvcap.exe stream_pipe
where the code for cvcap.cpp boils down to this:
cv::VideoCapture *pIns = new cv::VideoCapture(argv[1]);
The program seems to hang when reaching this one line, so, I am wondering if this is the right way of going about this. I have never used named pipes before and I am not sure if this is the correct usage. In addition, I don't know if I need to handle the named pipe differently in OpenCV--change code around to accept this kind of input. Like I said, my code already accepts files and camera inputs, I am just hung up on a stream coming in. I have only heard that named pipes can be used for OpenCV--I haven't seen any actual code or commands!
Any help or insights are appreciated!
UPDATE :
I believe named pipes may not be working in the way I intended. As seen on this cygwin forum post:
The problem is that Cygwin's implementation of fifos is very buggy. I wouldn't recommend using fifos for anything but the simplest of applications.
I may need to find another way to do this. I have tried to pipe the ffmpeg output into a normal file and then have OpenCV read it at the same time. This works to some extent, but I imagine in can be dangerous to read and write from a file concurrently--who knows what would happen!
A: hope it's not too late to answer, but I have tried the same thing some time ago, and here is how I did it.
The video-decoding backend for OpenCV is actually ffmpeg, so all its facitilites are available in OpenCV as well. Not all the interface is exposed, and that adds some difficulties, but you can send the rtp stream address to OpenCV.
cap.open("rtp://xxx.xxx.xxx.xxx:1234");
Important: OpenCV is not able to access password-protected rtp streams. To do that, you would need to provide the username and the password, there is no API exposed for it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Question about java.util.Calendar I'm trying to understand the behavior with the following code.
My local time zone is UTC -7 (Arizona).
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE,40);
cal.set(Calendar.AM_PM,Calendar.PM);
System.out.println("1 UTC -4 Hour:" + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("1 UTC -4 Day:" + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("1 UTC -7 Time Stamp:" + cal.getTime().toString());
cal.set(Calendar.HOUR,12);
System.out.println("2 UTC -4 Hour:" + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("2 UTC -4 Day:" + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("2 UTC -7 Time Stamp:" + cal.getTime().toString());
cal.setTimeZone(TimeZone.getTimeZone("America/New_York")); //set time zone to UTC -4
System.out.println("3 UTC -4 Hour:" + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("3 UTC -4 Day:" + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("3 UTC -7 Time Stamp:" + cal.getTime().toString());
cal.set(Calendar.HOUR,12);
System.out.println("4 UTC -4 Hour:" + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("4 UTC -4 Day:" + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("4 UTC -7 Time Stamp:" + cal.getTime().toString());
It generates this output:
1 UTC -4 Hour:12
1 UTC -4 Day:27
1 UTC -7 Time Stamp:Tue Sep 27 12:40:37 MST 2011
2 UTC -4 Hour:0
2 UTC -4 Day:28
2 UTC -7 Time Stamp:Wed Sep 28 00:40:37 MST 2011
3 UTC -4 Hour:3
3 UTC -4 Day:28
3 UTC -7 Time Stamp:Wed Sep 28 00:40:37 MST 2011
4 UTC -4 Hour:12
4 UTC -4 Day:28
4 UTC -7 Time Stamp:Wed Sep 28 09:40:37 MST 2011
What I don't understand is why the first cal.set(Calendar.HOUR,12) causes the date to flip to the next day. It makes sense that using add() on one value would cause other values to be adjusted, but it doesn't make sense for set() to do that as well.
Is there some way to do an absolute set() where all other values are preserved?
A: You're setting "HOUR" rather than "HOUR_OF_DAY". It's therefore setting it to be "12 hours after the start of the afternoon" - i.e. midnight at the end of that day, so the start of the next. Think of it as saying, "I'm meant to be PM, so setting the hour is midday + hours * 12"
Personally I think that's still a bit odd behaviour, but I'd stick to using HOUR_OF_DAY instead... or preferrably, using Joda Time in the first place.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: With an Azure project, when managing multiple service configurations, where are the current configuration choice saved I'm wondering about this because i'd like to find a way to create a post-build event that is different whether I'm trying to compile and run in the emulator or wheter I'm compiling and publishing to the cloud.
I don't know if there is an easier way, but I thought that If I could find where the current setting (cloud or local) is saved I could branch my post-build event based on that
thx
A: It is in a variable TargetProfile so you should be able to do something similar to this (which is for after publish, but you get the idea):
<Target Name="AfterPublish">
<ItemGroup Condition="'$(TargetProfile)' == 'Cloud'">
<-- Do you thing here -->
</ItemGroup>
</Target>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C++ Memory/Input Problem I'm trying to create a small program in c++ where the user puts in multiple lines and the program outputs all the lines of after a EOT command is given (ctrl-d)
But i'm getting some error's when executing the program. I think i did a lot wrong.
(This is an hypothetical exersise, i don't want to use any vectors, lists etc., and only want include iostream.
#include <iostream>
using namespace std;
int main()
{
//Temp input string
string input_string;
//Array with input lines
string lines[1];
//Counter for input lines
size_t line_counter = 0;
//Input terminated checker
bool breaker = false;
//Eternal loop
for(;;){
//Get line, store in input_string and set breaker if input is terminated
if(getline(cin, input_string).eof()) breaker = true;
//Create a new temp array to hold our data
string temp_lines[line_counter+1];
for(size_t counter = 0; counter != line_counter; ++counter){
//And use a for loop to get data from our last array with data
temp_lines[counter] = lines[counter];
}
//Create a second array and repeat process
//because c++ doesn't allow us to create dynamic array's
string lines[line_counter+1];
for(size_t counter = 0; counter != line_counter; ++counter){
lines[counter] = temp_lines[counter];
}
//store input in the new array
lines[line_counter] = input_string;
//increase the input counter
++line_counter;
//if breaker is set terminate loop but output lines first
if(breaker){
//for each input
for(size_t anothercounter = 0; anothercounter != line_counter; ++anothercounter){
//output the inputed line
cout << anothercounter << ": " << lines[anothercounter] << "\n";
}
//break out of eternal for loop
break;
}
}
}
A: For one thing I can see wrong is you cannot do this
//Create a new temp array to hold our data
string temp_lines[line_counter+1];
as line_counter is a variable, and array size must be a compile time time constant. Otherwise use new to allocate memory for the array.
Also it would help a lot in answering your question if you also post the errors you are getting.
A: Try something like this (untested, edited in notepad):
#include <iostream>
using namespace std;
int main()
{
//Temp input string
string input_string;
//Array with input lines
string * lines = 0;
// Array used for temporary storage
string * temp_lines = 0;
//Counter for input lines
size_t line_counter = 0;
//Input terminated checker
bool breaker = false;
//Eternal loop
for(;;){
//Get line, store in input_string and set breaker if input is terminated
if(getline(cin, input_string).eof()) breaker = true;
// Copy all lines from original array to temporary array, to enable resizing the original
temp_lines = new string[line_counter+1];
for(size_t tmp = 0; tmp < line_counter; tmp++) temp_lines[tmp] = lines[tmp];
temp_lines[line_counter] = input_string;
delete [] lines;
lines = new string[line_counter+1];
for(size_t tmp = 0; tmp <= line_counter; tmp++) lines[tmp] = temp_lines[tmp];
delete [] temp_lines;
//increase the input counter
++line_counter;
//if breaker is set terminate loop
if(breaker) break;
}
//for each input
for(size_t anothercounter = 0; anothercounter != line_counter; ++anothercounter){
//output the inputed line
cout << anothercounter << ": " << lines[anothercounter] << "\n";
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use Eval() with a column name that contains a dot(.)? In my SQL Server table there is a column slno. (yes, it contains a dot) that is working fine in SQL Server. However, <%#Eval("slno.")%> is giving an error:
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'slno'.
How can this be solved? I can't change column name in database: I am getting data from stored procedure so I cannot modify it.
<ItemTemplate> <%#Eval("slno.") %> </ItemTemplate>
A: use
<%# ((DataRowView)Container.DataItem)["slno."] %>
Alternatively use
<%# DataBinder.Eval (Container.DataItem, "slno.") %>
For MSDN reference see http://msdn.microsoft.com/en-us/library/4hx47hfe.aspx
EDIT - Another option:
<%# DataBinder.GetPropertyValue(Container.DataItem, "slno.") %>
EDIT 2 - as per comments:
AFAIK Eval handles the string as an expression which it evaluates using some rules - these rules have special handling for the dot...
GetPropertyValue OTOH does not apply those rules (which means it is NOT a full replacement for Eval AFAIK) thus having the ability to handle cases where the dot handling of Eval leads to problems (like in this case).
A: I Used DataBinder.GetPropertyValue() as it follows:
DataBinder.GetPropertyValue(Container.DataItem, "Name of my Fields with(Parentheses)")
and Worked like a Charm on a ASP.NET VB Project.
A: You can use SELECT AS in your SELECT SQL statement.
SELECT Tabl1.slno. AS slno_no_dot from Table1
than
<ItemTemplate> <%#Eval("slno_no_dot") %> </ItemTemplate>
A: I recently ran into the same issue in a self-written customcontrol. In some cases I need to use the syntax "object.property" and sometimes I need to use "columnname.with.dots". Finally I solved it by using a Try-Catch block:
object value;
try
{
// Try "Object.Property" approach...
value = DataBinder.Eval(container.DataItem, Fieldname);
}
catch
{
// fallback for columns containing dots or other special characters
value = DataBinder.GetPropertyValue(container.DataItem, Fieldname);
}
A: Do not use DataBinder.eval(); eval() can not read field after dot(.).
Instead, use DataBinder.GetPropertyValue()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: C# shift two dimension array fast method I have a 2D string array in C# and I need to shift that array to left in one dimension
how can I do that in efficient way
I dont want use nested for and i want an algurithm in O(n) not O(n2)
for (int i = 50; i < 300; i++)
{
for (int j = 0; j < 300; j++)
{
numbers[i-50, j] = numbers[i, j];
}
}
A: The most efficient way would be to not shift it at all, but instead change how you access the array. For example, keep an offset that tells you where in the dimension the first column is.
A: If you want to shift large amounts of data around quickly, use Array.Copy rather than a loop that copies individual characters.
If you swap to a byte array and use Array.Copy or Buffer.BlockCopy you will probably improve the performance a bit more (but if you have to convert to/from character arrays you may lose everything you've gained).
(edit: Now that you've posted example code): If you use references to the array rows then you may be able to shift the references rather than having to move the data itself. Any you can still shift the references using Array.Copy)
But if you change your approach so you don't need to shift the data, you'll gain considerably better performance - not doing the work at all if you can avoid it is always faster! Chances are you can wrap the data in an accessor layer that keeps track of how much the data has been shifted and modifies your indexes to return the data you are after. (This will slightly slow down access to the data, but saves you shifting the data, so may result in a net win - depending on how much you access relative to how much you shift)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Why do "single statement" blocks require not using semi-colons? I'm usually a C# programmer and going to Delphi has been full of "interesting" discoveries. The one that baffles me the most is single statements in Delphi.
Example C# block
if(x)
Foo();
else
Bar();
Example Delphi block:
if x then
Foo() //note missing semicolon
else
Bar();
What exactly was their purpose for requiring that semi-colon to not be there? Is there a historical reason dating back to Pascal?
A: There is a difference between semi-colons in Pascal and in C and their derivatives.
*
*In C the semi-colon is a statement terminator.
*In Pascal the semi-colon is a statement separator.
Wikipedia explains the implications of this:
This difference manifests itself primarily in two situations:
*
*there can never be a semicolon directly before else in Pascal
whereas it is mandatory in C (unless a block statement is used)
*the last statement before an end is not required to be followed by
a semicolon
A superfluous semicolon can be put on the last line before end,
thereby formally inserting an empty statement.
A: The real reason ; is not allowed in front of a if-then else is to avoid ambiguity with its lesser known cousin, the case-of else.
Observe the following snippet:
case enum1 of
male: writeln('hallo');
female: if a=1 then writeln('oops'); <<-- watch this space.
else writeln('neither')
end;
Because there is a ; after the 'oops' line, the else belongs to the case statement and not the if.
If you leave out the ; then the else belongs to the if a=1.
That's why a ; is not allowed in front of an if else.
Personally having worked in Pascal for some 20-odd years, I still put ; in front of else, because I put ; in C-style. And the compiler still bugs me, you'd think the compiler would have learned by now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Left function in c# what is the alternative for Left function in c#
i have this in
Left(fac.GetCachedValue("Auto Print Clinical Warnings").ToLower + " ", 1) == "y");
A: It's the Substring method of String, with the first argument set to 0.
myString.Substring(0,1);
[The following was added by Almo; see Justin J Stark's comment. —Peter O.]
Warning:
If the string's length is less than the number of characters you're taking, you'll get an ArgumentOutOfRangeException.
A: Just write what you really wanted to know:
fac.GetCachedValue("Auto Print Clinical Warnings").ToLower().StartsWith("y")
It's much simpler than anything with substring.
A: It sounds like you're asking about a function
string Left(string s, int left)
that will return the leftmost left characters of the string s. In that case you can just use String.Substring. You can write this as an extension method:
public static class StringExtensions
{
public static string Left(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
maxLength = Math.Abs(maxLength);
return ( value.Length <= maxLength
? value
: value.Substring(0, maxLength)
);
}
}
and use it like so:
string left = s.Left(number);
For your specific example:
string s = fac.GetCachedValue("Auto Print Clinical Warnings").ToLower() + " ";
string left = s.Substring(0, 1);
A: use substring function:
yourString.Substring(0, length);
A: var value = fac.GetCachedValue("Auto Print Clinical Warnings")
// 0 = Start at the first character
// 1 = The length of the string to grab
if (value.ToLower().SubString(0, 1) == "y")
{
// Do your stuff.
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "50"
}
|
Q: javascript getting setting deleteing cookies I am having trouble setting and deleting cookies in php Ive got no problem.. in javascript eh.. lots I know this question is everywhere but all the answers I come across seem to bring me the same fate so I have no idea whats going on.. this is what I have currently.
SetCookie("username",ztsUser,14,'/', '');
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
the error:
expires.toGMTString is not a function
The whole lot of cookie functions I have.. is:
var today = new Date();
var expiry = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) { endstr = document.cookie.length; }
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal (j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function DeleteCookie (name,path,domain) {
if (GetCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
if anyone knows a better method Im all ears.. but this is what I got at the moment, I need to set, update, delete, get the value of.. cookies
A: toGMTString has been deprecated. Try toUTCString instead:
function SetCookie (name,value,expires,path,domain,secure) {
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toUTCString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
You're also passing a number (14) when the function expects a Date (expires.toUTCString):
SetCookie("username", ztsUser, 14, '/', '');
What is 14 intended to be? 14 days? Assuming that, you can add this at the top of the function to support both numbers and dates:
if ('number' === typeof expires) {
expires = new Date(new Date().getTime() + expires * 86400000);
}
86400000 is the number of milliseconds in a day -- 24 * 60 * 60 * 1000.
A: There are already a number of great libraries for handling cookies in JS. Why not use one of them? Just go to your favorite search engine and enter "javascript cookie library" to find one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Global named event equivalent in Unix What is the global named event object equivalent in Unix? I need to create a named event-like object in unix so that another process can set it
pseudocode in Win32:
HANDLE hEvent=CreateEvent(...,"Global\\CSAPP");
while(1)
{
WaitForSingleObject(hEvent);
...
}
In another process:
HANDLE hEvent=OpenEvent(...,"Global\\CSAPP");
SetEvent(hEvent);
A: You are probably looking for a named semaphore.
int initial = 0;
sem_t *sem = sem_open("/global_name", O_CREAT, 0644, initial);
/* Down ("Wait"). */
sem_wait(sem);
/* Up ("Set") . */
sem_post(sem);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I create an AVAsset with a UIImage captured from a camera? I am a newbie trying to capture camera video images using AVFoundation and
want to render the captured frames without using AVCaptureVideoPreviewLayer. I
want a slider control to be able to slow down or speed up the rate of display of
camera images.
Using other peoples code as examples, I can capture images and using an NSTimer,
with my slider control can define on the fly how often to display them, but I
can't convert the image to something I can display. I want to move these
images into a UIView or UIImageView and render them in the timer Fire function.
I have looked at Apples AVCam app, (which uses an AVCaptureVideoPreviewLayer)
but because it has its own built in AVCaptureSession, I can't adjust how often the
images are displayed. (well, you can adjust the preview layer frame rate but
that can't be done on the fly)
I have looked at the AVFoundation programming guide, which talks about AVAssets
and AVPlayer, etc. but I can't see how a camera image can be turned into an
AVAsset. When I look at the AVFoundation guide, and other demos which show how
to define an AVAsset, it only gives me choices of using http stream data to
create the asset, or a url to define an asset using an existing file. I can't
figure out how to make my captured UIImage into an AVAsset, in which case I guess
I could use an AVPlayer, AVPlayerItems and AVAssetTracks to show the image with
an observeValueForKeyPath function checking status and doing [myPlayer play].
(I also studied the WWDC session 405 "Exploring AV Foundation" to see how that
is done)
I have tried similar code as in the WWDC Session 409 "Using the Camera on iPhone."
Like that myCone demo, I can set up the device, the input, the capture session,
the output, the setting up of a callback function to a CMSampleBuffer, and I
can collect UIImages and size them, etc. At this point I want to send that image
to a UIView or UIimageView. The session 409 just talks about doing it with
CFShow(sampleBuffer). This wasn't explained, and I guess its just assuming a
knowledge of Core Foundation I don't yet have. I think I am turning the captured
output in the sample buffer into a UIImage, but I can't figure out how to render
it. I created an IBOutlet UIImageView in my nib file, but when I try to stuff
the image into that view, nothing gets displayed. Do I need an AVPlayerLayer?
I have looked at the UIImagePickerViewController as an alternate method of
controlling how often I display captured camera images, and I dont see that I
can change the time on the fly to display images using that controller either.
So, as you can see, I am learning this stuff with the Apple development forum and
their documentation, the WWDC videos, and various websites such as
stackoverflow.com but have yet to see any examples of doing camera to screen
without using AVCaptureVideoPreviewLayer, UIImagePickderViewController or by
using an AVAsset that isnt already a file or http stream.
Can anybody make a suggestion? Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ face detection/recognition implementations I'd have thought that google could answer this question, but I've not had much luck.
Does anyone know of any open source C++ implementations of any face detection algorithms other than the Viola-Jones (boosted cascades of Haar-like features) method?
Also, does there exist an open source C++ implementation of Fisherfaces anywhere?
Thanks.
A: This post gets some attention, so I'd like to update it. I've contributed the face recognition library I wrote to OpenCV, which includes Eigenfaces, Fisherfaces and Local Binary Patterns Histograms at time of writing this. So OpenCV 2.4.2 now comes with everything to get started, see the very detailed documentation:
*
*http://docs.opencv.org/trunk/modules/contrib/doc/facerec/
Now the original answer.
I am the author of the article linked in Kevin's post. Please note that you need to find the eigenvalues of the non-symmetric matrix S_{W}^{-1} S_{B} for the Fisherfaces, I didn't explicitly mention it in my blog. OpenCV only has a solver for symmetric matrices in its current version; since eigenvalues and singular values aren't equivalent for non-symmetric matrices you can't use a SVD either. For my project I have adapted the JAMA solver to C++ for solving the eigenvalue problem for non-symmetric matrices, so there's no need to use an external library for it. The CMakeLists.txt is configured, so Eigen can be used as well, so you have the choice.
Now I've finally found some minutes to implement the Fisherfaces method with the OpenCV2 C++ API and pushed the code into my github account at:
*
*https://github.com/bytefish/opencv/blob/master/lda
The main.cpp shows you how to use the Fisherfaces class and how to use the Linear Discriminant Analysis with the same example as on: http://www.bytefish.de/wiki/pca_lda_with_gnu_octave. It comes as a CMake project, so compiling is as easy as typing:
philipp@mango:~/some/dir$ mkdir build; cd build
philipp@mango:~/some/dir/build$ cmake ..
philipp@mango:~/some/dir/build$ make
philipp@mango:~/some/dir/build$ ./lda
I don't know if it's the preferred Stackoverflow way to post code in the answer, but I think it's a bit too long to post.
Please note two things. (1) I read the images from a CSV file (just like this one), you don't have to care about the order of the labels. (2) I store the eigenvectors by column, while the PCA in OpenCV stores them by row. It's just a matter of personal taste to do so, but I've never seen that for any other solver and so I decided to store them by column.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Arithmetic operation within string concatenation without parenthesis causes strange result Consider the following line of code:
<?php
$x = 10;
$y = 7;
echo '10 - 7 = '.$x-$y;
?>
The output of that is 3, which is the expected result of the calculation $x-$y. However, the expected output is:
10 - 7 = 3
My question therefore is, what happened to the string that I'm concatenating with the calculation? I know that in order to produce the result I expected, I need to enclose the arithmetic operation in parenthesis:
<?php
$x = 10;
$y = 7;
echo '10 - 7 = '.($x-$y);
?>
outputs
10 - 7 = 3
But since PHP does not complain about the original code, I'm left wondering what the logic behind the produced output in that case is? Where did the string go? If anyone can explain it or point me to a location in the PHP manual where it is explained, I'd be grateful.
A: Your string '10 - 7 = ' is being concatenated with $x. Then that is being interpreted as an int which results in 10 and then 7 is subtracted, resulting in 3.
For more explanation, try this:
echo (int) ('10 - 7 = ' . 10); // Prints "10"
More information on string to number conversion can be found at http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion
If the string starts with valid numeric data, this will be the value used
A: In this code:
echo '10 - 7 = '.$x-$y;
The concatenation takes precedence, so what you're left with is this:
echo '10 - 7 = 10'-$y;
Because this is trying to perform integer subtraction with a string, the string is converted to an integer first, so you're left with something like this:
echo (int)'10 - 7 = 10'-$y;
The integer value of that string is 10, so the resulting arithmetic looks like this:
echo 10-$y;
Because $y is 7, and 10 - 7 = 3, the result being echoed is 3.
A: . and - have the same precedence, so PHP is reinterpreting '10 - 7 = 10' as a number, giving 10, and subtracting 7 gives 3.
A: PHP runs operations in the order defined here ; https://www.php.net/manual/en/language.operators.precedence.php
Take a look at this example ;
$session_period = 30;
new \DateTime('now -' . $session_period+1 . ' minutes');
Beware! This will NOT give you the time 31 minutes ago.
In this case PHP just interprets starting from the leftmost part of an expression so this simple-looking expression returns the wrong result;
Because ;
*
*'now -' . $session_period => 'now -30'
*then PHP will cast the string to 0 and add 1 to that => 1
*and 1 . ' minutes' => '1 minutes'
That's why the expression above will give you the result of
new \DateTime('1 minutes')
To avoid this kind of confusion, use () like this ;
new \DateTime('now -' . ($session_period+1) . ' minutes');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Concatenation function: splitting and merging cells Assuming column A23 (#) is 22, B23 (Last name) is Danielle, C22(middle name), D22 (last name) is Anderson.
This example has no middle name.
By using the =CON
I want a combination of the first letter in the student’s first name, the first letter in their middle name and the first 6 letters of their last name. If the student does not have a middle name, the number in the A column and corresponding row should be used.
If the student’s last name is shorter than 6 letters, their full last name should be used.
A: =left(B23,1) & if(C22<>"",left(C22,1),A23) & left(D22,6)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sql subquery syntax asp.net I am trying to excute this sql query
Dim str As String = "UPDATE table1 SET " & _
"number = '" & strc & "'," & _
"code = '" & "123" & "'," & _
"line= '" & dd1.text & "'," & _
"sellr = '" & txtrun.text & "'," & _
"endu= '" & txtex1.value+txtex2.value & "'" & _
"WHERE number IN (select table1.number" & _
"FROM table1 INNER JOIN table2 ON table1.number = table2.number" & _
"WHERE ((table1.username)='" & session("username") & "' AND (table1.pass)='" & session("pass") & "' AND (table2.sellnum)='" & session("sellnum") & "'));"
there is a Syntax error in query expression and this is te first time I am using nested subquery
all the field are getting String values
So if someone can tell me what is the right approach to write this query I will be very grateful
A: You're missing spaces after table1.number and table2.number fields in the subquery.
I don't know where you're using this query, but you might want to read about SQL injection. When you stick strings together to build SQL, your code may be vulnerable to malicious users who put SQL code into the fields of your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Long click on rectangle I created a view with rectangles which are clickable using the method onTouchEvent (using ACTION_DOWN motion). I want to enable a long click on the rectangle which open a dialog, and I tried to do it using ACTION_UP, but then the dialog is presented only after I release the finger. How can I do it in the same way that OnLongClickListener of buttons do?
A: Set the onLongClickListener:
http://developer.android.com/reference/android/view/View.html#setOnLongClickListener(android.view.View.OnLongClickListener)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iPhone - is CGContextSetStrokeColorWithColor not creating wanted color? I am having some weird troubles with drawing some lines in an application.
My drawRect is using
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:57 green:172 blue:255 alpha:1].CGColor]);
CGContextSetAlpha(context, 0.8);
CGContextSetLineWidth(context, POLYLINE_WIDTH);
The color that is supposed to be shown is something like this. However I am getting a dark grey color, does anyone know why this color could be getting skewed?
A: Try
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:57 / 255 green:172 / 255 blue:255 / 255 alpha:1].CGColor]);
These functions are expecting a number from 0-1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it valid to give a style element an ID? It says here that it is not within HTML4, though I don't really see where that's spelled out in the text.
From what I can tell, based on this, it is ok to do so in HTML5 but I'm not entirely sure (assuming style is an HTML element?)
I am using this to rotate out a stylesheet and want it to be as valid as possible according to HTML5 specs, so wondering if I should rewrite it with a data-* element.
A: +1 Interesting question!
Instead of using a style block, you should consider linking (link) to your stylesheets and then switch them out by referencing an id or a class.
That said, title is perfectly acceptable for a style tag in HTML5. You can use this as a hook for your stylesheet switching.
http://www.w3.org/TR/html5/semantics.html#the-style-element
Fyi... this validates
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<style title="whatever"></style>
</head>
<body>
Test body
</body>
</html>
http://validator.w3.org/#validate_by_input+with_options
A: I've just put the following code into the W3C validator and it has no errors :)
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<style id="test"></style>
</head>
<body>
Test body
</body>
</html>
I think the W3C Validator is a good resource for this type of thing, it is marked as experimental but that's because the standard is yet to be be finalised.
A: It is not valid in HTML4 (as per the spec) and data-* attributes are not either. That is, the document will not validate against the Doctype spec if you use these attributes.
Regardless of whether the document validates or not, browsers will ignore elements that they do not recognize.
Style tags are DOM elements like any other tag, so you can add any attributes you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: how to get and auto enter current date in sqlite db in java? I want to automatically enter the date time of the data into the database table. I am using the Date field and used timeEntry=DATE('NOW') but when I did a query, the output is "DATE('NOW') instead of the time.
Can anyone kindly help me out ? Thanks.
A: If you are inputting the value of timeEntry via ContentValues be aware that these values are properly sanitized resulting in timeEntry being assigned a TEXT value & not the result of the function you are passing.
A: First of all - SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
*
*TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
*REAL as Julian day numbers, the number of days since noon in
Greenwich on November 24, 4714 B.C. according to the proleptic
Gregorian calendar.
*INTEGER as Unix Time, the number of seconds since 1970-01-01
00:00:00 UTC.
SQLite supports five date and time functions as follows:
*
*date(timestring, modifier, modifier, ...)
*time(timestring, modifier, modifier, ...)
*datetime(timestring, modifier, modifier, ...)
*julianday(timestring, modifier, modifier, ...)
*strftime(format, timestring, modifier, modifier, ...)
You can replace timestring with 'now' to get the current datetime value.
For more information please see SQLite date and time functions
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: img.onerror does not seem to work for IE8 I am trying to load an image from a url to check internet connectivity. When no internet connection, it should display a dojo warning dialog. This works for Firefox but does not for IE8.
Following is the code snippet:
var img = new Image();
img.src = userGuideUrl1_img + '?' + (new Date).getTime();
img.onload = function() {
window.open(userGuideUrl1);
}
img.onerror = function() {
dojo.addOnLoad(warningDialogFunc);
}
Here warningDialogFunc is a dojo object. Any thoughts?
Thanks
A: Could it be that the page is already loaded by the time the img.onerror handler is executed, and IE doesn't rexecute the function for the dojo.addOnLoad(warningDialogFunc)?
Try changing
img.onerror = function() {
dojo.addOnLoad(warningDialogFunc);
}
to simply:
img.onerror = function() {
warningDialogFunc();
}
A: You have to set up the handler before you set the source of image, when you change the src attribute, IE will try to download the image and trigger the events.
var img = new Image();
img.onload = function() {
window.open(userGuideUrl1);
}
img.onerror = function() {
dojo.addOnLoad(warningDialogFunc);
}
img.src = userGuideUrl1_img + '?' + (new Date).getTime(); // Trigger image download and the handlers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Need iPhone card flip effect , can't figure out how to do it I'm writing a card game and need a animation to flip them over from one side to the other along the y axses. What would be the easiest way to do this? Is there any good tutors?
This is what I did:
Found some sample code for using UITransitionView. But it comes up as undeclared on my sdk, and I found out this was undocumented.
Looked into OpenGL, seems to complicated.
Any help would be GREAT!
Ted
A: Here is some code that I used in a blackjack app tutorial I went through:
-(void) flipCard {
[UIView beginAnimations:@"Flip Top Card" context:nil];
[UIView setAnimationDidStopSelector:@selector(flipCardDone)];
[UIView setAnimationDuration:1];
[UIView setAnimationDelegate:self];
[UIView setAnimationRepeatCount:0];
[UIView setAnimationRepeatAutoreverses:NO];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut ];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:topCard cache:YES];
topCard.image = [UIImage imageNamed:@"back.png"]; //begin
topCard.image = [UIImage imageNamed:currentName]; //end
[UIView commitAnimations];
}
-(void) flipCardDone {
topCard.hidden = YES;
nextCardToFlip.hidden = NO; // bad var name, nextCardToFlip ONLY appears to flip.
}
I hope it helps you :)
A: The simplest way to do this would be to use UIView transitions, or CATransitions depending on what exactly you're trying to accomplish.
Documentation for the UIView animation can be found here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Will everything work the same if I cut and paste my .cpp to the bottom of my .h? I have a very simple class and I'd like to consolidate it to a single .h file. Will everything work the same if I cut and paste the guts of my .cpp to the bottom of my .h?
In particular, there are static member variable initializations int MyClass::myStaticVar = 0; outside of any class definition at the top of the .cpp, and following that, there are static member function implementations void MyClass::myStaticMethod() {...}. Some non-static member functions are already being implemented in the .h, not the .cpp. So you can see there are some nuances here that I'd like to clarify.
Edit So far, what I'm getting is:
This is naughty, but it will work if you only #include the .h once.
It breaks the convention and doesn't really work like a .h so it might
as well be named .doofus.
Now, for example, look at the TUIO C++ bindings. A lot of the classes consist of one .h file, no cpp (TuioPoint.h, TuioCursor.h, TuioObject.h, etc). I don't think this is so bad...
A: If you're left with a single cpp file in the entire project, then it will work (but it's bad practice). If you have two cpp files that both include that header, you're breaking the one definition rule, and you (should) get linker errors.
You can do this if (A) All the functions are templates (in fact, you must in this case), or (B) all the functions are marked as inline.
[Edit]
The reason you aren't already having problems is a function defined in the class definition is automatically marked as inline. Thus: no problems. However, if the function is defined outside of the class definition, it should be in a cpp file. Also, static members should always be in a cpp file.
[Edit2] The reason non-inline, non-template functions and File scope varaibles (globals and static members) should always be in a cpp file, is that when the compiler finds that line of code, it creates the function/variable right there. Obviously, it must be created once to be used. Why not in a header file? Because then if the header is included in two cpp files, it will be created in two places (I have hpp files at work that are literally included in several thousand cpp files). C++ has a "one-definition rule" where each function/object can only be defined/created once, to prevent this obvious error:
int MyClass::myStaticVar = 0;
int MyClass::myStaticVar = 7;
Which would it use? You've just created two variables with the same name! So this isn't allowed, even if they were exactly the same, (except for inline/template). Each cpp file is compiled once and only once (unless for some oddball reason it's included from something else), which prevents accidental violations of the one-definition rule.
Also, hpp files are for declarations, and cpp files are for definitions/instantiations.
A: what good would the .h file be anymore? you can't have multiple .cpp files #include this .h file. And if this .h is only included by a single .cpp, then why do you need the .h file in the first place - just put everything in the .cpp.
A: In addition to Mooings answer you might want to consider the compile/link process for a while.
*
*The compiler compiles the .cpp files, not the .h files (by convention).
This has the consequence that for each .cpp file you need the definitions for the classes you reference in order to create instructions for the code in the .cpp. The .h files provides that.
What you do not want is identical pieces of code being duplicated across your program, which would be the consequence of compiling .cpp files including headers with implementations(what you are suggesting); hence the one definition rule.
In a one .cpp-file project as Mooing suggests you can of course abuse this to your delight as long as you have a .cpp with a main and only one set of includes.
A: Essentially, this is what #include does (it pastes the header into the cpp, basically doing the same thing in a sense). So, yes, everything SHOULD work out fine, assuming no odd cases. I can't see why you would want to do this though. You'd be better off just flat out defining the functions and such in the class definition or just using #include. Is there any reason you're choosing not to?
EDIT: In response to your edits, why are you implementing members in the header? I'd suggest moving those to the .cpp unless this is a template class or some similar special case. Use the header for prototype and decleration, use the cpp for definition. That should solve any issues for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to generate and insert datetime into a mysql database (PHP) Hey I need to insert current datatime into mysql database.. this is the format:
0000-00-00 00:00:00
A: Most easily done with MySQL directly using the NOW() function.
INSERT INTO tbl (datecol) VALUES (NOW());
If you need PHP to produce a value other than the exact current timestamp, use the format:
date('Y-m-d H:i:s', $some_unix_timestamp);
A: As a MySQL query:
INSERT INTO table (fieldname) VALUES (NOW())
And wrapped in PHP:
$db = new PDO($dsn, $user, $password);
$db->query("INSERT INTO table (fieldname) VALUES (NOW())");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't get the correct parameters from PayPal's new screen I'm developing an application in rails, my problem is that now with the new design of PayPal's screen, when it redirects the client to my web page to notify him if the transaction has been done correctly, I only get in [:params] the controller's and the action's name, when I should receive this two parameters: [:payment_status] and [:payer_status].
I'll try to explain it better, sometimes, when the user finishes the checkout on my web page and clicks on the "buy" button, my page redirects him to a PayPal screen that has the description of the products bought in the top of the page, and sometimes to another screen that has the description in the right side of the screen.
After he pays on PayPal, he has the option to return to my page, where he would be notified with a message like "The transaction has been done". The problem is that always that the user is redirected to the second PayPal screen, after he pays and returns to my page, a message like this appears "The transaction could not be finished correctly", because like I said before I don't get the correct parameters. But always that the user is redirected from the first screen, I get the correct parameters and I can show the "transaction completed" message correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Setting local field from timer I have the following problem in my unit test. The class with tests:
class TestClass {
boolean stopTest = false;
@Test
public void test() {
// do something
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
stopTest = true;
}
}, 1200);
while(!stopTest) {
}
timer.cancel();
// do assert
}
}
This test works right only in debug with breakpoint on while operator, but if I run test not in debug or without breakpoint, he works infinitely. I tried to change stopTest to class with boolean field, also a tried to work through get and set methods in this class. What I do wrong?
A: You need to use the volatile modifier due to concurrency, otherwise stopTest cannot be reliably updated and read. For more information, see JLS §8.3.1.4 - volatile Fields.
volatile boolean stopTest = false;
A: You should declare stopTest to be volatile.
See also:
*
*volatile vs atomicboolean
*synchronized methods
*tutorial on concurrency
A: @JRL and @mrkhrts are right. But I would like to suggest something else.
You really do not need timer here. You just want to run some code in separat thread and make your main thread to wait until this asynchronous task is done. Do it using simple thread and join() method:
@Test
public void test() {
// do something
Thread t = new Thread() {
public void run() {
try {Thread.sleep(1200)} catch(InterruptedException e) {}
// do what you want here
}
}
t.start();
t.join(); // this line will be bloked until the async task is done.
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Centering text overlays over images in div containers I have two images to be displayed in two div boxes. I would like the box positions to be fixed and also for text overlays (captions) on the images. The images keep changing and are of varying sizes, so fixing the size of the box prevents the page elements from jumping around.
Not being an expert on the subject I followed a few tutorials to achieve that, the main ones being here and here.
The code am playing with can be found with and modified here and is also pasted below.
Am looking for the caption background to be the exact same width as the caption. And not spill over the side of the image when the image is really small (possibly wrap in that case).
HTML:
<div class="outer">
<div class="container">
<div class="wraptocenter">
<span class="wrimg">
<div class="shrinkwrapImage">
<h3 class="caption">Image Caption 1</h3>
<img src="http://www.google.fr/images/logos/ps_logo2.png" />
</div>
</span>
</div>
</div>
<div class="container">
<div class="wraptocenter">
<span class="wrimg">
<div class="shrinkwrapImage">
<h3 class="caption">Image Caption 2</h3>
<img src="http://www.google.fr/images/logos/ps_logo2.png" width="30%"/>
</div>
</span>
</div>
</div>
</div>
CSS:
.container * {
border:1px solid;
}
.container {
position:relative;
height:400px;
width:400px;
margin:0 auto;
}
.caption {
position:absolute;
padding:0.05em;
top:0.1em; left:120px; right:120px;
color: white;
background: rgb(0, 0, 0); /* fallback color */
background: rgba(0, 0, 0, 0.4);
font: 14px Helvetica, Sans-Serif;
text-align:center;
}
.wraptocenter .wrimg{
display: table-cell;
text-align: center;
vertical-align: middle;
width: 400px;
height: 400px;
}
.wraptocenter * {
vertical-align: middle;
}
.wraptocenter {
display: block;
}
.wraptocenter span {
display: inline-block;
height: 100%;
width: 1px;
}
.wraptocenter .wrimg img{
box-shadow: 0px 0px 0.5em #000000;
border-radius:0.5em;
max-width:400px;
max-height:400px;
}
.shrinkwrapImage {
position : relative;
}
A: The solution that comes to my mind is using a background image
HTML
<div id="pictures">
<div id="picture1">
<h3 class="caption">Image Caption 1</h3>
</div>
</div>
CSS
#picture1 { background: url(http://www.google.fr/images/logos/ps_logo2.png) top center no-repeat; width: 400px; height: 500px; }
A: Remember that the keyword "expression" in CSS, which basically eval JS in your CSS, only works in IE < 8.
I think that I got what you expect here http://jsfiddle.net/sanbor/3Gb6e/8/
A: Here's your solution: http://jsfiddle.net/vonkly/D9hB3/
The container (yellow background) is a fixed size, as requested. The caption currently sits at the top of the image; simply adjust the top: 0; property in the css for .captioned span (note: about 46% will get you a vertically centered caption). The image can be whatever size you want; the caption will always be at the area you specify (and with the proper width).
CSS
.container{
display: table;
background: yellow;
height: 400px;
width: 400px;
}
.centeritall {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.centeritall .imageWrap {
position: relative;
top: 0;
left: 0;
display: inline-block;
}
.imageWrap span {
position: absolute;
top: 0;
left: 0;
width: 100%;
color: #fff;
background-color: black;
}
HTML
<div class="container">
<div class="centeritall">
<div class="imageWrap">
<img src="http://www.placehold.it/300x200" />
<span>This is a caption for the image...</span>
</div>
</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to hook up Data Binding, Linq, DataGridView in the MVC way? I'd like to separate the presentation logic and the controls as much as possible in a MVC fashion:
class MyModel : INotifyPropertyChanged {
private IEnumerable<Domain> _domains;
public IEnumerable<Domain> Domains {
get { return _domains; }
set { _domains = value; SendPropertyChanged("Domains");
}
}
class MyControl
{
// m_Grid's hooked up to m_BindingSource
private DataGridView m_Grid;
private BindingSource m_BindingSouce;
public void SetModel( MyModel model )
{
m_BindingSource.DataSource = model.Domains;
}
}
class Controller
{
private MyModel _model;
private void UpdateDomains()
{
// predicate is built on user inputs
_model.Domains = db.GetDomains( predicate );
}
}
// extra code to create Controller, MyModel, and MyControl.
When MyModel.Domains is changed, an event is fired to inform MyControl that its m_BindingSource.DataSource is changed. However, the grid isn't updated with the new values.
To fix this problem, MyControl is changed to:
class MyControl
{
public void SetModel( MyModel model )
{
m_BindingSource.DataSource = model.Domains;
model.Domains.PropertyChanged += OnDataChanged;
}
private void OnDataChanged(object sender, PropertyChangedEventArgs e)
{
BindingSource.DataSource = _model.Data.Users;
}
}
Can anyone explain why is this needed? One of the main benefits of DataBinding is to alleviate programmers from managing PropertyChanged events. Ironically, BindingSouce is able to detect changes on MyModel.Domains. I experimented updating the DataSource inside a handler of m_BindingSource.DataSourceChanged. After the change, the grid stops updating.
A: See if an ObservableCollection http://msdn.microsoft.com/en-us/library/ms668604.aspx
or BindingList http://msdn.microsoft.com/en-us/library/ms132679.aspx makes any difference.
btw you made a typo (forgot the 'r'):
private BindingSource m_BindingSouce;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Memory allocation doubt with type pointer to char This program is supposed to prompt for the number of letters in a word(to be entered later) so it knows how much space to allocate. It seems to work OK, however it doesn't seem to matter if you allocate less memory than needed for the word to be stored.
Is it a bug that I must correct or is it because that's how pointer to char (char *) works?
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int a = 0;
printf("Enter the size of the word(0=exit) :");
scanf("%d",&a);
if(a==0){return 0;}
else
{
char *word = (char *)malloc(a*sizeof(char) + 1);
if(word == NULL)
{
fprintf(stderr,"no memory allocated");
return 1;
}
printf("Reserved %d bytes of space (accounting for the end-character).\nEnter your word: ", a*sizeof(char) + 1);
scanf("%s", word);
printf("The word is: %s\n", word);
}
return 0;
}
All right i think i might have fixed it, this way, running with valgrind shows none of the errors that it showed earlier.
char aux[]="";
scanf("%s", aux);
if(strlen(aux)>(a*sizeof(char) + 1))
{
fprintf(stderr,"Word bigger than memory allocated\nExiting program\n");
return 1;
}
else
{
strcpy(word,aux);
printf("The word is: %s\nAnd is %d characters long\n", word, strlen(word));
}
Now my doubt is: why can I declare an empty char array(char aux[] = ""), and then use "extra" memory with no errors (in valgrind output) yet char *aux = ""; gives me a segmentation fault?
I'm very new to C programming so I'm sorry if it's obvious/ dumb question.
Thanks.
A: It doesn't seem to matter but it does, if you use more space than allocated you will eventually end with a buffer overrun. It's possible that your current implementation allocates a bit more than what you actually request, its also possible that it doesn't. You cannot relay on that behavior, never access/use memory that wasn't allocated.
Also sizeof( char ) == 1 by definition.
A: Yes, you must correct that bug in your program.
When you allocate less memory than you need, and later access that "extra" memory, the program goes into undefined behavior mode. It may seem to work, or it may crash, or it may do anything unexpected. Basically, nothing is guaranteed after you write to the extra memory that you didn't allocate.
[Update:]
My proposal to read a string of arbitrary length from a file is the following code. I cannot help that it is somewhat long, but since standard C doesn't provide a nice string data type, I had to do the whole memory management thing on my own. So here it is:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/** Reads a string from a file and dynamically allocates memory for it. */
int fagetln(FILE *f, /*@out*/ char **s, /*@out*/ size_t *ssize)
{
char *buf;
size_t bufsize, index;
int c;
bufsize = 128;
if ((buf = malloc(bufsize)) == NULL) {
return -1;
}
index = 0;
while ((c = fgetc(f)) != EOF && c != '\n') {
if (!(index + 1 < bufsize)) {
bufsize *= 2;
char *newbuf = realloc(buf, bufsize);
if (newbuf == NULL) {
free(buf);
return -1;
}
buf = newbuf;
}
assert(index < bufsize);
buf[index++] = c;
}
*s = buf;
*ssize = index;
assert(index < bufsize);
buf[index++] = '\0';
return ferror(f) ? -1 : 0;
}
int main(void)
{
char *s;
size_t slen;
if (fagetln(stdin, &s, &slen) != -1) {
printf("%zu bytes: %s\n", slen, s);
}
return 0;
}
A: Usually (but not always) the overflows of allocated buffers causing a crash when you free the buffer. If you would add free(word) at the end, you will probably see the crash.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a semantic way of using 3 select boxes to choose 'Date of Birth'? I'm currently building a web form and I need users to enter their DOB.
I have used 3 select boxes at the moment. One for the Day, one for the Month and one for the Year.
I have wrapped them within a 'Date of Birth' label and styled things up with CSS.
Everything looks ok, but when I go to validate things, I get the following error:
" The label element may contain at most one input, button, select, textarea, or keygen descendant "
It would be good to hear if there is a better way of doing this or any semantic alternatives?
Thanks in advance :o)
ps - I had to include a br within the label too, this is to get the select boxes to clear the label text. I've wrapped the select boxes within my label tag for positioning purposes, as my form is made up of a two column layout. There doesn't seem to be a validation issue with the br where it is. So hoping it's ok...
Here's what things look like atm:
and here's my code atm:
<label id="date_of_birth">Date of Birth:<br />
<select class="first" name="date_of_birth:day" tabindex="7">
<option value="">
<!-- -->
</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="date_of_birth:mon" tabindex="8">
<option value="">
<!-- -->
</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select name="date_of_birth:year" tabindex="9">
<option value="">
<!-- -->
</option>
<option value="1920">1920</option>
<option value="1921">1921</option>
<option value="1922">1922</option>
<option value="1923">1923</option>
<option value="1924">1924</option>
<option value="1925">1925</option>
<option value="1926">1926</option>
<option value="1927">1927</option>
<option value="1928">1928</option>
<option value="1929">1929</option>
<option value="1930">1930</option>
<option value="1931">1931</option>
<option value="1932">1932</option>
<option value="1933">1933</option>
<option value="1934">1934</option>
<option value="1935">1935</option>
<option value="1936">1936</option>
<option value="1937">1937</option>
<option value="1938">1938</option>
<option value="1939">1939</option>
<option value="1940">1940</option>
<option value="1941">1941</option>
<option value="1942">1942</option>
<option value="1943">1943</option>
<option value="1944">1944</option>
<option value="1945">1945</option>
<option value="1946">1946</option>
<option value="1947">1947</option>
<option value="1948">1948</option>
<option value="1949">1949</option>
<option value="1950">1950</option>
<option value="1951">1951</option>
<option value="1952">1952</option>
<option value="1953">1953</option>
<option value="1954">1954</option>
<option value="1955">1955</option>
<option value="1956">1956</option>
<option value="1957">1957</option>
<option value="1958">1958</option>
<option value="1959">1959</option>
<option value="1960">1960</option>
<option value="1961">1961</option>
<option value="1962">1962</option>
<option value="1963">1963</option>
<option value="1964">1964</option>
<option value="1965">1965</option>
<option value="1966">1966</option>
<option value="1967">1967</option>
<option value="1968">1968</option>
<option value="1969">1969</option>
<option value="1970">1970</option>
<option value="1971">1971</option>
<option value="1972">1972</option>
<option value="1973">1973</option>
<option value="1974">1974</option>
<option value="1975">1975</option>
<option value="1976">1976</option>
<option value="1977">1977</option>
<option value="1978">1978</option>
<option value="1979">1979</option>
<option value="1980">1980</option>
<option value="1981">1981</option>
<option value="1982">1982</option>
<option value="1983">1983</option>
<option value="1984">1984</option>
<option value="1985">1985</option>
<option value="1986">1986</option>
<option value="1987">1987</option>
<option value="1988">1988</option>
<option value="1989">1989</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
<option value="1994">1994</option>
<option value="1995">1995</option>
<option value="1996">1996</option>
<option value="1997">1997</option>
<option value="1998">1998</option>
<option value="1999">1999</option>
<option value="2000">2000</option>
</select>
</label>
A: There is a suggestion here that structures a DOB appropriately for assistive technology that might help answer your question (in your case the <input>'s would be replaced with <select>'s:
This is how I'd tend to do it (I'm not saying it's necessarily the
best way, mind you): I have visible text for sighted users, and have
css-positioned text offscreen for screen reader users where it will be
picked up and correctly associated with the appropriate controls.
Birthdate:
<fieldset id="birthdate">
<label for="birthday_day" class="offset">Birthday Day</label>
<input type="text" name="birthday_day" id="birthday_day" size="2" maxlength="2" value="" />
<label for="birthday_month" class="offset">Birthday Month</label>
<input type="text" name="birthday_month" id="birthday_month" size="2" maxlength="2" value="" />
<label for="birthday_year" class="offset">Birthday Year</label>
<input type="text" name="birthday_year" id="birthday_year" size="4" maxlength="4" value="" />
</fieldset>
...you need a label for each control, otherwise assistive technology
will struggle with it - it will just say "edit:" and someone won't
necessarily know what they are supposed to put in each field. This
method tells the assistive technology without taking up screen real
estate.
A: my code , very simple,using jquery: codepen
HTML :
<form class = "container">
<label >birthday<span>*</span></label>
<SELECT id ="year" name = "yyyy" onchange="change_year(this)">
</SELECT>
<SELECT id ="month" name = "mm" onchange="change_month(this)">
</SELECT>
<SELECT id ="day" name = "dd" >
</SELECT>
</form>
JS:
var Days = [31,28,31,30,31,30,31,31,30,31,30,31];// index => month [0-11]
$(document).ready(function(){
var option = '<option value="day">day</option>';
var selectedDay="day";
for (var i=1;i <= Days[0];i++){ //add option days
option += '<option value="'+ i + '">' + i + '</option>';
}
$('#day').append(option);
$('#day').val(selectedDay);
var option = '<option value="month">month</option>';
var selectedMon ="month";
for (var i=1;i <= 12;i++){
option += '<option value="'+ i + '">' + i + '</option>';
}
$('#month').append(option);
$('#month').val(selectedMon);
var d = new Date();
var option = '<option value="year">year</option>';
selectedYear ="year";
for (var i=1930;i <= d.getFullYear();i++){// years start i
option += '<option value="'+ i + '">' + i + '</option>';
}
$('#year').append(option);
$('#year').val(selectedYear);
});
function isLeapYear(year) {
year = parseInt(year);
if (year % 4 != 0) {
return false;
} else if (year % 400 == 0) {
return true;
} else if (year % 100 == 0) {
return false;
} else {
return true;
}
}
function change_year(select)
{
if( isLeapYear( $(select).val() ) )
{
Days[1] = 29;
if( $("#month").val() == 2)
{
var day = $('#day');
var val = $(day).val();
$(day).empty();
var option = '<option value="day">day</option>';
for (var i=1;i <= Days[1];i++){ //add option days
option += '<option value="'+ i + '">' + i + '</option>';
}
$(day).append(option);
if( val > Days[ month ] )
{
val = 1;
}
$(day).val(val);
}
}
else {
Days[1] = 28;
}
}
function change_month(select) {
var day = $('#day');
var val = $(day).val();
$(day).empty();
var option = '<option value="day">day</option>';
var month = parseInt( $(select).val() ) - 1;
for (var i=1;i <= Days[ month ];i++){ //add option days
option += '<option value="'+ i + '">' + i + '</option>';
}
$(day).append(option);
if( val > Days[ month ] )
{
val = 1;
}
$(day).val(val);
}
A: Try following code for date of birth , select box.
code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script>
var setyear=0;
var setmonth=0;
var dayarray=new Array("31","28","31","30","31","30","31","31","30","31","30","31");
function onchangeyear(val){
setyear=val;
var dayoption='<option value="">Day</option>';
// dayarray[val-1];
if(setmonth!=0){
if(val%4==0 && setmonth==2) {
for(var i=1;i<=parseInt((dayarray[setmonth-1]))+1;i++) {
dayoption +='<option value="'+i+'">'+i+'</option>';
}
}else{
for(var i=1;i<=parseInt(dayarray[setmonth-1]);i++) {
dayoption +='<option value="'+i+'">'+i+'</option>';
}
}
$('#day').html(dayoption);
}else{
for(var i=1;i<=31;i++) {
dayoption +='<option value="'+i+'">'+i+'</option>';
}
$('#day').html(dayoption);
}
}
function onchangemonth(val){
setmonth=val;
var dayoption='<option value="">Day</option>';
// dayarray[val-1];
if(setyear!=0){
if(setyear%4==0 && val==2) {
for(var i=1;i<=parseInt((dayarray[val-1]))+1;i++) {
dayoption +='<option value="'+i+'">'+i+'</option>';
}
}else{
for(var i=1;i<=(dayarray[val-1]);i++) {
dayoption +='<option value="'+i+'">'+i+'</option>';
}
}
$('#day').html(dayoption);
}else{
for(var i=1;i<=dayarray[val-1];i++) {
dayoption +='<option value="'+i+'">'+i+'</option>';
}
$('#day').html(dayoption);
}
}
</script>
<label id="date_of_birth">Date of Birth:<br />
<select class="first" name="date_of_birth:day" tabindex="7" id="day">
<option value="">--day--</option>
<option value="1">1</option>
-------------------------
<option value="31">31</option>
</select>
<select name="date_of_birth:mon" tabindex="8" id="month" onchange="onchangemonth(this.value)">
<option value="">month</option>
<option value="1">Jan</option>
-------------------
<option value="12">Dec</option>
</select>
<select name="date_of_birth:year" tabindex="9" id="year" onchange="onchangeyear(this.value)">
<option value=""> years</option>
<option value="1920">1920</option>
----------------
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
</select>
</label>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: vb6 - NUMERIC and microsoft ole db provider for sql server First of all sorry for the bad english.
I want to make the following query: "select top 1 NumeroLote from tblLote where convert(numeric(12), Documento)=28405"
The data for "Documento" is stored on a varchar field and sometimes is recorded as "002008" or "2008"... That's why I was trying to use numeric.
It works on sql server 2008 but when I use it from vb6 using Provider="sqloledb"and Microsoft ActiveX Data Objects 2.0 library, I get the following error: "numeric is not a recognized function name. Microsoft Ole Db provider for sql server".
Do you know some alternatives, I can only think of using "like".
EDIT: Documento might be varchar(12)
Answer: bigint
Thank you so much for your time!
A:
The data for "Documento" is stored on a varchar field and sometimes is recorded as "002008" or "2008"... That's why I was trying to use numeric.
Is the number always an integer? If so, try using this instead:
CONVERT(INT, Documento)
Edit: Use bigint to avoid the overflow problem:
CONVERT(BIGINT, Documento)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: rsync with delta transfers to synchronize based on timestamps I use rsync command to delta transfers. What rsync does is that it would transfer only changes. Now I have two machines each of which have two folders whose contents get changed from time to time. What I want is to have a script that when executed replaces the contents of the side that is older with the one that is newer. The older one is the one that has lower timestamp when compared with the newer one. Is rsync capable of doing this?
A: Use the -u option (which won't overwrite a file with a newer timestamp) and run rsync twice:
local@localhost: rsync -au remote@remotehost:/dir1/ dir2
local@localhost: rsync -au dir2/ remote@remotehost:/dir1
A: Duplicates:
synchronization-of-a-directory-in-2-systems-using-rsync
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to loop through all tables in SSIS and export each one to a flat file named after the table (e.g. table1.txt)? Questions says it all.
Using SSIS I want to be able to loop through all the tables in a given database. For each table I want to be able to export all of the data to a flat file (.txt file) that is pipe-delimited and includes column names (I assume using a flat file destination task).
Is this possible? And if so, how to do it?
Thanks - wg
A: General pattern would be
1) Create an Execute SQL task that dumps a table list into an object variable
2) Shred the recordset object into schema and table name variables
3) Perform an Execute Process Task to BCP the data into files
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Which method should I use to create my first open source Ruby Gem with Rails 3.1? Should I use the new Rails 3.1 rails plugin new command, jeweler or bundler to create my first Ruby on Rails Gem? Which tutorials would you recommend to help me get started with writing open source Gems for Ruby on Rails?
A: Generally, Ruby gems are pretty simple, and Rails plugins are just gems that in some way touch Rails APIs. (as the other answer pointed out, Railties are a good way to hook into Rails). To write a gem, designate a folder, and have in it:
*
*<gemname>.gemspec: this lists the gem's name, version, authors, website, a list of gem dependencies and a list of files to include in the gem. (Rails' plugin new and Bundler gem will both generate good .gemspecs for you, see below)
*lib/<gemname>.rb: this is the main code of your gem. Usually this contains a class or a module named after your gem. (Rails' plugin new goes with module).
Everything else is optional, but good practices include:
*
*test/ or spec/: this is where your tests go. Because a Rails plugin is usually used in an app, Rails' plugin new makes a dummy app in test/. If your gem is pretty standalone, with no explicit Rails integration, you don't need the dummy app.
*README, for describing what you gem does and how it's to be used.
You can make this folder and, critically, the .gemspec file entirely by hand, but the two tools will give you the following:
Bundler does for you:
*
*creates a Gemfile for you and automatically includes dependencies specified in your <gemname>.gemspec in the bundle (it's a single Gemfile command, gemspec)
*creates a sample <gemname>.gemspec for you, sets it up to pull your gem's version from lib/<gemname>/version.rb
*sets up using Git to generate a list of gem files (convenient, but the gem-building machine needs to have Git installed). Usually I do this using Rake, but it's more annoying.
Rails' plugin new does the Gemfile and .gemspec, just like Bundler. Also:
*
*Rails uses Ruby to generate the list of gemfiles. Nice.
*It sets up a minimal directory structure, mostly empty, for you.
*It sets up a sample test, and an entire dummy app(!) for the test to run against. I just saw this, and it strikes me as genius.
Rails will also make you a Rakefile, for adding rake tasks, and both tools will preconfigure a .gitignore for Git to ignore some common products.
To test your gem in an actual app, do gem build <gemname>.gemspec, and add gem <gemname> to your app's Gemfile. This will make a -.gem file, which contains the whole gem. You can gem install <gemname>-<version>.gem, and Bundler will pick it up.
When you're ready to publish, gem push <gemname>-<version>.gem will push it up to RubyGems.org. See http://rubygems.org for details on getting an account and pushing gems.
Also, while you're developing, you'll want to make changes to your gem and not have to keep building (and installing) versions. Unit testing will take care of some of that, but if you'd like to use your gem directly from source, Bundler has a fantastic tool:
gem <gemname>, :path => "<path/to/your/gems/folder>"
The folder is the one that contains the .gemspec file.
Does anyone know any reason to use jeweler? I'd love know what it does more than these guys. Generally, writing gemspecs by hand is pretty easy for me, once you've got one template to copy-and-paste-and-modify. Also, if I made any mistakes or omissions in what each tool gives you, I've made the answer a wiki so they can be corrected.
A: rails plugin new creates an empty gem, that immediately hooks into rails. So it does creates a "frame" for you to fill in.
You will then still need either bundler or jeweler to actually convert this set of files to a gem and publish it.
Which you would choose from the two is a bit a matter of taste. Lately I find a lot of people are actually advocating to use bundler. But with bundler it still is mainly a manual process.
I personally believe it still is very interesting to use jeweler. What are the advantages of using jeweler:
*
*use a Gemfile as in any rails or other project, jeweler will generate a gemspec that corresponds to that. Note that this is opposite to what Yehuda from bundler fame proposes: he proposes to fill in the gemspec manually, and then lets the Gemfile use that by specifying gemspec in the file.
*adds a set of rake tasks to make your life easier to publish and build your gem
*allows easy version management
*very well integrated with git, will automatically tag, push, commit.
In short I still recommend to use jeweler, after doing a rails plugin new.
Hope this helps.
A: Since gems are easier to install and manage, it might be best to use jeweler to create your gem. The best way to find inspiration is to open up the source of any gem that has Rails integration and see how they do it. Generally this is done through the Railties facility.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ajax.BeginForm Update unique div id in For Loop Update
I ended up just using Session Variables to pass in the values to the Ajax.BeginForm block. It's a hack that I didn't want to use, but I just couldn't find another way...
Original Post
I am using a For Loop that assigns each comment div in the loop a unique id like:
<div id="comment@(feedModel.PostID)"></div>
EX:
comment1
comment2
comment3
Each one of these div's has an Ajax.BeginForm with a input submit button. I want to set the UpdateTargetId AjaxOption, but I can't because each id is unique. So UpdateTargetId = "div" won't work. I can't just pass in the model or TempData becasue this is Ajax.BeginForm. So how do I pass in the feedModel.PostID?
Code:
@foreach (Website.Models.FeedModel feedModel in Model)
{
<span id="commentspan@(feedModel.PostID)" style="margin-top:5px; display:block;
font-weight:bold"><a href="#" onclick="loadPartialView(@feedModel.PostID);
return false;">Comments(@feedModel.Replies)</a></span>
<div id="comments@(feedModel.PostID)"></div>
}
The Javascript that is called:
function loadPartialView(context) {
method HomeController._Comments
$('#comments' + context).load('Home/_Comments/' + context);
}
Inside that PartialView
@if (Request.IsAuthenticated)
{
<div class="childpost">
@using (Ajax.BeginForm("SubmitChildPost", "Home", new AjaxOptions { UpdateTargetId =
"comments@TempData['feedModelID'].ToString()" }, new { id =
@TempData["feedModelID"].ToString() }))
{
@Html.TextArea("MessageBox", "", 2, 50, null)
<br />
<p>
@Html.AntiForgeryToken()
<input type="submit" value="Reply" class="replybutton" />
</p>
}
</div>
}
Which posts to the Action. The string id is null because you can't pass Model values or Temp Data to the Ajax.BeginForm so I'm not sure what to do...
[ValidateAntiForgeryToken]
public ActionResult SubmitChildPost(FormCollection formValue, string id)
{
string message = formValue["MessageBox"].ToString();
if (message != "")
{
MessageRepository.UpdatePostReply(Convert.ToInt32(id));
MessageRepository.SaveChildPost(message, id, User.Identity.Name);
}
return RedirectToAction("_Comments", "Home", new { ID = id});
}
A: Assuming that the Ajax.BeginForm is inside of the For loop, you can give the target div a unique id using the same method you already are using, like so:
@using (Ajax.BeginForm("Comment", "Comments", new AjaxOptions()
{ HttpMethod = "Post", UpdateTargetId = "target" + feedModel.PostID }))
Then, in your loop, define the target div:
<div id="target@feedModel.PostID" />
UPDATE
Based on the code you posted, making an assumption that the context value you are passing is being passed into the id tokenvalue in your route, then you can capture this value in the PartialView as follows:
@{
var id = this.Request.RequestContext.RouteData.Values["id"].ToString();
}
Then, you can use id to assign your unique id.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Wordpress with SQL Server I was wondering if there is any way wordpress (php) can be used to write to a SQL Server . Simpler the better. We are currently looking at transferring our website over a CMS (preferrably wordpress) but we have all SQL Server databases.
Thanks for the insight guys.
A: This is actually quite simple with the WP Db Abstraction plugin. I have been using it for months and it seems quite solid. After you extract the WordPress archive but before running the installer you will need to edit your wp-config.php file your database connection details. From that point it is just like running WordPress with MySQL. Fire up the browser and the installer will complete the setup of WordPress
http://wordpress.org/extend/plugins/wordpress-database-abstraction/
P.S. This works great with SQL Azure as well
A: You will want to be careful when following the Running WordPress on SQL Server tutorial mentioned by Remus Rusanu. It relies in a pre-built version of WordPress that is not up to date with the latest releases. It is safer to use the WP Db Abstraction plugin directly from the WordPress.org site.
A: You may start looking at http://code.google.com/p/wordpress-mssql/.
My advice is to try a different approach that will avoid wordpress hacks.
A: There is a detailed step by step how-to at Running WordPress on SQL Server. It allows you to run on both standalone SQL Server or on a SQL Azure database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: is it possible to get the height of a cloned jQuery object? Sample jQuery:
$('document').ready(function(){
var $theP = $('p');
var $theDiv = $('div');
$theP.html($theP.html() + "<br>div height: " + $theDiv.outerHeight());
var $theClone = $theDiv.clone();
$theP.html($theP.html() + "<br>clonded div height: " + $theClone.outerHeight());
})
Live link: http://jsbin.com/odujiv/4
In running above, you get a result of '0' when trying to get its height. I think this is due to the fact that the cloned object hasn't yet been put into the DOM. Is the only way to get the height to first add the cloned element back to the DOM? If so, I think that's doable, but it'd be great to handle it before I put it back into the DOM.
A: No, unfortunately. Raw HTML elements don't have sizes when not attached to the document, and jQuery hasn't implemented a workaround. I assume that this is because of how interdependent HTML elements' sizes are on each other!
A: Try this:
$theClone.height();
or
$theClone.css('height');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Question about .profile generated by ubuntu 11.04 I noticed the following lines at the bottom of my ~/.profile that was generated from when I installed Ubuntu 11.04:
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
PATH="$HOME/bin:$PATH"
fi
I see the logic there, but shouldn't the PATH variable be exported?
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
export PATH="$HOME/bin:$PATH"
fi
If not, then I don't understand how the value of PATH does not get lost once the bottom of the .profile file is reached, unless something is sourcing this file with . ~/.profile, which I do not see (at least explicitly) happening in any other shell script on the system.
A: If a variable is already exported, you don't have to export it again. And yes, the shell does (the moral equivalent of) source .profile when you start a login shell (unless you also have a .bash_profile; but then that should customarily source .profile in turn).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Every Python IDLE run starts a new process Windows 7: I'm using Python3.2 with IDLE. Every time I edit and load my program, I get a new "pythonw.exe *32" process (as shown by Windows Task Manager)--even if the program just prints Hello World.
This is a special nuisance if the program is on a static RAM drive, because then I have to kill each of these processes individually before I can eject my drive.
Is this a bug in IDLE? Is there a way I can prevent this from happening? Or at least, is there a way I can kill all these pythonw processes at once, instead of one at a time?
A: Upgrade to version 3.2.2. That fixed the bug for me. I saw the same thing in 3.2.1.
A: You can also kill multiple python processes at once on Windows with the command:
taskkill /F /IM pythonw.exe
A: I've noticed this on Windows 7, running IDLE v2.7.3; Tk version 8.5; Python 2.7.3
However, it only seems to fail to close the process if you kill a program before it finishes on its own. If possible, let your programs run to their end.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Recover a SVN repository from within a SVN repository OK - so I managed to create a SVN repository within another SVN repository on a remote network svn server. See screenshots for details. I used the Tortoise client when I originally made that fatal error. Bottom line, I just need to pull the data off of the existing repository and place it into the first/original repository.
A: *
*Export the outer repository (exporting prevents the creation of .svn folders) into some folder on your HD. (If it is too big to be exported all, you need to selectively export only the files and folders of the inner repository.) Recover the inner repository from that, and move it wherever you need it, trash the rest of the exported files and folders.
*Make sure the inner repository you salvaged is working faultlessly.
*Delete (svn delete) the files and folders of the inner repository from the outer one.
Yes, that leaves you with a confusing piece of history in the outer repository, but usually this is not a problem. (There are ways to remove stuff from a repository's history, but that is complicated and rarely ever worth the bother.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change direction of disclosure triangle How can I change the direction of the disclosure triangle programmatically?
In Interface Builder it's possible by changing the value "Control -> Layout" from "Left to Right" or "Right to Left".
I made a diff of a NIB file. The only change was NSCellFlags2.
Is this documented anywhere?
A: The method you’re looking for is -[NSCell setUserInterfaceLayoutDirection:]. You need to obtain a reference to the corresponding cell and then send it the appropriate message. For example, considering disclosureButton points to that disclosure button:
[[disclosureButton cell] setUserInterfaceLayoutDirection:NSUserInterfaceLayoutDirectionRightToLeft];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MessageSource and PropertyPlaceholderConfigurer cannot load messages but with classpath* My applicationContext.xml is in path:
src/main/resources/META-INF/spring
and property files are in path:
src/main/resources/messages
and I load spring context in web.xml as follows:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/spring/applicationContext.xml</param-value>
</context-param>
when I am configuring MessageSource and PropertyPlaceholderConfigurer as follows:
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:messages/apps.properties</value>
</list>
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:messages/ValidationMessages</value>
<value>classpath:messages/app</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
they both don't work, it only works when I change classpath to classpath*
Any ideas why?
A: From Spring documentation:
4.7.2.2 The classpath*: prefix
[...] location string may use the special classpath*: prefix: [...]
This special prefix specifies that all classpath resources that match the given name must be obtained [...], and then merged to form the final application context definition.
Are you sure there are no other messages/apps.properties files on your CLASSPATH coincidentally taking precedence and overriding your file? This description suggests that you might have several same named files that are merged when * is used.
Can you check this by calling:
SomeClass.class.getClassLoader().getResources("/messages/apps.properties");
?
A: Look at this excellent article for classpath v classpth* difference in regards to spring resource loading, I did some testing on your problem in my testing it worked whether i used classpath or classpath*
I am listing the code here about the test i did
*
*I created a this directory structure (META-INF/spring under src/main/resource) placed context.xml
*I am listing complete context.xml here
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:messages/apps.properties</value>
</list>
</property>
</bean>
<bean class="prasanna.service.TestBean">
<property name="appName" value="${appname}"></property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:messages/ValidationMessages</value>
<value>classpath:messages/apps</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
</beans>
*Listing for apps.properties
appname=spring mvc app
*Listing for ValidationMessages.properties
error.name=Invalid name
*TestBean is rather simple
public class TestBean
{
private String appName;
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
}
*I am using a simple java class to load the property files and read them
public class LoadContext
{
public static void main(String[] args)
{
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:META-INF/spring/context.xml"});
ReloadableResourceBundleMessageSource msgs = ctx.getBean(ReloadableResourceBundleMessageSource.class);
TestBean testBean = ctx.getBean(TestBean.class);
Assert.assertTrue(testBean.getAppName().equals("spring mvc app"));
String msg = msgs.getMessage("appname", new Object[]{new DefaultMessageSourceResolvable("appname")}, null);
System.out.println(" "+ msg);
String msg2 = msgs.getMessage("error.name", new Object[]{new DefaultMessageSourceResolvable("error.name")}, null);
System.out.println(" "+ msg2);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: VBA Recordsets: Why does the way I declare my array, in the Fieldvalue parameters of .addnew, matter? I've been trying to dynamically add to a Recordset but I am unable to do so. The .addnew function of a adodb.recordset seems to not allow just any type of array to be passed to it's fieldvalues, values parameters. For example if after setting up your recordset with the appropriate field values you say:
FieldsArray = array("field1", "field2")
ValuesArray = array("val1","val2")
rs.AddNew FieldsArray, ValuesArray
This works!!
But if you instead write
Dim fieldsarray(0 To 1) As String
FieldsArray(0) = "field1"
FieldsArray(1) = "field2"
ValuesArray = array("val1","val2")
rs.AddNew FieldsArray, ValuesArray
It Fails?!?! (More specifically [Run-Time error '3001': Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another])
Why does the way one declares the field array in the .addnew parameters matter? Is there a way I can get the latter to work?
A: This is because in the first example you are declaring two arrays of VARIANT data type, while in the second example you are declaring STRING arrays.
The AddNew function is expecting a variant array.
In you second example, change your first line to:
Dim fieldsarray(0 To 1) As Variant
and it should work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there another way to call this function besides using php's eval? So there's a php function in a database field. Here's what it looks like:
'$put_fname_fn = function($filename) {
return $filename.'.Z';
};'
I'm executing it like this:
$code = fetchFromDatabase(); // Get the function string
eval($code);
$put_fname_fn('MYFILE.TXT'); // Convert it to MYFILE.TXT.Z
Is there a more graceful way to call the user function? I try to avoid using eval but I don't another way to do this.
A: There is no other way to evaluate code in PHP. (You could write the code to a file and include it, but that's just a hidden eval.)
Still you should probably reconsider your application design. Evaluating code from the database is a VERY BIG SECURITY RISK: If your database is compromised (using a simple and common SQL injection attack) you at the same time give the attacker arbitrary PHP code execution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: JPA Equivalent of Oracle TopLink's addBatchReadAttribute We're using JPA, and when a collection of objects returns from a query, a separate query is executed for each "child" object related through a foreign key.
For example, in our Authorization entity class, we have the following Client object mapped:
@JoinColumn(name = "clientId", referencedColumnName = "clientId")
@ManyToOne (fetch = FetchType.LAZY)
@NotNull(groups = Default.class)
private Client client;
When 10 Authorizations are returned, 10 Client queries are executed. In TopLink, I was able to bring this number to one with the ReadAllQuery class's addBatchReadAttribute() method. According to the TopLink docs, "when any of the batched parts is accessed, the parts will all be read in a single query, this allows all of the data required for the parts to be read in a single query instead of (n) queries."
This worked perfectly, giving us a single query using an IN clause with 10 ids.
What I read about re: JPA pointed me toward a batch join or something like:
hints = {@QueryHint(name = "eclipselink.batch", value = "p.client"), ...
This strategy helps reduce the number of queries,
*
*but it also gave me more joins, possibly slowing things down (?) on
some queries
*and it didn't seem to help as drastically as the TopLink call.
Is there a way to get the strategy that uses a single query with IN in the WHERE clause?
Thanks in advance.
Dave
A: Internally the QueryHint "eclipselink.batch" is translated to addBatchAttribute() so the behaviour you see should be identical. Does the JPQL you have created produce the same query as the native TopLink API? It is possible you have Fetch's or additional joins in the JPQL?
A: EclipseLink supports several types of batch fetching.
See,
http://java-persistence-performance.blogspot.com/2010/08/batch-fetching-optimizing-object-graph.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Wrong object referenced when click event is activated I'm attempting to create an accordion effect for a document where when you click on an <h1> the rest of the document (the <div.container>) with toggle sliding up and sliding down. I keep running into a problem however. Here is the code:
HTML
<article>
<h1>Title</h1>
<div class="container">
//...
</div>
</article>
<article>
//...
</article>
<article>
//...
</article>
CoffeeScript:
articles = $('article').toArray()
for article in articles
#console.log $('.container', article).parent().attr('id')
$('h1', article).click ->
$('.container', article).slideToggle 'slow'
When I use the article variable in say... the console.log It rotates through the articles and prints back their ids. But when I go to click any of the <h1> elements, it always collapses the last <article>s <div.container>.
I think this is because the article variable is stored outside of the scope of the for loop in CoffeeScript and the click doesn't execute until after the loop has already completed.
If this is true, how do I guarantee that the right object is being referenced when the click event is executed? Would it be better just to use a for i in [0...3] loop and just reference the array directly? Is the problem something else entirely? Thank you for your help!
For those who may not be familiar with coffeeScript, here's the javaScript that is compiled (just ignore the _results variable):
var articles
articles = $('article').toArray();
_results = [];
for (_i = 0, _len = articles.length; _i < _len; _i++) {
article = articles[_i];
_results.push($('h1', article).click(function() {
return $('.container', article).slideToggle('slow');
}));
}
A: The reason you are seeing this behavior is because the article referenced in the click events is not evaluated until the handler is triggered, and at that point in time, it is set to the last article which was evaluated in your loop.
This may work a bit better for you (sorry, not sure of the coffee script implementation):
$('article h1').click(function() {
$(this).next('.container').slideToggle('slow');
});
A: Rocco's answer is correct. Let me expand on it:
This is a common area of confusion: Only functions create scope in JavaScript (and CoffeeScript), which means that when you do something asynchronous within a loop, you have to remember to "capture" the variable. The preferred way to do that in CoffeeScript is with the do syntax, which lets you write
for article in articles
do (article) ->
$('h1', article).click ->
$('.container', article).slideToggle 'slow'
which compiles to the equivalent of
for article in articles
((article) ->
$('h1', article).click ->
$('.container', article).slideToggle 'slow'
)(article)
That way, each click callback sees its own iteration of article, not the one that changes value as you go through the loop. I talk about this briefly in my PragPub article A CoffeeScript Intervention.
A: Here's another way to do it (in javascript/jQuery) by:
*
*Modifying the initial selector to pick all the h1 tags under article
*Using this.parentNode to get the context from the click
*Then look for the .container object under that common parent.
This way, we don't have to store any state across the click as we can just find the container that shares the same parent with the item that is clicked on. This method also doesn't rely on the exact position of the container object relative to the h1 that is clicked on - it just needs the container to share the same parent so it's more flexible in future layout.
$('article h1').click(function() {
$('.container', this.parentNode).slideToggle('slow');
});
A: I don't know anything about Coffeescript, but the compiled Javascript has a pretty obvious bug.
This line:
article = articles[_i];
Should read like this:
var article = articles[_i];
With this change, the article variable will be considered part of the calling scope and reference the appropriate element when it comes time to call your handler (rather than referencing an implicit global variable). That's all you need to fix your bug.
Hopefully there's a way to specify that in Coffeescript, but it seems pretty horrendous that for article in articles doesn't do that automatically.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Building with Eclipse and Remote System Explorer First with the background...
*
*We have a Linux server that supports multiple projects.
*The Clearcase server and repository are installed on this Linux server.
*Different projects require different cross-compilers and libraries, and all of them are installed on the server.
*User can choose different tool sets by running different scripts, which exports different environment variable values such as include paths and compilers.
*User needs to run cleartool to mount the repository.
*Developers develop in Eclipse and have two options:
*
*SSH into the server and run Eclipse through with X11 tunneling.
*Install Eclipse locally on their Windows machine and invoke builds from the SSH terminal.
Now:
*
*Problem with #1 is that Eclipse operations (typing, content assist, etc) are extremely laggy.
*Problem with #2 is that the developers need to go through extra hoops to build their code.
This is what I have tried:
*
*Set up Remote System Explorer, which allows remote editing of files and remote running of the compiler:
How to build a c++ project on a remote computer in Eclipse?
This approach works perfectly for files that do not need special environment variable values and mounting of Clearcase repository, but I could not figure out how to get all of these things to integrate.
It would be great if someone can let me know how I can direct RSE to run a script (may be different per project) to set the environment variables and to run the cleartool commands to mount the repository so that it can locate the files.
The cleartool command arguments would be different per user for setting up a particular view.
Some extra info that may help:
*
*I have root access to the development server
*The Clearcase filesystem is mapped to a drive on the Windows machine
Thanks in advance for saving me hours of frustration dealing with a slow network!
==================
Additional detail per comments:
- The VOB storage is located locally on the Linux server. We would SSH to the server and start Eclipse there, therefore the delay should not be due to dynamic vs snapshot view and GUI performance seems to be the real problem.
- We also mount the same view on Windows by using Region Synchronizer. When running the local copy of Eclipse installed on Windows, there is no performance problems.
So this question can probably be solved by answering either question:
1. How to improve X11 performance such that development on Linux will suffice?
2. How to set up Windows Eclipse to perform all the steps mentioned above when building projects?
A: I came here a similar question to your part two, but alas, no one has answered it. However, I have an answer to your part one: https://www.nomachine.com/. It speeds up X11 forwarding considerably.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Firebird TIBQuery insert with returning ... INTO I have a firebird 2.x database with Generator and a trigger to generate the key field.
I need to get the returned value from below query.
INSERT INTO XXXX (vdate,description) values ('"+ VDate +"','"+ Description +"') returning vno INTO :ParamVoucherNo
I tried several versions of below code but it dont wrok and I get
Dynamic sql error sql error code = -104
Is it really possible to get the return value in delphi using TIBQuery ?
Query1->SQL->Clear();
Query1->SQL->Add("INSERT INTO XXXX (vodate,description) values ('"+ VDate +"','"+ Description +"') returning vno INTO :ParamVoucherNo");
Query1->Params->ParamByName("ParamVoucherno")->ParamType = ptResult;
Query1->Params->ParamByName("ParamVoucherno")->DataType = ftInteger;
Query1->Params->ParamByName("ParamVoucherno")->Value = "";
Query1->Prepare();
Query1->ExecSQL();
Any suggestions?
A: From Firebird README.returning:
The INTO part (i.e. the variable list) is allowed in PSQL only (to
assign local variables) and rejected in DSQL.
As IBX uses DSQL, you should exclude INTO part from your query.
INSERT ... RETURNING for DSQL looks the same as a call of a stored procedure, which returns result set. So, you have to use Open instead of ExecSQL.
A: Your mixing of dynamic SQL with parameters is just confusing.
Do this instead:
Query1->SQL->Clear();
Query1->SQL->Add("INSERT INTO table1 (vodate,description) VALUES"+
"(:VoDate,:Description) RETURNING vno INTO :VoucherNo ");
Query1->Params->ParamByName("VoDate")->Value = VDate;
Query1->Params->ParamByName("description")->Value = Description;
Query1->Prepare();
Query1->ExecSQL();
VoucherNo = Query1->Params->ParamByName("VoucherNo")->AsInteger;
A: Using Delphi 6 I have the ID returning successfully using an EXECUTE BLOCK statement:
EXECUTE BLOCK
RETURNS ( DeptKey INT )
AS
BEGIN
INSERT INTO DEPARTMENT
( COMPANY_KEY, DEPARTMENT_NAME )
VALUES ( 1, 'TEST1' ) RETURNING DEPARTMENT_KEY INTO :DeptKey;
SUSPEND;
END;
From Delphi you can do the folliowing:
FQuery.SQL.Text := '<Execute Block Statement>';
FQuery.Open();
ANewKey := FQuery.Fields[0].AsInteger;
A: Why not get the next value for VoucherNo first, followed by
"INSERT INTO table1 (vno, vodate,description) VALUES (:VoucherNo,:VoDate,:Description)");
?
Your trigger can then either be dispensed with (which is nice), or modified to detect null (or <= zero can be useful too) and only then populate the vno field.
create trigger bi_mytable
active before insert position 1
on mytable
as
begin
if (new.vno is null)
then new.vno = next value for gen_VoucherNos;
end
Client-side you can :
select gen_id(gen_VoucherNos, 1) from rdb$database;
By modifying the trigger in this manner you save yourself a headache later on if/when you want to insert blocks of records
A: IBX is not Firebird ready
you can take a look at FIBPLUS who support Firebird features
FIBPlus also supports FB2.0 insert ... into ... returning. Now you
should not bother about getting generator values from the client but
leave them in the trigger. You can also use RDB$DB_KEY. New possible
variants of work with insert returning and RDB$DB_KEY are shown in the
example “FB2InsertReturning”.
A: I wonder if that INSERT can be wrapped into EXECUTE BLOCK command.
Would IBX manage EXECUTE BLOCK then?
*
*http://www.firebirdsql.org/refdocs/langrefupd20-execblock.html
*http://firebirdsql.su/doku.php?id=execute_block
Hope to try it in both IBX and Unified Interbase in XE2
PS: Even if it does not, I found the library, that tells to work on top of IBX of Delphi XE2 (both x86 and x64) and to add EXECUTE BLOCK support: http://www.loginovprojects.ru/index.php?page=ibxfbutils#eb.
A: As I know there should be some changes to IBX made. Internally INSERT ... RETURNING should be treated the same way as a selectable procedure with returning parameters.
A: i know this question was answered a long time ago, but i must write this as clear as possible, for those who need this as i was.
i too, needed the "INSERT..RETURNING" thing.
the Delphi drove me crazy for a long time, until i changed my Data access components.
i even moved from Delphi XE2, to XE5 only because of that...
conclusion : IBX does NOT support RETURNING!
FireDAC is PERFECT for what i need with Firebird.
just move to FireDAC and you'll be able to do everything you need, and with high performance.
A: If you have a table with this 2 Fields: GRP_NO and GROUPNAME and you want to get the new GRP_NO you have to use RET_ as prefix, see example:
procedure TFormDatenbank.Button1Click(Sender: TObject);
var
q: Uni.TUniQuery;
ID: Integer;
GroupName: String;
begin
GroupName := 'MyGroupName';
q := TUniQuery.Create(nil);
try
q.Connection := Datenmodul.UniConnection;
q.ParamCheck := true; // the default value of ParamCheck is true.
q.SQL.Clear;
q.SQL.Add('SELECT GRP_NO, GROUPNAME FROM GROUPDATA WHERE GROUPNAME = :GROUPNAME');
q.ParamByName('GROUPNAME').AsString := GroupName;
q.Open;
if q.RecordCount > 0 then
ID := q.FieldByName('GRP_NO').AsInteger
else
begin
// there exist no group with this name, so insert this new name
q.SQL.Clear;
q.SQL.Add('INSERT INTO GROUPDATA');
q.SQL.Add('(GROUPNAME)');
q.SQL.Add('VALUES');
q.SQL.Add('(:GROUPNAME)');
q.SQL.Add('RETURNING GRP_NO;');
q.ParamByName('GROUPNAME').AsString := GroupName;
q.Execute;
ID := q.ParamByName('RET_GRP_NO').AsInteger;
end;
finally
q.Free;
end;
end;
A: From the IBx2 sources, you can do it like this:
//Uses IBSql;
//var Cur: IResults;
IBSQL1.SQL.Text := 'delete from tbl_document where id = 120 returning id;';
IBSQL1.Prepare;
if IBSQL1.Prepared then
begin
Cur := IBSQL1.Statement.Execute(IBTransaction1.TransactionIntf);
WriteLn(Cur.Data[cou].AsString);
Cur.GetTransaction.Commit(True);
end;
IResults interface Code:
IResults = interface
function getCount: integer;
function GetTransaction: ITransaction;
function ByName(Idx: String): ISQLData;
function getSQLData(index: integer): ISQLData;
procedure GetData(index: integer; var IsNull:boolean; var len: short; var data: PChar);
procedure SetRetainInterfaces(aValue: boolean);
property Data[index: integer]: ISQLData read getSQLData; default;
property Count: integer read getCount;
end;
Test enviroment:
Arch Linux X86
Firebird 3
Lazarus 1.9
FPC 3.0.4
Quick note: This works on new Firebird API in the IBX, But I didn't test it in Legacy Firebird API with the IBX.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: array position objective-c I have an NSArray. Lets say that i have 3 objects inside it. e.g
test (
{
Code = A;
Comment = "None ";
Core = Core;
},{
Code = B;
Comment = "None ";
Core = Core;
},{
Code = C;
Comment = "None ";
Core = Core;
})
I want to search for a 'Code' and return the array index. How can i do this? e.g. locate code 'b' and i would have '1' being returned (since its the second position within the array).
A: Off the top of my head so there might be some typos in it. I am assuming the objects inside your array are dictionaries:
for (NSDictionary dict in testArray)
{
if ([[dict objectForKey:"Code"] isEqualToString:@"B"]
{
NSLog (@"Index of object is %@", [testArray indexOfObject:dict]);
}
}
You could also use (probably more efficient)
- (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate
passing a predicate of @"Code == 'B'" on the block. This method will specifically return the index of objects passing the test.
A: If targeting iOS 4.0 or above there are NSArray methods that allow you to do this using blocks.
– indexOfObjectPassingTest:
– indexesOfObjectsPassingTest:
etc..
NSArray *test = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:@"A", @"Code", @"None", @"Comment", @"Core", @"Core", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"B", @"Code", @"None", @"Comment", @"Core", @"Core", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"C", @"Code", @"None", @"Comment", @"Core", @"Core", nil],
nil];
NSIndexSet *indexes =[test indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [[obj valueForKey:@"Code"] isEqualToString:@"B"];
}];
NSLog(@"Indexes with Code B: %@", indexes);
A: In its simplest form I would use the following:
- (NSInteger)indexForText:(NSString*)text inArray:(NSArray*)array
{
NSInteger index;
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
YourObject* o = (YourObject*)obj;
if ([[o property] isEqualToString:text]) {
index = idx;
*stop = YES;
}
}];
return index;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery Date Range Picker latestDate is not working? im using this jQuery Date Range Picker and im trying to limit the user for choosing a date in the future in the picker. i tried using latestDate but its not working what is the right way to this ?
jQuery_1_6("#dateRange").daterangepicker({
earliestDate: Date.parse('1/1/2009'),
latestDate:Date.parse('today'),
presetRanges: [
{text: 'Last 7 days', dateStart: 'Today-7', dateEnd: 'Today' },
{text: 'Last 30 days',dateStart: 'Today-30', dateEnd: 'Today'},
{text: 'Last 90 days',dateStart: 'Today-90', dateEnd: 'Today'}
],
onClose: function() { },
presets: {
dateRange: 'Date Range'
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Camping model ignores association module App::Models
class Team < Base
has_many :players
[...]
end
class Player < Base
belongs_to :team
end
When calling @team.players (or @player.team):
NoMethodError at /team/red
undefined method `players' for [#<App::Models::Team (...)>]:ActiveRecord::Relation
Am I using it wrong?
A: Note that you're calling players on an instance of ActiveRecord::Relation. You don't actually have one Team, you have a query of several teams. Simply append .first to your definition of @team to get the first team:
class TeamX
def get(name)
@team = Team.where(:name => name).first
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Common sense when storing currencies? After reading up on how to best handle users in multiple timezones properly, I've learned that the way to go is to store all dates in an normalized, application-wide timezone - UTC and then apply the diff between the normalized timezone and the individual users timezone when outputting. Today I came to think if this would be appropriate to apply this approach to handling currency in software:
All stored currency are converted to a application-wide currency, lets say EUR (€), and when outputting, the currency is converted back into the users own currency, with an updated exchange rate of the day?
What's common sense here? How is this generally solved and what should I be aware of before choosing a way to handle this?
A: One standard approach is to store both an amount and a currency whenever monetary values are held and manipulated.
See the Money Pattern in Martin Fowler's Patterns of Enterprise Application Architecture.
Fowler describes defining a simple datatype to hold the two primitive components, with overloaded arithmetical operators for performing monetary operations:
"The basic idea is to have a Money class with fields for the numeric
amount and the currency. You can store the amount as either an
integral type or a fixed decimal type. The decimal type is easier for
some manipulations, the integral for others. You should absolutely
avoid any kind of floating point type, as that will introduce the kind
of rounding problems that Money is intended to avoid. Most of the time
people want monetary values rounded to the smallest complete unit,
such as cents in the dollar. However, there are times when fractional
units are needed. It’s important to make it clear what kind of money
you’re working with, especially in an application that uses both
kinds. It makes sense to have different types for the two cases as
they behave quite differently under arithmetic.
Money needs arithmetic operations so that you can use money objects as
easily as you use numbers. But arithmetic operations for money have
some important differences to money operations in numbers. Most
obviously, any addition or subtraction needs to be currency aware so
you can react if you try to add together monies of different
currencies. The simplest, and most common, response is to treat the
adding together of disparate currencies as an error. In some more
sophisticated situations you can use Ward Cunningham’s idea of a money
bag. This is an object that contains monies of multiple currencies
together in one object. This object can then participate in
calculations just like any money object. It can also be valued into a
currency."
A: The difference between handling time and currency, is that time zones doesn't shift in value.
When handling monetary values you have to consider what the currency of the actual money is. If the actual money is in USD and you store it as EUR, you will get a discrepancy between the actual value and the stored value when their values shift.
Alternatively you would have to recalculate all values when the exchange rate is updated, but that would take away the purpose of storing the values in a single currency.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Setting range of a colormap in Matplotlib I'm using matplotlib to plot a simple graph:
cm=plt.get_cmap('Blues')
nx.draw_circular(G,
node_color='White',
edge_color=range(G.number_of_edges()),
edge_cmap=cm,
node_size=900,
width=4
)
I want to set a range on the colormap 'Blues' in such a way to delete the white color which is not visible in the draw.
Please help!
Sorry for bad english.
A: The range (or normilization) is not really a feature of the colormap, but is often implemented as a feature in the functions that plot using colormaps. For example, imshow uses vmin and vmax, so you might try using these as keywords with draw_circular (I can't find the documentation), or maybe norm.
Other than this, you can make your own colormap with exact color arrangement that you want. There are plenty of examples on how to make custom colormaps, and a few different approaches available. Here (a, b, c, d) are a few examples that might be useful to you.
A: I ran into this problem trying to plot data with different colormaps:
It's hard to which of the whitish dots belong to which distribution. I solved this problem by chopping off the whiter parts of the colormap spectrum:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
def chop_cmap_frac(cmap: LinearSegmentedColormap, frac: float) -> LinearSegmentedColormap:
"""Chops off the beginning `frac` fraction of a colormap."""
cmap_as_array = cmap(np.arange(256))
cmap_as_array = cmap_as_array[int(frac * len(cmap_as_array)):]
return LinearSegmentedColormap.from_list(cmap.name + f"_frac{frac}", cmap_as_array)
cmap1 = plt.get_cmap('Reds')
cmap2 = plt.get_cmap('Blues')
cmap1 = chop_cmap_frac(cmap1, 0.4)
cmap2 = chop_cmap_frac(cmap2, 0.4)
np.random.seed(42)
n = 50
xs = np.random.normal(size=n)
ys = np.random.normal(size=n)
vals = np.random.uniform(size=n)
plt.scatter(xs, ys, c=vals, cmap=cmap1)
plt.scatter(ys, xs, c=vals, cmap=cmap2)
plt.gca().set_facecolor('black')
plt.colorbar()
plt.show()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Remove an Object/Row from a Core Data Entity There are a couple answers similar to this (Like deleting an entire entity). But none that have worked for me. I am just looking for simple way to fetch the object I want to delete using NSPredicate and then delete only that object. I only want to delete one object/row. It should be fairly simple code, nothing too complicated. I would provide my code but I am pretty sure it won't help because it isn't even close to being complete or even working.
A: EntityToDelete *entity = (EntityToDelete *)[NSEntityDescription insertNewObjectForEntityForName:@"EntityToDelete" inManagedObjectContext:self.managedObjectContext];
NSError *error;
[self.managedObjectContext deleteObject:entity];
if (![self.managedObjectContext save:&error]) {
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use jQuery slideDown() to display _almost_ all contents? I have a div within a div. On page load, they should both be hidden, then when I trigger the slideDown() function on the outer div, I want the inner div to remain hidden. How can I achieve this?
<script>
$(function(){
$('.body').hide();
$('.display').click(function(){
$(this).closest('.wrapper').find('.body').slideDown();
});
});
</script>
<div class="wrapper">
<a class="display" href="#">Display Outer</a>
<div class="body">
Now displaying outer div
<div class="wrapper">
<a class="display" href="#">Display Inner</a>
<div class="body">
Now displaying inner div
</div>
</div>
</div>
</div>
Here is an example of it not working: http://jsfiddle.net/b7Tpt/
A: The reason it doesn't work is the use of find. find would traverse all levels to find the matches while the children would travel single level. So use find('.body:first') or children('.body')
$(function(){
$('.body').hide();
$('.display').click(function(){
$(this).closest('.wrapper').find('.body:first').slideDown();
});
});
Updated Example
OR
$(function(){
$('.body').hide();
$('.display').click(function(){
$(this).closest('.wrapper').children('.body').slideDown();
});
});
Updated Example
A: Try -
$('.display').click(function(){
$(this).siblings('.body').slideDown();
});
I think $(this).closest('.wrapper') was moving up the DOM tree and finding the top most wrapper div then opening all the body classes it found underneath. Using siblings should get the element with a body class that is directly beneath the clicked link.
Demo - http://jsfiddle.net/pMgVj/1/
A: try this: http://jsfiddle.net/Kf6gk/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7574753",
"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.