PHP using foreach to insert multiple rows not working
I'm trying to check if a row exists for a specific transaction and when a
new one is submitted it inserts, however, it's only inserting the first
one and not the next 5 that are there too.
Code:
foreach($transactions as $transaction) {
$check_if_transaction_exists =
$db->query("SELECT * FROM
`transactions`")->fetchColumn();
if($check_if_transaction_exists == 0) {
$insert_transaction =
$db->prepare("INSERT INTO
`transactions`
(`deposit_address`,
`amount`,
`timereceived`,
`txid`,
`category`)
VALUES
(:deposit_address,
:amount,
:timereceived,
:txid,
:category)");
$insert_transaction->execute(array(
':deposit_address' =>
$_SESSION['deposit_address'],
':amount' =>
$transaction['amount'],
':timereceived' =>
$transaction['timereceived'],
':txid' =>
$transaction['txid'],
':category' =>
$transaction['category']
));
}
echo '<br />';
echo '<br />' . $transaction['address'];
echo '<br />' . $transaction['amount'];
echo '<br />' . $transaction['confirmations'];
date_default_timezone_set('America/Los_Angeles');
echo '<br />'; echo date("F j, Y, h:i A,",
$transaction['timereceived']);
}
The bottom bit of code returns 6 of the designated elements (address,
amount, confs, etc. ) but only inserts the very first one into the
database. How can I make it insert all of them?
Saturday, 31 August 2013
toISOString() return wrong date
toISOString() return wrong date
Hy this piece of code return the tomorrow date ?
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toisostring
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the date and time as a string,
using the ISO standard.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var d = new Date();
var x = document.getElementById("demo");
x.innerHTML=d.toISOString();
}
</script>
</body>
</html>
Hy this piece of code return the tomorrow date ?
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toisostring
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the date and time as a string,
using the ISO standard.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var d = new Date();
var x = document.getElementById("demo");
x.innerHTML=d.toISOString();
}
</script>
</body>
</html>
Eclipse Color Theme is not working
Eclipse Color Theme is not working
I am Ubuntu 13.04, Eclipse 4.2.1(ADT v22) user.
I encounted error when I might add plugin which is Eclipse Color Theme for
eclipse.
And in Preferences-General-Appearance, when I click Color Theme output
error log...
(Eclipse Color Theme get on Help-install new software
http://eclipse-color-theme.github.com/update
errTitle: Unhandled event loop exception
org.eclipse.swt.SWTException: Failed to execute runnable
(org.eclipse.swt.SWTError: No more handles [Unknown Mozilla path
(MOZILLA_FIVE_HOME not set)])
at org.eclipse.swt.SWT.error(SWT.java:4361)
at org.eclipse.swt.SWT.error(SWT.java:4276)
at
org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:138)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:3537)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3189)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
at org.eclipse.jface.window.Window.open(Window.java:801)
at
org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.open(WorkbenchPreferenceDialog.java:215)
at
org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:65)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
..
..
..
at org.eclipse.jface.util.OpenStrategy$3.run(OpenStrategy.java:433)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at
org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
... 35 more
and close Preference, more error happened.
errTitle: java.lang.ArrayIndexOutOfBoundsException: 0
java.lang.ArrayIndexOutOfBoundsException: 0
at
com.github.eclipsecolortheme.preferences.ColorThemePreferencePage.performOk(ColorThemePreferencePage.java:207)
at
org.eclipse.jface.preference.PreferenceDialog$13.run(PreferenceDialog.java:965)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
at
org.eclipse.jface.preference.PreferenceDialog.okPressed(PreferenceDialog.java:945)
at
org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.okPressed(FilteredPreferenceDialog.java:448)
at
org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.okPressed(WorkbenchPreferenceDialog.java:171)
at
org.eclipse.jface.preference.PreferenceDialog.buttonPressed(PreferenceDialog.java:233)
at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:624)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1276)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3562)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3186)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
at org.eclipse.jface.window.Window.open(Window.java:801)
at
org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.open(WorkbenchPreferenceDialog.java:215)
at
org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:65)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
at
org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
at
org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
at
org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:411)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1276)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3562)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3186)
at
org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1053)
at
org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at
org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:942)
at
org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:86)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:588)
at
org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at
org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:543)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at
org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
at
org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at
org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at
org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
How do I fix it for Eclipse Color Theme working?
I am Ubuntu 13.04, Eclipse 4.2.1(ADT v22) user.
I encounted error when I might add plugin which is Eclipse Color Theme for
eclipse.
And in Preferences-General-Appearance, when I click Color Theme output
error log...
(Eclipse Color Theme get on Help-install new software
http://eclipse-color-theme.github.com/update
errTitle: Unhandled event loop exception
org.eclipse.swt.SWTException: Failed to execute runnable
(org.eclipse.swt.SWTError: No more handles [Unknown Mozilla path
(MOZILLA_FIVE_HOME not set)])
at org.eclipse.swt.SWT.error(SWT.java:4361)
at org.eclipse.swt.SWT.error(SWT.java:4276)
at
org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:138)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:3537)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3189)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
at org.eclipse.jface.window.Window.open(Window.java:801)
at
org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.open(WorkbenchPreferenceDialog.java:215)
at
org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:65)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
..
..
..
at org.eclipse.jface.util.OpenStrategy$3.run(OpenStrategy.java:433)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at
org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
... 35 more
and close Preference, more error happened.
errTitle: java.lang.ArrayIndexOutOfBoundsException: 0
java.lang.ArrayIndexOutOfBoundsException: 0
at
com.github.eclipsecolortheme.preferences.ColorThemePreferencePage.performOk(ColorThemePreferencePage.java:207)
at
org.eclipse.jface.preference.PreferenceDialog$13.run(PreferenceDialog.java:965)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
at
org.eclipse.jface.preference.PreferenceDialog.okPressed(PreferenceDialog.java:945)
at
org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.okPressed(FilteredPreferenceDialog.java:448)
at
org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.okPressed(WorkbenchPreferenceDialog.java:171)
at
org.eclipse.jface.preference.PreferenceDialog.buttonPressed(PreferenceDialog.java:233)
at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:624)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1276)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3562)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3186)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
at org.eclipse.jface.window.Window.open(Window.java:801)
at
org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.open(WorkbenchPreferenceDialog.java:215)
at
org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:65)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
at
org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
at
org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
at
org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:411)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1276)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3562)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3186)
at
org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1053)
at
org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at
org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:942)
at
org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:86)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:588)
at
org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at
org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:543)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at
org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
at
org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at
org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at
org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
How do I fix it for Eclipse Color Theme working?
Capybara - assert_selector("tr#1234") doesn't work, but find_by_id(1234) does
Capybara - assert_selector("tr#1234") doesn't work, but find_by_id(1234) does
What are possible reasons that doing page.find_by_id(id) works, but doing
page.assert_selector("tr##{id}") returns aCapybara::ElementNotFound`?
For background, I am using the Poltergeist driver for Capybara.
I have HTML that is structured like so:
<tbody>
<tr id="1234">
<td>Rico Jones</td>
<td><a href="/price_requests/5678">Price Request</a></td>
</tr>
<tr id="2345">
<td>Rico Jones</td>
<td><a href=/price_requests/6789">Price Request</a></td>
</tr>
</tbody>
I have confirmed that my HTML is coming out as expected by using the
page.driver.debug feature of Poltergeist and looking at the actual HTML
generated by the test.
When I put something like this in my tests, I get a
Capybara::ElementNotFound error:
lead = Lead.first
assert_selector "tr##{lead.id}"
I also get an error when doing this:
lead = Lead.first
within "tr##{lead.id}" do
click_on "Price Request"
end
However, using find_by_id works:
lead = Lead.first
find_by_id(lead.id).click_on("Price Request")
Based on my understanding of Capybara, this shouldn't be the case. Am I
doing something wrong?
What are possible reasons that doing page.find_by_id(id) works, but doing
page.assert_selector("tr##{id}") returns aCapybara::ElementNotFound`?
For background, I am using the Poltergeist driver for Capybara.
I have HTML that is structured like so:
<tbody>
<tr id="1234">
<td>Rico Jones</td>
<td><a href="/price_requests/5678">Price Request</a></td>
</tr>
<tr id="2345">
<td>Rico Jones</td>
<td><a href=/price_requests/6789">Price Request</a></td>
</tr>
</tbody>
I have confirmed that my HTML is coming out as expected by using the
page.driver.debug feature of Poltergeist and looking at the actual HTML
generated by the test.
When I put something like this in my tests, I get a
Capybara::ElementNotFound error:
lead = Lead.first
assert_selector "tr##{lead.id}"
I also get an error when doing this:
lead = Lead.first
within "tr##{lead.id}" do
click_on "Price Request"
end
However, using find_by_id works:
lead = Lead.first
find_by_id(lead.id).click_on("Price Request")
Based on my understanding of Capybara, this shouldn't be the case. Am I
doing something wrong?
Best way to manage and serialize objects in C#
Best way to manage and serialize objects in C#
I'm writing one C# application to improve my basic understanding of .NET,
and I would like to know what is the best way to do what I need for. Best
means for me: simple to code and efficient to use.
My application have to work with objects (of the same type, eg. AAA), and
it creates different collections of them... so I'll have a Collection of
Collections of AAA.
My main needs are: - to work with this main collection in memory and to
persist (serialize) it on disk; - to deserialize from disk into memory;
Another need can be: - to "query" its data (eg. "give me all the
collection in which contained objects has a specified value of a field").
Thank you for you indications.
I'm writing one C# application to improve my basic understanding of .NET,
and I would like to know what is the best way to do what I need for. Best
means for me: simple to code and efficient to use.
My application have to work with objects (of the same type, eg. AAA), and
it creates different collections of them... so I'll have a Collection of
Collections of AAA.
My main needs are: - to work with this main collection in memory and to
persist (serialize) it on disk; - to deserialize from disk into memory;
Another need can be: - to "query" its data (eg. "give me all the
collection in which contained objects has a specified value of a field").
Thank you for you indications.
In NetBeans, how do I remove this red line?
In NetBeans, how do I remove this red line?
I've added the following comment to the start of a java program:
** * * George Tomlinson (I'm not the author). I took this from the
internet and made one correction. * This program converts the string
entered by the user from hexadecimal to ASCII.
*/
The word 'internet' (italicised above but not in the actual program) is
being underlined in red by NetBeans. The error it displays is 'misspelled
word', but it's not misspelled. In Word I would just add it to the
dictionary, but I can't find any such option. Does anyone know how to sort
this out?
You can see a screenshot here:
https://www.facebook.com/photo.php?fbid=10201433173246824&set=a.10201433153846339.1073741827.1099868090&type=3&theater
I've added the following comment to the start of a java program:
** * * George Tomlinson (I'm not the author). I took this from the
internet and made one correction. * This program converts the string
entered by the user from hexadecimal to ASCII.
*/
The word 'internet' (italicised above but not in the actual program) is
being underlined in red by NetBeans. The error it displays is 'misspelled
word', but it's not misspelled. In Word I would just add it to the
dictionary, but I can't find any such option. Does anyone know how to sort
this out?
You can see a screenshot here:
https://www.facebook.com/photo.php?fbid=10201433173246824&set=a.10201433153846339.1073741827.1099868090&type=3&theater
Store javascript variable into array
Store javascript variable into array
Is it possible to store variables into arrays? What is the correct way of
doing it? I can't seem to be able to store it in this way.
var fxVal = '<?php echo $fxVal;?>';
var equitiesVal = '<?php echo $equitiesVal;?>';
var boVal = '<?php echo $boVal;?>';
var balance = '<?php echo $account_balance;?>';
var myData = [fxVal,equitiesVal,boVal,balance];
Is it possible to store variables into arrays? What is the correct way of
doing it? I can't seem to be able to store it in this way.
var fxVal = '<?php echo $fxVal;?>';
var equitiesVal = '<?php echo $equitiesVal;?>';
var boVal = '<?php echo $boVal;?>';
var balance = '<?php echo $account_balance;?>';
var myData = [fxVal,equitiesVal,boVal,balance];
Friday, 30 August 2013
Trouble mixing mod_proxy and mod_cluster
Trouble mixing mod_proxy and mod_cluster
I mod_cluster all traffic to JBoss.
Now, I want to direct /path traffic to an internal apache instance.
I tried simply adding mod_proxy and using ProxyPass / ProxyPassReverse to
send /path traffic to the internal apache, but that only works after I
restart apache and before the jvms check in with it. Then all traffic is
routed to the jvms.
I have also tried adding /path as an excluded context in the jboss console.
Here's VirtualHost:
<VirtualHost [MYIP]:[MYPORT]>
ServerAdmin [MYEMAIL]
DocumentRoot [MYDOCROOT]
ServerName [MYSERVER]
UseAlias 1
ProxyPreserveHost On
ProxyRequests off
ProxyPass /path http://[MY_INTERNAL_APACHE]/
ProxyPassReverse /path http://[MY_INTERNAL_APACHE]/
<Directory [MYDOCROOT]>
Options -FollowSymLinks -Includes -Indexes -MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/[MYLOG].log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/[MYLOG]-access.log combined
</VirtualHost>
Any ideas on how I can have my cake and eat it, too?
I mod_cluster all traffic to JBoss.
Now, I want to direct /path traffic to an internal apache instance.
I tried simply adding mod_proxy and using ProxyPass / ProxyPassReverse to
send /path traffic to the internal apache, but that only works after I
restart apache and before the jvms check in with it. Then all traffic is
routed to the jvms.
I have also tried adding /path as an excluded context in the jboss console.
Here's VirtualHost:
<VirtualHost [MYIP]:[MYPORT]>
ServerAdmin [MYEMAIL]
DocumentRoot [MYDOCROOT]
ServerName [MYSERVER]
UseAlias 1
ProxyPreserveHost On
ProxyRequests off
ProxyPass /path http://[MY_INTERNAL_APACHE]/
ProxyPassReverse /path http://[MY_INTERNAL_APACHE]/
<Directory [MYDOCROOT]>
Options -FollowSymLinks -Includes -Indexes -MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/[MYLOG].log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/[MYLOG]-access.log combined
</VirtualHost>
Any ideas on how I can have my cake and eat it, too?
Thursday, 29 August 2013
XML to text in a JSP
XML to text in a JSP
I need to display the content of an XML file as text, but I don't know how
to simply do that.
The user upload his file and I need to display the content on the page,
but the XML is interpreted.
I've tried this two solutions but it doesn't seem to work:
<iframe id="file" width="800px" height="600px" src="<c:url
value="${fichier}"/>" ></iframe>
and
<pre>
<c:import url="${fichier}"></c:import>
</pre>
Any idea?
I need to display the content of an XML file as text, but I don't know how
to simply do that.
The user upload his file and I need to display the content on the page,
but the XML is interpreted.
I've tried this two solutions but it doesn't seem to work:
<iframe id="file" width="800px" height="600px" src="<c:url
value="${fichier}"/>" ></iframe>
and
<pre>
<c:import url="${fichier}"></c:import>
</pre>
Any idea?
How to remove an element from a dynamically allocated array of objects with operator -= without using std::vectors?
How to remove an element from a dynamically allocated array of objects
with operator -= without using std::vectors?
Overloading the operator -=:
RentACar& operator-=(const Automobile& av)
In RentACar i have a dynamically allocated array of Automobile *a
So lets say that if any a has the same a.brand with av.brand then that a
should be removed and the allocated memory freed for one object.
I thought sth. like if it doesnt find an object with the same brand it
return *this, but if it does, it allocates space for a new automobile
array of size of a-1, assigns objects of, skips the one with the same
brand, but i dont know how to write it.
I don't know how to write with vectors and push back, anyway, i study for
an exam and we never used vectors for whatever reason so i can't use them
on the exam so i must do this even if it is a stupid implementation!
Thanks!
with operator -= without using std::vectors?
Overloading the operator -=:
RentACar& operator-=(const Automobile& av)
In RentACar i have a dynamically allocated array of Automobile *a
So lets say that if any a has the same a.brand with av.brand then that a
should be removed and the allocated memory freed for one object.
I thought sth. like if it doesnt find an object with the same brand it
return *this, but if it does, it allocates space for a new automobile
array of size of a-1, assigns objects of, skips the one with the same
brand, but i dont know how to write it.
I don't know how to write with vectors and push back, anyway, i study for
an exam and we never used vectors for whatever reason so i can't use them
on the exam so i must do this even if it is a stupid implementation!
Thanks!
Wednesday, 28 August 2013
garrys mod entity collision detection?
garrys mod entity collision detection?
Is their a way to get the entity that another touches/collide with? eg. I
throw a can(known prop, prop A) at a door(unknown prop, prop B) and
retrieve the entity object and the point where they first touched? (i'm
trying to make a harpoon for flood mod using hydraulics with a stress
limit and i'm new to lua ) any help? i am intending to use,
function standing on()
local trground = util.TraceLine( util.GetPlayerTrace( player.GetByID(X),
Vector( 0,0,-1 ) ) )
if IsValid( trground.Entity ) then
return trground.Entity
else
return false
end
end
Is their a way to get the entity that another touches/collide with? eg. I
throw a can(known prop, prop A) at a door(unknown prop, prop B) and
retrieve the entity object and the point where they first touched? (i'm
trying to make a harpoon for flood mod using hydraulics with a stress
limit and i'm new to lua ) any help? i am intending to use,
function standing on()
local trground = util.TraceLine( util.GetPlayerTrace( player.GetByID(X),
Vector( 0,0,-1 ) ) )
if IsValid( trground.Entity ) then
return trground.Entity
else
return false
end
end
SyntaxError: unexpected EOF while parsing in Python 3
SyntaxError: unexpected EOF while parsing in Python 3
Code :
n,X=input(),0
for t in range(int(n)):
eval(input())
print(X)
Traceback (most recent call last):
File "prog.py", line 3, in <module>
eval(input())
File "<string>", line 1
X++
^
SyntaxError: unexpected EOF while parsing
Using raw_input instead of input() in the only solution I am able to find
but in python 3.x input is raw_input(): How do I use raw_input in Python
3.1
any other method?
FYI; I am trying to solve: http://codeforces.com/problemset/problem/282/A
Code :
n,X=input(),0
for t in range(int(n)):
eval(input())
print(X)
Traceback (most recent call last):
File "prog.py", line 3, in <module>
eval(input())
File "<string>", line 1
X++
^
SyntaxError: unexpected EOF while parsing
Using raw_input instead of input() in the only solution I am able to find
but in python 3.x input is raw_input(): How do I use raw_input in Python
3.1
any other method?
FYI; I am trying to solve: http://codeforces.com/problemset/problem/282/A
How to post textbox value after selecting particular checkbox
How to post textbox value after selecting particular checkbox
Here is the snippet of html code.....
1)After checking each check box the value's is posting to the database.
2)But the problem is when i checked other, i need to take the value of the
text box and it is posting the value of the checkbox instead of the
textbox value
but i don't know where i did mistake...
<form action="purchase.php" name="form1" id="form1" method="POST">
<ul class="n_ul"> <span>*</span>
What is your Primary goal?
<br>
<br>
<li>
<input name="goal" id="goal" value="Add a popular customer
service to attract/retain more customers"
type="checkbox">
</li> <span>*</span>
Popular customer Services
<br>
<br>
<li>
<input name="goal" id="goal" value="Add a turnkey revenue
sources for my location(s)"
type="checkbox">
</li> <span>*</span>
trunkey revenue source
<br>
<br>
<li>
<input name="goal" id="goal" type="checkbox" value="other">
</li> <span>*</span>
Other (Please specify below)
<br>
<br>
<input name="other" id="goal" type="text" class="new">
</ul>
</form>
Any suggestions are acceptable....
Here is the snippet of html code.....
1)After checking each check box the value's is posting to the database.
2)But the problem is when i checked other, i need to take the value of the
text box and it is posting the value of the checkbox instead of the
textbox value
but i don't know where i did mistake...
<form action="purchase.php" name="form1" id="form1" method="POST">
<ul class="n_ul"> <span>*</span>
What is your Primary goal?
<br>
<br>
<li>
<input name="goal" id="goal" value="Add a popular customer
service to attract/retain more customers"
type="checkbox">
</li> <span>*</span>
Popular customer Services
<br>
<br>
<li>
<input name="goal" id="goal" value="Add a turnkey revenue
sources for my location(s)"
type="checkbox">
</li> <span>*</span>
trunkey revenue source
<br>
<br>
<li>
<input name="goal" id="goal" type="checkbox" value="other">
</li> <span>*</span>
Other (Please specify below)
<br>
<br>
<input name="other" id="goal" type="text" class="new">
</ul>
</form>
Any suggestions are acceptable....
Add elements to Drop down bb 10 cascades
Add elements to Drop down bb 10 cascades
i have a Drop down in Qml file like...
DropDown {
enabled: true
// text only
Option {
text: "EUR/USD"
}
}
and my Database base read function is like... QList
DatabaseOperations::readRecords(QString tableName){
QList<QString> sym_ID_List;
// 1. Get the local DB connection. Note, called database()
// Will automatically open a connection to the database
QSqlDatabase database = QSqlDatabase::database(); // opens the
default database.
// 2. Create a query to search for the records
QSqlQuery query(database);
const QString sqlQuery = "SELECT * FROM "+tableName;
if (query.exec(sqlQuery)) {
// Get the field indexes. We know the order of the fields, and
could skip this step.
// However this will still work if the fi changeldse order in the
query string.
const int customerIDField = query.record().indexOf("SymbolId");
// 3. Start navigating through the records by calling the 'next'
function.
// When there are no longer any records it will return false.
int recordsRead = 0;
while (query.next()) {
// 4. Access the data (stored in the query) via the field
indexes
// and add the data to the model.
sym_ID_List.insert(recordsRead,query.value(1).toString());
recordsRead++;
}
qDebug() << "Read " << recordsRead << " records succeeded";
if (recordsRead == 0) {
// alert(tr("The customer table is empty."));
}
} else {
// alert(tr("Read records failed:
%1").arg(query.lastError().text()));
}
// 6. Optionally close the database connection if we no longer plan
to use it
database.close();
return sym_ID_List;
}
once...this method ie Executed, It returns all the Symbol Id's in an
"Qlist". now my Question is how to Add these "Qlist" elements dynamiccaly
into Drop Down?
How to achive it,
Thanks,
i have a Drop down in Qml file like...
DropDown {
enabled: true
// text only
Option {
text: "EUR/USD"
}
}
and my Database base read function is like... QList
DatabaseOperations::readRecords(QString tableName){
QList<QString> sym_ID_List;
// 1. Get the local DB connection. Note, called database()
// Will automatically open a connection to the database
QSqlDatabase database = QSqlDatabase::database(); // opens the
default database.
// 2. Create a query to search for the records
QSqlQuery query(database);
const QString sqlQuery = "SELECT * FROM "+tableName;
if (query.exec(sqlQuery)) {
// Get the field indexes. We know the order of the fields, and
could skip this step.
// However this will still work if the fi changeldse order in the
query string.
const int customerIDField = query.record().indexOf("SymbolId");
// 3. Start navigating through the records by calling the 'next'
function.
// When there are no longer any records it will return false.
int recordsRead = 0;
while (query.next()) {
// 4. Access the data (stored in the query) via the field
indexes
// and add the data to the model.
sym_ID_List.insert(recordsRead,query.value(1).toString());
recordsRead++;
}
qDebug() << "Read " << recordsRead << " records succeeded";
if (recordsRead == 0) {
// alert(tr("The customer table is empty."));
}
} else {
// alert(tr("Read records failed:
%1").arg(query.lastError().text()));
}
// 6. Optionally close the database connection if we no longer plan
to use it
database.close();
return sym_ID_List;
}
once...this method ie Executed, It returns all the Symbol Id's in an
"Qlist". now my Question is how to Add these "Qlist" elements dynamiccaly
into Drop Down?
How to achive it,
Thanks,
Tuesday, 27 August 2013
Recover deleted file from linode VPS server with Ubuntu 12.04
Recover deleted file from linode VPS server with Ubuntu 12.04
I have accidentally deleted files from my VPS server bought from Linode.
It uses Ubuntu 12.04. How can I recover the files. I hadn't enabled backup
for it.
I have accidentally deleted files from my VPS server bought from Linode.
It uses Ubuntu 12.04. How can I recover the files. I hadn't enabled backup
for it.
Subversion and source not committed in Delphi XE2
Subversion and source not committed in Delphi XE2
I have installed the latest release of Subversion following these
instructions http://www.drbob42.com/examines/examinD3.htm successfully.
Then I installed the Delphi IDE integration too.
If I open a Delphi project, right click on the Project Manager in the
Delphi IDE and choose "Tortoise SVN" and then "Repository browser" I can
see all the files in my project in the local repository.
At that stage I added one instruction line in my application source, saved
and then tried to commit. The SVN commit form shows up but it says "No
files were changed since the last commit. There is nothing for TortoiseSVN
to do here". As I just changed the source of my application I was
expecting SVN showing that. Why isn't this happening ?
I chose the option cleanup and the error message says "Cleanup failed to
process the following paths..... is not a working directory
Thanks
I have installed the latest release of Subversion following these
instructions http://www.drbob42.com/examines/examinD3.htm successfully.
Then I installed the Delphi IDE integration too.
If I open a Delphi project, right click on the Project Manager in the
Delphi IDE and choose "Tortoise SVN" and then "Repository browser" I can
see all the files in my project in the local repository.
At that stage I added one instruction line in my application source, saved
and then tried to commit. The SVN commit form shows up but it says "No
files were changed since the last commit. There is nothing for TortoiseSVN
to do here". As I just changed the source of my application I was
expecting SVN showing that. Why isn't this happening ?
I chose the option cleanup and the error message says "Cleanup failed to
process the following paths..... is not a working directory
Thanks
custom query for both category and pages using global $wpdb;
custom query for both category and pages using global $wpdb;
I have a custom query returning categories, but I also need to return some
pages with a particular post ids. How would I add those? They obviously
have no taxonomy and are page post types.
Below is my query so far:
protected function _getPostByCategory($category) {
global $wpdb;
$result = $wpdb->get_results(" SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID =
$wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy
ON($wpdb->term_relationships.term_taxonomy_id =
$wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id =
$wpdb->terms.term_id)
WHERE $wpdb->terms.name = '$category'
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.post_date DESC");
I have a custom query returning categories, but I also need to return some
pages with a particular post ids. How would I add those? They obviously
have no taxonomy and are page post types.
Below is my query so far:
protected function _getPostByCategory($category) {
global $wpdb;
$result = $wpdb->get_results(" SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID =
$wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy
ON($wpdb->term_relationships.term_taxonomy_id =
$wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id =
$wpdb->terms.term_id)
WHERE $wpdb->terms.name = '$category'
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.post_date DESC");
How to return a string-literal from a std::string?
How to return a string-literal from a std::string?
I have a requirement to manipulate a const char* and to return a new const
char*.
i.e If user gives " someThing ", the function should trim the spaces and
return "someThing".
const char* foo (" someThing ") {
// some logic ..;
return "someThing";
}
The following works, but valgrind barfs stating "Invalid Read of size 1".
size_t trim (char*& str)
{
char *c = str;
// empty-string, no input given.
if (!str)
{
return 0;
}
// remove all leading whitespaces
while (isspace(*c))
{
c++;
}
str = c;
c = str + strlen(str) - 1;
// remove the trailing spaces
while (isspace(*c))
{
c--;
}
*(c+1) = '\0';
return strlen(str);
}
const char* foo (const char* str)
{
// copying to char* ... to modify
char *copy = new char[strlen(str) + 1];
strncpy (copy, str, strlen(str));
copy [strlen(str)] = '\0';
// modify ... remove the spaces
trim(copy);
// Intend to return "copy" as String-Literal
// How to make sure that copy is stored as string-literal ?
std::string ret (copy);
// Avoid memory-leaks
delete [] copy;
copy = 0;
// Am i really returning string-literal ??
// or
// Will it be an invalid Pointer
return ret.c_str();
}
// Usage is like
class Bar {
public :
Bar (const char* str) : expr (foo(str)) {
// EMPTY BODY
}
private :
std::string expr;
};
string.c_str() returns a pointer to the std::string internal buffer. For
different user-inputs, i wanted foo() to create string-literals.
When i debug, found out that the memory for return string is allocated on
HEAP. Donno whether this behaviour is platform (RHEL 5.4) or compiler
specific (gcc 4.1.2).
Since the return-string (from foo()) will be out-of-scope once the
function call is over, the valgrind-log "INVALID READ OF SIZE 1" seems to
be reasonable.
Q1) Is the (above) method proper to achieve the objective ? (objective :
modify user-input if required and return string-literal)
Q2) How to make sure that string/string.c_str() returns a string-literal ?
Q3) Is there any other effective way to do the same ?
I have a requirement to manipulate a const char* and to return a new const
char*.
i.e If user gives " someThing ", the function should trim the spaces and
return "someThing".
const char* foo (" someThing ") {
// some logic ..;
return "someThing";
}
The following works, but valgrind barfs stating "Invalid Read of size 1".
size_t trim (char*& str)
{
char *c = str;
// empty-string, no input given.
if (!str)
{
return 0;
}
// remove all leading whitespaces
while (isspace(*c))
{
c++;
}
str = c;
c = str + strlen(str) - 1;
// remove the trailing spaces
while (isspace(*c))
{
c--;
}
*(c+1) = '\0';
return strlen(str);
}
const char* foo (const char* str)
{
// copying to char* ... to modify
char *copy = new char[strlen(str) + 1];
strncpy (copy, str, strlen(str));
copy [strlen(str)] = '\0';
// modify ... remove the spaces
trim(copy);
// Intend to return "copy" as String-Literal
// How to make sure that copy is stored as string-literal ?
std::string ret (copy);
// Avoid memory-leaks
delete [] copy;
copy = 0;
// Am i really returning string-literal ??
// or
// Will it be an invalid Pointer
return ret.c_str();
}
// Usage is like
class Bar {
public :
Bar (const char* str) : expr (foo(str)) {
// EMPTY BODY
}
private :
std::string expr;
};
string.c_str() returns a pointer to the std::string internal buffer. For
different user-inputs, i wanted foo() to create string-literals.
When i debug, found out that the memory for return string is allocated on
HEAP. Donno whether this behaviour is platform (RHEL 5.4) or compiler
specific (gcc 4.1.2).
Since the return-string (from foo()) will be out-of-scope once the
function call is over, the valgrind-log "INVALID READ OF SIZE 1" seems to
be reasonable.
Q1) Is the (above) method proper to achieve the objective ? (objective :
modify user-input if required and return string-literal)
Q2) How to make sure that string/string.c_str() returns a string-literal ?
Q3) Is there any other effective way to do the same ?
Excel: Search and Replace based on Rules
Excel: Search and Replace based on Rules
I have a list in Excel more than 3000 rows that I would like to research
and replace some words within the list based on another list.
For example:
List 1:
Blackcurrant Juice 500ml
Strawberry Juice 750ml
List 2:
have two columns (a: the word that I want to replace, b: the word that I
want to replace with)
A: Blackcurrant should be B: B/currant
A: Strawberry should be B: Strawb
And I want search in list 1 and replace the some word based on List two
Any ideas?
I have a list in Excel more than 3000 rows that I would like to research
and replace some words within the list based on another list.
For example:
List 1:
Blackcurrant Juice 500ml
Strawberry Juice 750ml
List 2:
have two columns (a: the word that I want to replace, b: the word that I
want to replace with)
A: Blackcurrant should be B: B/currant
A: Strawberry should be B: Strawb
And I want search in list 1 and replace the some word based on List two
Any ideas?
VMware OS had Password Encryption and After Converting to VDI , it Gives Fatal Error
VMware OS had Password Encryption and After Converting to VDI , it Gives
Fatal Error
I had Ubuntu installed in vmware [Host OS = Windows 8], now I have removed
windows 8 and am in Ubuntu as Host OS and have Virtual Box.
I did conversion from vmdk to vdi, but now, while accessing VDI it gives
Fatal Error, as No Bootable media found, it doesn't even ask password.
Is there any way, i can login to my VM Ubuntu machine via virtualbox. It
has lots of my business confidential data and i don't want to loose them.
Thanks
Fatal Error
I had Ubuntu installed in vmware [Host OS = Windows 8], now I have removed
windows 8 and am in Ubuntu as Host OS and have Virtual Box.
I did conversion from vmdk to vdi, but now, while accessing VDI it gives
Fatal Error, as No Bootable media found, it doesn't even ask password.
Is there any way, i can login to my VM Ubuntu machine via virtualbox. It
has lots of my business confidential data and i don't want to loose them.
Thanks
Monday, 26 August 2013
Repeat some operation in the same column
Repeat some operation in the same column
I'm new to excel. I want to subtract All element of A from I1 and then
divide it by J1. So, I use =(A1-l1)/j1 and then paste the same operation
for other element but it doesn't work and the operation convert to
=(A2-l2)/j2 and =(A3-l3)/j3 ...but I want =(A2-l1)/j1 and =(A3-l1)/j1 what
should I do?
Thanks.
I'm new to excel. I want to subtract All element of A from I1 and then
divide it by J1. So, I use =(A1-l1)/j1 and then paste the same operation
for other element but it doesn't work and the operation convert to
=(A2-l2)/j2 and =(A3-l3)/j3 ...but I want =(A2-l1)/j1 and =(A3-l1)/j1 what
should I do?
Thanks.
NoSuchMethodError in OSX but not Ubuntu
NoSuchMethodError in OSX but not Ubuntu
I have a class that calls methods from another class. I compiled and ran
it on Ubuntu 13.04 and it runs fine. On OSX 10.8.4, I get the following
output:
Exception in thread "main" java.lang.NoSuchMethodError:
Complex.equals(LComplex;)Z at ComplexTester.main(ComplexTester.java:11)
I tried running it in Eclipse, Netbeans and terminal and I get the same
output. Any help would be greatly appreciated.
public class Complex {
private double real;
private double imaginary;
/**
*
* @param real the real part of the Complex number
* @param imaginary the imaginary part of the Complex number
*/
public Complex(double newReal,double newImaginary){
real=newReal;
imaginary=newImaginary;
}
/**
*
* @return the real part of the Complex number
*/
public double getReal(){
return real;
}
/**
*
* @return the imaginary part of the complex number
*/
public double getImaginary(){
return imaginary;
}
/**
* gives real a new value
* @param newReal the new value of real
*/
public void setReal(double newReal){
real=newReal;
}
/**
* gives imaginary a new value
* @param newImaginary the new value of Imaginary
*/
public void setImaginary(double newImaginary){
imaginary=newImaginary;
}
/**
*
* @param x the new Complex object whose instance variables must be added
to the old one
* @return a new Complex object that is a combination of the parameters of
both Complex objects
*/
public Complex add(Complex x){
Complex result=new Complex(x.getReal()+real,x.getImaginary()+imaginary);
return result;
}
/**
*
* @param other the Complex object being compared
* @return true if both Complex objects have the same imaginary and real
parts
*/
public boolean equals(Complex other){
return other.getImaginary()==imaginary && other.getReal()==real;
}
}
public class ComplexTester {
public static void main(String[] args){
Complex x=new Complex(23.2,33.1);
Complex y=new Complex(23.2,33.1);
//test the equals method
System.out.println(x.equals(y));
System.out.println("Expected: True");
//test the setImaginary() and setReal() methods
x.setImaginary(2);
x.setReal(5);
//test the getImaginary() and getReal() methods
System.out.println(x.getImaginary());
System.out.println("Expected: 2");
System.out.println(x.getReal());
System.out.println("Expected: 5");
//test the equals method again
System.out.println(x.equals(y));
System.out.println("Expected: False");
//test the add method
Complex added=x.add(y);
System.out.println(added.getReal());
System.out.println("Expected: 28.2");
System.out.println(added.getImaginary());
System.out.println("Expected: 35.1");
}
}
I have a class that calls methods from another class. I compiled and ran
it on Ubuntu 13.04 and it runs fine. On OSX 10.8.4, I get the following
output:
Exception in thread "main" java.lang.NoSuchMethodError:
Complex.equals(LComplex;)Z at ComplexTester.main(ComplexTester.java:11)
I tried running it in Eclipse, Netbeans and terminal and I get the same
output. Any help would be greatly appreciated.
public class Complex {
private double real;
private double imaginary;
/**
*
* @param real the real part of the Complex number
* @param imaginary the imaginary part of the Complex number
*/
public Complex(double newReal,double newImaginary){
real=newReal;
imaginary=newImaginary;
}
/**
*
* @return the real part of the Complex number
*/
public double getReal(){
return real;
}
/**
*
* @return the imaginary part of the complex number
*/
public double getImaginary(){
return imaginary;
}
/**
* gives real a new value
* @param newReal the new value of real
*/
public void setReal(double newReal){
real=newReal;
}
/**
* gives imaginary a new value
* @param newImaginary the new value of Imaginary
*/
public void setImaginary(double newImaginary){
imaginary=newImaginary;
}
/**
*
* @param x the new Complex object whose instance variables must be added
to the old one
* @return a new Complex object that is a combination of the parameters of
both Complex objects
*/
public Complex add(Complex x){
Complex result=new Complex(x.getReal()+real,x.getImaginary()+imaginary);
return result;
}
/**
*
* @param other the Complex object being compared
* @return true if both Complex objects have the same imaginary and real
parts
*/
public boolean equals(Complex other){
return other.getImaginary()==imaginary && other.getReal()==real;
}
}
public class ComplexTester {
public static void main(String[] args){
Complex x=new Complex(23.2,33.1);
Complex y=new Complex(23.2,33.1);
//test the equals method
System.out.println(x.equals(y));
System.out.println("Expected: True");
//test the setImaginary() and setReal() methods
x.setImaginary(2);
x.setReal(5);
//test the getImaginary() and getReal() methods
System.out.println(x.getImaginary());
System.out.println("Expected: 2");
System.out.println(x.getReal());
System.out.println("Expected: 5");
//test the equals method again
System.out.println(x.equals(y));
System.out.println("Expected: False");
//test the add method
Complex added=x.add(y);
System.out.println(added.getReal());
System.out.println("Expected: 28.2");
System.out.println(added.getImaginary());
System.out.println("Expected: 35.1");
}
}
Add field to Devise user registration
Add field to Devise user registration
I use Devise with my Ruby on Rails 4 application for user
authentication/registration. I want to add one more field to my user
registration form called nickname. Adding this field to the views is
straight forward, but what's the best way to go ahead and ensure that
Devise ensures that it persists to the model and doesn't reject this
attribute as it is non-standard for it is built for?
I use Devise with my Ruby on Rails 4 application for user
authentication/registration. I want to add one more field to my user
registration form called nickname. Adding this field to the views is
straight forward, but what's the best way to go ahead and ensure that
Devise ensures that it persists to the model and doesn't reject this
attribute as it is non-standard for it is built for?
How to insert a date that is 1 month prior to an existing date in Sybase Advantage Database using SQL?
How to insert a date that is 1 month prior to an existing date in Sybase
Advantage Database using SQL?
I have been asked to fill a field with date that is 1 month prior to a
date in a another field in our database. This would be like if the date is
1/16/13 I would then input into the new field the date of 12/16/12. The
issue that I ran into is that some functions that are normal to native SQL
databases do not exist in the same capacity in the Sybase Advantage
Database I am using. DATEADD for instance is not available from what I
have experienced thus far. So I have used the semi equivalent timestampadd
function. I started getting an error right when I thought I had it figured
out so here is where I feel the issue is, but I do not know what the issue
is:
INSERT INTO Normalization (memotext)
SELECT timestampadd(sql_tsi_month, -1, memotext)
FROM eqanswer
WHERE entityrole='MTG_PROP_FIGS'
and fieldnum=22
;
I keep getting this error: ERROR IN SCRIPT: poQuery: Error 7200: AQE
Error: State = S0000; NativeError = 2124; [iAnywhere Solutions][Advantage
SQL Engine]Invalid operand for operator:
Any help would be greatly appreciated! Thanks!
Advantage Database using SQL?
I have been asked to fill a field with date that is 1 month prior to a
date in a another field in our database. This would be like if the date is
1/16/13 I would then input into the new field the date of 12/16/12. The
issue that I ran into is that some functions that are normal to native SQL
databases do not exist in the same capacity in the Sybase Advantage
Database I am using. DATEADD for instance is not available from what I
have experienced thus far. So I have used the semi equivalent timestampadd
function. I started getting an error right when I thought I had it figured
out so here is where I feel the issue is, but I do not know what the issue
is:
INSERT INTO Normalization (memotext)
SELECT timestampadd(sql_tsi_month, -1, memotext)
FROM eqanswer
WHERE entityrole='MTG_PROP_FIGS'
and fieldnum=22
;
I keep getting this error: ERROR IN SCRIPT: poQuery: Error 7200: AQE
Error: State = S0000; NativeError = 2124; [iAnywhere Solutions][Advantage
SQL Engine]Invalid operand for operator:
Any help would be greatly appreciated! Thanks!
Wireless network suddenly not working on 13.04
Wireless network suddenly not working on 13.04
I installed Ubuntu 13.04 few days ago and it worked fine. I did some
tweaks with my ssd and other things including wlan cards power management.
I'm afraid i did something wrong while tweaking because tonight when i
booted the computer again, wireless network didn't work any more.
I'm not new with ubuntu but I've never learned much about the system so I
don't even know what codes to include in this message. Driver is Broadcom
BCM43228 and it's ticked in software & updates
iwconfig:
eth0 no wireless extensions.
eth1 IEEE 802.11abg ESSID:off/any
Mode:Managed Access Point: Not-Associated
Retry long limit:7 RTS thr:off Fragment thr:off
Power Management:off
lo no wireless extensions.
I installed Ubuntu 13.04 few days ago and it worked fine. I did some
tweaks with my ssd and other things including wlan cards power management.
I'm afraid i did something wrong while tweaking because tonight when i
booted the computer again, wireless network didn't work any more.
I'm not new with ubuntu but I've never learned much about the system so I
don't even know what codes to include in this message. Driver is Broadcom
BCM43228 and it's ticked in software & updates
iwconfig:
eth0 no wireless extensions.
eth1 IEEE 802.11abg ESSID:off/any
Mode:Managed Access Point: Not-Associated
Retry long limit:7 RTS thr:off Fragment thr:off
Power Management:off
lo no wireless extensions.
Remove html table row using javascript or jquery?
Remove html table row using javascript or jquery?
I have a dynamic table in my html form that has functionality to add/drop
rows. The name of each element has a number appended to the end of it
specifying the row number (e.g. ID.0 , ID.1 , etc.). I have written this
function to attempt to remove each row as well as update the name of each
element:
function remove() {
var theName=getItemNames();
var counter=theName.length;
var index=0;
f.preventDefault();
$(this).parents("tr").remove();
counter--;
$('input[name*="Id."]').each(function() {
$(this).attr("name", "Id."+index);
index++;
});
$('input[name*="Date."]').each(function() {
$(this).attr("name", "Date."+index);
index++;
});
$('input[name*="Value."]').each(function() {
$(this).attr("name", "Value."+index);
index++;
});
$('input[name*="Required."]').each(function() {
$(this).attr("name", "Required."+index);
index++;
});
}
This, however, removes only the remove button and not the entire row as I
expected it to. Can anyone see what I'm doing wrong?
I have a dynamic table in my html form that has functionality to add/drop
rows. The name of each element has a number appended to the end of it
specifying the row number (e.g. ID.0 , ID.1 , etc.). I have written this
function to attempt to remove each row as well as update the name of each
element:
function remove() {
var theName=getItemNames();
var counter=theName.length;
var index=0;
f.preventDefault();
$(this).parents("tr").remove();
counter--;
$('input[name*="Id."]').each(function() {
$(this).attr("name", "Id."+index);
index++;
});
$('input[name*="Date."]').each(function() {
$(this).attr("name", "Date."+index);
index++;
});
$('input[name*="Value."]').each(function() {
$(this).attr("name", "Value."+index);
index++;
});
$('input[name*="Required."]').each(function() {
$(this).attr("name", "Required."+index);
index++;
});
}
This, however, removes only the remove button and not the entire row as I
expected it to. Can anyone see what I'm doing wrong?
How to change Edit control background color in FireMonkey XE4 for Mobile Application?
How to change Edit control background color in FireMonkey XE4 for Mobile
Application?
I just can't find a way of changing background color of Edit control in my
mobile FireMonkey application.
Application?
I just can't find a way of changing background color of Edit control in my
mobile FireMonkey application.
How to easily and completely disable/enable WLAN (so it cannot be turned on again while travelling)=?iso-8859-1?Q?=3F_=96_apple.stackexchange.com?=
How to easily and completely disable/enable WLAN (so it cannot be turned
on again while travelling)? – apple.stackexchange.com
Without going into specifics of why I might like to do this, or whether
this is a good idea or not, I would like to know how I can disable use of
wireless networking on my MacBook Air, either via ...
on again while travelling)? – apple.stackexchange.com
Without going into specifics of why I might like to do this, or whether
this is a good idea or not, I would like to know how I can disable use of
wireless networking on my MacBook Air, either via ...
Currency class only one instance per currency?
Currency class only one instance per currency?
From this official oracle java tutorial:
Note that the Currency class is designed so that there is never more than
one Currency instance for any given currency. Therefore, there is no
public constructor. As demonstrated in the previous code example, you
obtain a Currency instance using the getInstance methods.
What is the risk of having more than one instance of Currency for a given
currency? Thanks in advance.
From this official oracle java tutorial:
Note that the Currency class is designed so that there is never more than
one Currency instance for any given currency. Therefore, there is no
public constructor. As demonstrated in the previous code example, you
obtain a Currency instance using the getInstance methods.
What is the risk of having more than one instance of Currency for a given
currency? Thanks in advance.
Sunday, 25 August 2013
How to make a new android project
How to make a new android project
I am getting a peculiar error while building my project. At last step from
make a new android project 'activity not found' and I have just a blank
box please help me I have already check my SDK and ADT.
run-run configuration-general - checked 'launch default activity'
I am getting a peculiar error while building my project. At last step from
make a new android project 'activity not found' and I have just a blank
box please help me I have already check my SDK and ADT.
run-run configuration-general - checked 'launch default activity'
Jquery Generate random number pass to if
Jquery Generate random number pass to if
I'm trying to create a random number in Jquery I'm not sure if I need to
store it to do the next part maybe you guys could help me out on that
first off my random number generator;
$( "#arrowleftup" ).click(function() {
var number = 1 + Math.floor(Math.random() * 10);
$('#storenumber').text(number);
});
I want to generate a random number when my Img with the id "arrowleftup"
is clicked, I then want to pass my number into this -
If ('#storenumber' == 8=>){
$('.battle').show();
} else {
die
};
So that if the number was 8 or higher it would show a hidden div, can
anyone spot the error in my code? Also do I need to store the value to
pass it into the if statement
JSFiddle - http://jsfiddle.net/7t59E/
thanks!
I'm trying to create a random number in Jquery I'm not sure if I need to
store it to do the next part maybe you guys could help me out on that
first off my random number generator;
$( "#arrowleftup" ).click(function() {
var number = 1 + Math.floor(Math.random() * 10);
$('#storenumber').text(number);
});
I want to generate a random number when my Img with the id "arrowleftup"
is clicked, I then want to pass my number into this -
If ('#storenumber' == 8=>){
$('.battle').show();
} else {
die
};
So that if the number was 8 or higher it would show a hidden div, can
anyone spot the error in my code? Also do I need to store the value to
pass it into the if statement
JSFiddle - http://jsfiddle.net/7t59E/
thanks!
How do I display a route parameter?
How do I display a route parameter?
I'm trying to understand Ember. I can't quite work it out. I currently
have the routes:
/participants
/list
/search/:query
And I'm trying to figure out how to get my search page to display that
query parameter. The navigation works, I just can't figure out how to
display that "query" bit (ie, "You searched for Bennie")
(One thing I tried is that I have an App.ParticipantsSearchController with
a 'searchtext' in it, and I know I can display that with {{searchtext}} in
the template, but even if I try to later do an
App.ParticipantsSearchController.searchtext = 'abc', that doesn't get
updated. So that doesn't seem to do me any good.)
I would really appreciate the help from somebody who understands Ember
better than I do.
I'm trying to understand Ember. I can't quite work it out. I currently
have the routes:
/participants
/list
/search/:query
And I'm trying to figure out how to get my search page to display that
query parameter. The navigation works, I just can't figure out how to
display that "query" bit (ie, "You searched for Bennie")
(One thing I tried is that I have an App.ParticipantsSearchController with
a 'searchtext' in it, and I know I can display that with {{searchtext}} in
the template, but even if I try to later do an
App.ParticipantsSearchController.searchtext = 'abc', that doesn't get
updated. So that doesn't seem to do me any good.)
I would really appreciate the help from somebody who understands Ember
better than I do.
Saturday, 24 August 2013
how to install libglade2-0
how to install libglade2-0
I'm trying to install a Canon MF4450 printer from a network to Ubuntu . I
have a driver file from Canon website
Linux_UFRII_PrinterDriver_V270_us_EN.tar.gz. Two *.deb files are contained
in the original file. The Printer installer is asking me a PPD file format
to be chosen in driver file selection. I'm using:
/folder$ sudo dpkg -i file_name.deb
command in the terminal and it is a dependency problem on libglade2-0 -
this package is not installed. How can I install this package?
I'm trying to install a Canon MF4450 printer from a network to Ubuntu . I
have a driver file from Canon website
Linux_UFRII_PrinterDriver_V270_us_EN.tar.gz. Two *.deb files are contained
in the original file. The Printer installer is asking me a PPD file format
to be chosen in driver file selection. I'm using:
/folder$ sudo dpkg -i file_name.deb
command in the terminal and it is a dependency problem on libglade2-0 -
this package is not installed. How can I install this package?
How to get the last row using MYSQL GROUP BY
How to get the last row using MYSQL GROUP BY
have two tables, table sets and chapters with MySQL table:
Table Series
ID_SERIES
NAME
DESCRIPTION
Table Chapters
ID_CHAPTERS
ID_SERIES
VIDEO
DATE_CREATED
As I can group all the chapters by id and give me back that I return in
the last chapter, that way I do this query ?
thanks for reading.
have two tables, table sets and chapters with MySQL table:
Table Series
ID_SERIES
NAME
DESCRIPTION
Table Chapters
ID_CHAPTERS
ID_SERIES
VIDEO
DATE_CREATED
As I can group all the chapters by id and give me back that I return in
the last chapter, that way I do this query ?
thanks for reading.
Filtering the result of the find command, so that it returns only directories
Filtering the result of the find command, so that it returns only directories
Is it possible to get only the results from find that are directory paths?
Using find with some option, or using grep or some other utility the
results are piped into as a filter?
I thought something like find | grep */$ might work, but it doesn't. From
some other testing where I "grepped for" a folder with a specific name it
seems like I get a hit for folder_name$ but not for folder_name/$. This
seems conterintuitive. How can I grep for lines that end with /?
Is it possible to get only the results from find that are directory paths?
Using find with some option, or using grep or some other utility the
results are piped into as a filter?
I thought something like find | grep */$ might work, but it doesn't. From
some other testing where I "grepped for" a folder with a specific name it
seems like I get a hit for folder_name$ but not for folder_name/$. This
seems conterintuitive. How can I grep for lines that end with /?
Java generic SOAP client lib
Java generic SOAP client lib
I wanna consume some web services, but I don't wanna use any method where
eclipse or other code generation mechanism to generate any SOAP client
classes for me.
I want something similar to ksoap (the one I used a loooong time ago when
playing with J2ME), which enable me (freely) to create a SOAP request and
parse SOAP response, without the need of using generated client codes.
Any suggestion will be appreciated.
Thanks in advance, Bromo
I wanna consume some web services, but I don't wanna use any method where
eclipse or other code generation mechanism to generate any SOAP client
classes for me.
I want something similar to ksoap (the one I used a loooong time ago when
playing with J2ME), which enable me (freely) to create a SOAP request and
parse SOAP response, without the need of using generated client codes.
Any suggestion will be appreciated.
Thanks in advance, Bromo
Javascript setTimeout(); for ProgressBar doesn't work
Javascript setTimeout(); for ProgressBar doesn't work
On my website I have a progressbar and when I click the Download button,
the progressbar starts. By the way I want it to progress a bit slowly, so
I thought I could use setTimeout();.
http://jsfiddle.net/pHxSy/9/
If you look at that jsfiddle, when you click the Download button anything
happens. I've tested it on firefox and the console tells me
ReferenceError: startTime is not defined.
How could I fix this?
On my website I have a progressbar and when I click the Download button,
the progressbar starts. By the way I want it to progress a bit slowly, so
I thought I could use setTimeout();.
http://jsfiddle.net/pHxSy/9/
If you look at that jsfiddle, when you click the Download button anything
happens. I've tested it on firefox and the console tells me
ReferenceError: startTime is not defined.
How could I fix this?
Unable to install ruby on ubuntu 12.04
Unable to install ruby on ubuntu 12.04
Hi i want to install ruby on my Ubuntu 12.04. I tried it with following
command sudo apt-get install curl but it gives me following error.
The hostname -f command returned: $1
Your system needs to have a fully qualified domain name (fqdn) in
order to install the var-qmail packages.
Installation aborted.
dpkg: error processing qmail (--configure):
subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of qmail-run:
qmail-run depends on qmail (>= 1.06-2.1); however:
Package qmail is not configured yet.
dpkg: error processing qmail-run (--configure):
dependency problems - leaving unconfigured
No apport report written because the error message indicates its a
followup error from a previous failure.
Errors
were
encountered
while
processing:
qmail
qmail-run
E: Sub-process /usr/bin/dpkg returned an error code (1)
How to solve this error. Need Help. I am using ubuntu 12.04
Hi i want to install ruby on my Ubuntu 12.04. I tried it with following
command sudo apt-get install curl but it gives me following error.
The hostname -f command returned: $1
Your system needs to have a fully qualified domain name (fqdn) in
order to install the var-qmail packages.
Installation aborted.
dpkg: error processing qmail (--configure):
subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of qmail-run:
qmail-run depends on qmail (>= 1.06-2.1); however:
Package qmail is not configured yet.
dpkg: error processing qmail-run (--configure):
dependency problems - leaving unconfigured
No apport report written because the error message indicates its a
followup error from a previous failure.
Errors
were
encountered
while
processing:
qmail
qmail-run
E: Sub-process /usr/bin/dpkg returned an error code (1)
How to solve this error. Need Help. I am using ubuntu 12.04
Friday, 23 August 2013
parallax change text effects
parallax change text effects
I've been exploring Adobe Muse but I'm not very good with jQuery/JS. I'm
trying to recreate an effect where when scrolling a text is changing.
<script type="text/javascript">
$(document).ready(function() { try {
Muse.Utils.transformMarkupToFixBrowserProblemsPreInit();/* body */
Muse.Utils.prepHyperlinks();/* body */
$('#u74').registerPositionScrollEffect({"offset":-101,"speedX":0,"speedY":0.8});/*
scroll effect */
$('#u79-4').registerPositionScrollEffect({"exitSpeedY":1,"offset":169.85000000000002,"enterSpeedX":0,"enterSpeedY":0.7,"exitSpeedX":0});/*
scroll effect */
$('#u83').registerPositionScrollEffect({"offset":703.35,"speedX":0,"speedY":0.4});/*
scroll effect */
Muse.Utils.fullPage('#page');/* 100% height page */
Muse.Utils.showWidgetsWhenReady();/* body */
Muse.Utils.transformMarkupToFixBrowserProblems();/* body */
} catch(e) { Muse.Assert.fail('Error calling selector function:' + e); }});
</script>
<script>
$(window).bind('scroll',function(e){
parallaxScroll();
});
function parallaxScroll(){
var scrolled = $(window).scrollTop();
$('#u-test').text((0+(scrolled)));
}
</script>
function parallaxScroll() does what I want, it is just that it is not
bound to the actual scroll of the text in question, which is
$('#u83').registerPositionScrollEffect
Where should i put this piece of code in order to get the correct value
based on the parallax offset?
Here is the piece of html that drives this
<div class="clearfix" id="page"><!-- group -->
<div class="se_invi" id="u74"><!-- image -->
<img class="block" id="u74_img" src="images/test.jpg" alt=""
width="1383" height="2048"/>
</div>
<div class="clearfix se_invi" id="u79-4"><!-- content -->
<p>This is an AMAZING EXPERIENCE</p>
</div>
<div class="clearfix se_invi" id="u83"><!-- group -->
<div class="clearfix grpelem" id="u81-6"><!-- content -->
<p id="u81-2">PERCENTAGE</p>
<p id="u81-4">%</p>
</div>
<div class="clearfix grpelem" id="u82-4"><!-- content -->
<p id="u-test" style="width: 500px;">0</p>
</div>
</div>
<div class="verticalspacer"></div>
I've been exploring Adobe Muse but I'm not very good with jQuery/JS. I'm
trying to recreate an effect where when scrolling a text is changing.
<script type="text/javascript">
$(document).ready(function() { try {
Muse.Utils.transformMarkupToFixBrowserProblemsPreInit();/* body */
Muse.Utils.prepHyperlinks();/* body */
$('#u74').registerPositionScrollEffect({"offset":-101,"speedX":0,"speedY":0.8});/*
scroll effect */
$('#u79-4').registerPositionScrollEffect({"exitSpeedY":1,"offset":169.85000000000002,"enterSpeedX":0,"enterSpeedY":0.7,"exitSpeedX":0});/*
scroll effect */
$('#u83').registerPositionScrollEffect({"offset":703.35,"speedX":0,"speedY":0.4});/*
scroll effect */
Muse.Utils.fullPage('#page');/* 100% height page */
Muse.Utils.showWidgetsWhenReady();/* body */
Muse.Utils.transformMarkupToFixBrowserProblems();/* body */
} catch(e) { Muse.Assert.fail('Error calling selector function:' + e); }});
</script>
<script>
$(window).bind('scroll',function(e){
parallaxScroll();
});
function parallaxScroll(){
var scrolled = $(window).scrollTop();
$('#u-test').text((0+(scrolled)));
}
</script>
function parallaxScroll() does what I want, it is just that it is not
bound to the actual scroll of the text in question, which is
$('#u83').registerPositionScrollEffect
Where should i put this piece of code in order to get the correct value
based on the parallax offset?
Here is the piece of html that drives this
<div class="clearfix" id="page"><!-- group -->
<div class="se_invi" id="u74"><!-- image -->
<img class="block" id="u74_img" src="images/test.jpg" alt=""
width="1383" height="2048"/>
</div>
<div class="clearfix se_invi" id="u79-4"><!-- content -->
<p>This is an AMAZING EXPERIENCE</p>
</div>
<div class="clearfix se_invi" id="u83"><!-- group -->
<div class="clearfix grpelem" id="u81-6"><!-- content -->
<p id="u81-2">PERCENTAGE</p>
<p id="u81-4">%</p>
</div>
<div class="clearfix grpelem" id="u82-4"><!-- content -->
<p id="u-test" style="width: 500px;">0</p>
</div>
</div>
<div class="verticalspacer"></div>
how can I get faster FTS4 query results ordered by a field in another table?
how can I get faster FTS4 query results ordered by a field in another table?
Background
I'm implementing full-text search over a body of email messages stored in
SQLite, making use of its fantastic built-in FTS4 engine. I'm getting some
rather poor query performance, although not exactly where I would expect.
Let's take a look.
Representative schema
I'll give some simplified examples of the code in question, with links to
the full code where applicable.
We've got a MessageTable that stores the data about an email message (full
version spread out over several files here, here, and here):
CREATE TABLE MessageTable (
id INTEGER PRIMARY KEY,
internaldate_time_t INTEGER
);
CREATE INDEX MessageTableInternalDateTimeTIndex
ON MessageTable(internaldate_time_t);
The searchable text is added to an FTS4 table named MessageSearchTable
(full version here):
CREATE VIRTUAL TABLE MessageSearchTable USING fts4(
id INTEGER PRIMARY KEY,
body
);
The id in the search table acts as a foreign key to the message table.
I'll leave it as an exercise for the reader to insert data into these
tables (I certainly can't give out my private email). I have just under
26k records in each table.
Problem query
When we retrieve search results, we need them to be ordered descending by
internaldate_time_t so we can pluck out only the most recent few results.
Here's an example search query (full version here):
SELECT id
FROM MessageSearchTable
JOIN MessageTable USING (id)
WHERE MessageSearchTable MATCH 'a'
ORDER BY internaldate_time_t DESC
LIMIT 10 OFFSET 0
On my machine, with my email, that runs in about 150 milliseconds, as
measured via:
time sqlite3 test.db <<<"..." > /dev/null
150 milliseconds is no beast of a query, but for a simple FTS lookup and
indexed order, it's sluggish. If I omit the ORDER BY, it completes in 10
milliseconds, for example. Also keep in mind that the actual query has one
more sub-select, so there's a little more work going on in general: the
full version of the query runs in about 600 milliseconds, which is into
beast territory, and omitting the ORDER BY in that case shaves 500
milliseconds off the time.
If I turn on stats inside sqlite3 and run the query, I notice the line:
Sort Operations: 1
If my interpretation of the docs about those stats is correct, it looks
like the query is completely skipping using the
MessageTableInternalDateTimeTIndex. The full version of the query also has
the line:
Fullscan Steps: 25824
Sounds like it's walking the table somewhere, but let's ignore that for now.
What I've discovered
So let's work on optimizing that a little bit. I can rearrange the query
into a sub-select and force SQLite to use our index with the INDEXED BY
extension:
SELECT id
FROM MessageTable
INDEXED BY MessageTableInternalDateTimeTIndex
WHERE id IN (
SELECT id
FROM MessageSearchTable
WHERE MessageSearchTable MATCH 'a'
)
ORDER BY internaldate_time_t DESC
LIMIT 10 OFFSET 0
Lo and behold, the running time has dropped to around 100 milliseconds
(300 milliseconds in the full version of the query, a 50% reduction in
running time), and there are no sort operations reported. Note that with
just reorganizing the query like this but not forcing the index with
INDEXED BY, there's still a sort operation (though we've still shaved off
a few milliseconds oddly enough), so it appears that SQLite is indeed
ignoring our index unless we force it.
I've also tried some other things to see if they'd make a difference, but
they didn't:
Explicitly making the index DESC as described here, with and without
INDEXED BY
Explicitly adding the id column in the index, with and without
internaldate_time_t ordered DESC, with and without INDEXED BY
Probably several other things I can't remember at this moment
Questions
100 milliseconds here still seems awfully slow for what seems like it
should be a simple FTS lookup and indexed order.
What's going on here? Why is it ignoring the obvious index unless you
force its hand?
Am I hitting some limitation with combining data from virtual and regular
tables?
Why is it still so relatively slow, and is there anything else I can do to
get FTS matches ordered by a field in another table?
Thanks!
Background
I'm implementing full-text search over a body of email messages stored in
SQLite, making use of its fantastic built-in FTS4 engine. I'm getting some
rather poor query performance, although not exactly where I would expect.
Let's take a look.
Representative schema
I'll give some simplified examples of the code in question, with links to
the full code where applicable.
We've got a MessageTable that stores the data about an email message (full
version spread out over several files here, here, and here):
CREATE TABLE MessageTable (
id INTEGER PRIMARY KEY,
internaldate_time_t INTEGER
);
CREATE INDEX MessageTableInternalDateTimeTIndex
ON MessageTable(internaldate_time_t);
The searchable text is added to an FTS4 table named MessageSearchTable
(full version here):
CREATE VIRTUAL TABLE MessageSearchTable USING fts4(
id INTEGER PRIMARY KEY,
body
);
The id in the search table acts as a foreign key to the message table.
I'll leave it as an exercise for the reader to insert data into these
tables (I certainly can't give out my private email). I have just under
26k records in each table.
Problem query
When we retrieve search results, we need them to be ordered descending by
internaldate_time_t so we can pluck out only the most recent few results.
Here's an example search query (full version here):
SELECT id
FROM MessageSearchTable
JOIN MessageTable USING (id)
WHERE MessageSearchTable MATCH 'a'
ORDER BY internaldate_time_t DESC
LIMIT 10 OFFSET 0
On my machine, with my email, that runs in about 150 milliseconds, as
measured via:
time sqlite3 test.db <<<"..." > /dev/null
150 milliseconds is no beast of a query, but for a simple FTS lookup and
indexed order, it's sluggish. If I omit the ORDER BY, it completes in 10
milliseconds, for example. Also keep in mind that the actual query has one
more sub-select, so there's a little more work going on in general: the
full version of the query runs in about 600 milliseconds, which is into
beast territory, and omitting the ORDER BY in that case shaves 500
milliseconds off the time.
If I turn on stats inside sqlite3 and run the query, I notice the line:
Sort Operations: 1
If my interpretation of the docs about those stats is correct, it looks
like the query is completely skipping using the
MessageTableInternalDateTimeTIndex. The full version of the query also has
the line:
Fullscan Steps: 25824
Sounds like it's walking the table somewhere, but let's ignore that for now.
What I've discovered
So let's work on optimizing that a little bit. I can rearrange the query
into a sub-select and force SQLite to use our index with the INDEXED BY
extension:
SELECT id
FROM MessageTable
INDEXED BY MessageTableInternalDateTimeTIndex
WHERE id IN (
SELECT id
FROM MessageSearchTable
WHERE MessageSearchTable MATCH 'a'
)
ORDER BY internaldate_time_t DESC
LIMIT 10 OFFSET 0
Lo and behold, the running time has dropped to around 100 milliseconds
(300 milliseconds in the full version of the query, a 50% reduction in
running time), and there are no sort operations reported. Note that with
just reorganizing the query like this but not forcing the index with
INDEXED BY, there's still a sort operation (though we've still shaved off
a few milliseconds oddly enough), so it appears that SQLite is indeed
ignoring our index unless we force it.
I've also tried some other things to see if they'd make a difference, but
they didn't:
Explicitly making the index DESC as described here, with and without
INDEXED BY
Explicitly adding the id column in the index, with and without
internaldate_time_t ordered DESC, with and without INDEXED BY
Probably several other things I can't remember at this moment
Questions
100 milliseconds here still seems awfully slow for what seems like it
should be a simple FTS lookup and indexed order.
What's going on here? Why is it ignoring the obvious index unless you
force its hand?
Am I hitting some limitation with combining data from virtual and regular
tables?
Why is it still so relatively slow, and is there anything else I can do to
get FTS matches ordered by a field in another table?
Thanks!
Error mounting: mount exited with exit code 1: helper failed with: mount: only root can mount /dev/sdb1 on /media/sdb1
Error mounting: mount exited with exit code 1: helper failed with: mount:
only root can mount /dev/sdb1 on /media/sdb1
I can't understand why, when I tried plug-in external USB driver in Ubuntu
12.04, I see next message:
Error mounting: mount exited with exit code 1: helper failed with:
mount: only root can mount /dev/sdb1 on /media/sdb1
I tried add this line to /etc/fstab:
UUID=0000-4645 /media/sdb1 vfat noexec
0 0
With of course correct ID (sudo blkid | grep sdb);
This is content of my /etc/fstab:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
proc /proc proc
nodev,noexec,nosuid 0 0
# / was on /dev/sda1 during installation
UUID=5f5d330f-d5f2-4157-9496-94f1dce2f181 / ext4
errors=remount-ro 0 1
# swap was on /dev/sda5 during installation
UUID=84747ef4-6f50-49bc-9df1-fcba364ba299 none swap sw
0 0
/dev/fd0 /media/floppy0 auto
rw,user,noauto,exec,utf8 0 0
/dev/sdc1 /media/sdc1 vfat
uid=nazar_art 0 0
/dev/sdb1 /media/sdb1 vfat
uid=nazar_art 0 0
/dev/sdd1 /media/sdd1 vfat
uid=nazar_art 0 0
# my adding after the disk drive for /media/sdc1 is not ready or not
presented
UUID=0000-4645 /media/sdb1 vfat noexec
0 0
And this is my current sudo fdisk -l:
Disk /dev/sda: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders, total 312581808 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000e28b8
Device Boot Start End Blocks Id System
/dev/sda1 * 2048 310484991 155241472 83 Linux
/dev/sda2 310487038 312580095 1046529 5 Extended
/dev/sda5 310487040 312580095 1046528 82 Linux swap / Solaris
Disk /dev/sdb: 993 MB, 993001472 bytes
2 heads, 1 sectors/track, 969728 cylinders, total 1939456 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
/dev/sdb1 133 1939455 969661+ 6 FAT16
Disk /dev/sdc: 4009 MB, 4009754624 bytes
16 heads, 32 sectors/track, 15296 cylinders, total 7831552 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xd8e1f237
Device Boot Start End Blocks Id System
/dev/sdc1 * 32 7831551 3915760 b W95 FAT32
sdc and sdb - there are external usb drivers.
How to solve this trouble and mount all external usb drives automatic, and
never seen this again.
only root can mount /dev/sdb1 on /media/sdb1
I can't understand why, when I tried plug-in external USB driver in Ubuntu
12.04, I see next message:
Error mounting: mount exited with exit code 1: helper failed with:
mount: only root can mount /dev/sdb1 on /media/sdb1
I tried add this line to /etc/fstab:
UUID=0000-4645 /media/sdb1 vfat noexec
0 0
With of course correct ID (sudo blkid | grep sdb);
This is content of my /etc/fstab:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
proc /proc proc
nodev,noexec,nosuid 0 0
# / was on /dev/sda1 during installation
UUID=5f5d330f-d5f2-4157-9496-94f1dce2f181 / ext4
errors=remount-ro 0 1
# swap was on /dev/sda5 during installation
UUID=84747ef4-6f50-49bc-9df1-fcba364ba299 none swap sw
0 0
/dev/fd0 /media/floppy0 auto
rw,user,noauto,exec,utf8 0 0
/dev/sdc1 /media/sdc1 vfat
uid=nazar_art 0 0
/dev/sdb1 /media/sdb1 vfat
uid=nazar_art 0 0
/dev/sdd1 /media/sdd1 vfat
uid=nazar_art 0 0
# my adding after the disk drive for /media/sdc1 is not ready or not
presented
UUID=0000-4645 /media/sdb1 vfat noexec
0 0
And this is my current sudo fdisk -l:
Disk /dev/sda: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders, total 312581808 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000e28b8
Device Boot Start End Blocks Id System
/dev/sda1 * 2048 310484991 155241472 83 Linux
/dev/sda2 310487038 312580095 1046529 5 Extended
/dev/sda5 310487040 312580095 1046528 82 Linux swap / Solaris
Disk /dev/sdb: 993 MB, 993001472 bytes
2 heads, 1 sectors/track, 969728 cylinders, total 1939456 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
/dev/sdb1 133 1939455 969661+ 6 FAT16
Disk /dev/sdc: 4009 MB, 4009754624 bytes
16 heads, 32 sectors/track, 15296 cylinders, total 7831552 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xd8e1f237
Device Boot Start End Blocks Id System
/dev/sdc1 * 32 7831551 3915760 b W95 FAT32
sdc and sdb - there are external usb drivers.
How to solve this trouble and mount all external usb drives automatic, and
never seen this again.
Continuity and discontinuity of this function
Continuity and discontinuity of this function
$$f(x)=[arctan(x)] $$ we are given this problem to check this function's
continuity and find out where it's discontinuous , note that $[]$ donotes
greatest integer function now the problem comes when we have to get that
value of $arctan(x)$ which is $\ge 1$ and $\le -1$ now how do we go on to
find out this?
$$f(x)=[arctan(x)] $$ we are given this problem to check this function's
continuity and find out where it's discontinuous , note that $[]$ donotes
greatest integer function now the problem comes when we have to get that
value of $arctan(x)$ which is $\ge 1$ and $\le -1$ now how do we go on to
find out this?
File uploading type error in ruby on rails 3
File uploading type error in ruby on rails 3
i am new on ruby on rails and i am trying to upload files into my
database. my form is:
<% provide(:title, 'New Configuration')%>
<h1> Upload new configuration </h1>
<div class="row">
<div class="span6 offset3">
<%= form_for @conf, :html => {:multipart => true} do |f| %>
<%= f.label :machine_brand %>
<%= f.text_field :machine_brand %>
<%= f.label :machine_model %>
<%= f.text_field :machine_model %>
<%= f.label :control_unit_brand %>
<%= f.text_field :control_unit_brand %>
<%= f.label :control_unit_model %>
<%= f.text_field :control_unit_model %>
<%= f.label :tool_axis_x %>
<%= f.text_field :tool_axis_x %>
<%= f.label :tool_axis_y %>
<%= f.text_field :tool_axis_y %>
<%= f.label :tool_axis_z %>
<%= f.text_field :tool_axis_z %>
<%= f.label :rotary_axis_number %>
<%= f.text_field :rotary_axis_number %>
<%= f.label :linear_axis_number %>
<%= f.text_field :linear_axis_number %>
<%= f.label :turning_mode %>
<%= f.text_field :turning_mode %>
<%= f.label :milling_mode %>
<%= f.text_field :milling_mode %>
<%= f.label :description %>
<%= f.text_field :description %>
<%= f.label :xml %>
<%= f.file_field :xml %>
<br />
<%= f.submit "Upload", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
here is my controller:
def create
@conf = Conf.new(params.require(:conf).permit(:xml))
if @conf.save
flash[:success] = "New Configuration uploaded!"
redirect_to conf_show_path
else
flash[:error] = "There is a problem!"
render 'new'
end
end
this is my model:
# == Schema Information
#
# Table name: confs
#
# id :integer not null, primary key
# machine_brand :string(255)
# machine_model :string(255)
# control_unit_brand :string(255)
# control_unit_model :string(255)
# tool_axis_x :decimal(, )
# tool_axis_y :decimal(, )
# tool_axis_z :decimal(, )
# rotary_axis_number :integer
# linear_axis_number :integer
# turning_mode :boolean
# milling_mode :boolean
# description :text
# xml :file
# user_id :integer
# developer_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Conf < ActiveRecord::Base
attr_accessible :linear_axis_number, :control_unit_brand,
:control_unit_model, :description, :developer_id, :machine_brand,
:machine_model, :milling_mode, :rotary_axis_number, :tool_axis_x,
:tool_axis_y, :tool_axis_z, :turning_mode, :user_id, :xml
belongs_to :developer, :class_name => 'User', :foreign_key =>
'developer_id'
belongs_to :receiver, :class_name => 'User', :foreign_key => 'user_id'
validates :user_id, presence: true
validates :developer_id, presence: true
end
at first my create like this and it was saying "There is a problem!"
def create
@conf = Conf.new(params[:conf])
if @conf.save
flash[:success] = "New Configuration uploaded!"
redirect_to conf_show_path
else
flash[:error] = "There is a problem!"
render 'new'
end
end
so i thought that i might defined xml part as text at the beginning. so i
created this migration file and run:
class ChangeTypeOfConfFile < ActiveRecord::Migration
def self.up
change_column :confs, :xml, :text
end
def self.down
change_column :confs, :xml, :file
end
end
console said ok. but "There is a problem!" was not solved. So i changed
the create method and add permit like above. but now i have this problem:
TypeError in ConfsController#create
can't convert Symbol into String
Rails.root: /home/staj/rails_projects/sample_app
Application Trace | Framework Trace | Full Trace
app/controllers/confs_controller.rb:40:in `create'
This error occurred while loading the following files:
conf
and this is the request if you want:
{"utf8"=>"✓",
"authenticity_token"=>"D1Iw0Vu58irnbot7OBQxOp98CJevcuajgfFLh2v5Q2s=",
"conf"=>{"machine_brand"=>"ali",
"machine_model"=>"veli",
"control_unit_brand"=>"kýrk",
"control_unit_model"=>"dokuz",
"tool_axis_x"=>"50",
"tool_axis_y"=>"50",
"tool_axis_z"=>"50",
"rotary_axis_number"=>"4",
"linear_axis_number"=>"3",
"turning_mode"=>"t",
"milling_mode"=>"t",
"description"=>"desc",
"xml"=>#<ActionDispatch::Http::UploadedFile:0x00000004246dd8
@original_filename="deneme.xml",
@content_type="text/xml",
@headers="Content-Disposition: form-data; name=\"conf[xml]\";
filename=\"deneme.xml\"\r\nContent-Type: text/xml\r\n",
@tempfile=#<File:/tmp/RackMultipart20130823-13267-nlx5xv>>},
"commit"=>"Upload"}
i am new on ruby on rails and i am trying to upload files into my
database. my form is:
<% provide(:title, 'New Configuration')%>
<h1> Upload new configuration </h1>
<div class="row">
<div class="span6 offset3">
<%= form_for @conf, :html => {:multipart => true} do |f| %>
<%= f.label :machine_brand %>
<%= f.text_field :machine_brand %>
<%= f.label :machine_model %>
<%= f.text_field :machine_model %>
<%= f.label :control_unit_brand %>
<%= f.text_field :control_unit_brand %>
<%= f.label :control_unit_model %>
<%= f.text_field :control_unit_model %>
<%= f.label :tool_axis_x %>
<%= f.text_field :tool_axis_x %>
<%= f.label :tool_axis_y %>
<%= f.text_field :tool_axis_y %>
<%= f.label :tool_axis_z %>
<%= f.text_field :tool_axis_z %>
<%= f.label :rotary_axis_number %>
<%= f.text_field :rotary_axis_number %>
<%= f.label :linear_axis_number %>
<%= f.text_field :linear_axis_number %>
<%= f.label :turning_mode %>
<%= f.text_field :turning_mode %>
<%= f.label :milling_mode %>
<%= f.text_field :milling_mode %>
<%= f.label :description %>
<%= f.text_field :description %>
<%= f.label :xml %>
<%= f.file_field :xml %>
<br />
<%= f.submit "Upload", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
here is my controller:
def create
@conf = Conf.new(params.require(:conf).permit(:xml))
if @conf.save
flash[:success] = "New Configuration uploaded!"
redirect_to conf_show_path
else
flash[:error] = "There is a problem!"
render 'new'
end
end
this is my model:
# == Schema Information
#
# Table name: confs
#
# id :integer not null, primary key
# machine_brand :string(255)
# machine_model :string(255)
# control_unit_brand :string(255)
# control_unit_model :string(255)
# tool_axis_x :decimal(, )
# tool_axis_y :decimal(, )
# tool_axis_z :decimal(, )
# rotary_axis_number :integer
# linear_axis_number :integer
# turning_mode :boolean
# milling_mode :boolean
# description :text
# xml :file
# user_id :integer
# developer_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Conf < ActiveRecord::Base
attr_accessible :linear_axis_number, :control_unit_brand,
:control_unit_model, :description, :developer_id, :machine_brand,
:machine_model, :milling_mode, :rotary_axis_number, :tool_axis_x,
:tool_axis_y, :tool_axis_z, :turning_mode, :user_id, :xml
belongs_to :developer, :class_name => 'User', :foreign_key =>
'developer_id'
belongs_to :receiver, :class_name => 'User', :foreign_key => 'user_id'
validates :user_id, presence: true
validates :developer_id, presence: true
end
at first my create like this and it was saying "There is a problem!"
def create
@conf = Conf.new(params[:conf])
if @conf.save
flash[:success] = "New Configuration uploaded!"
redirect_to conf_show_path
else
flash[:error] = "There is a problem!"
render 'new'
end
end
so i thought that i might defined xml part as text at the beginning. so i
created this migration file and run:
class ChangeTypeOfConfFile < ActiveRecord::Migration
def self.up
change_column :confs, :xml, :text
end
def self.down
change_column :confs, :xml, :file
end
end
console said ok. but "There is a problem!" was not solved. So i changed
the create method and add permit like above. but now i have this problem:
TypeError in ConfsController#create
can't convert Symbol into String
Rails.root: /home/staj/rails_projects/sample_app
Application Trace | Framework Trace | Full Trace
app/controllers/confs_controller.rb:40:in `create'
This error occurred while loading the following files:
conf
and this is the request if you want:
{"utf8"=>"✓",
"authenticity_token"=>"D1Iw0Vu58irnbot7OBQxOp98CJevcuajgfFLh2v5Q2s=",
"conf"=>{"machine_brand"=>"ali",
"machine_model"=>"veli",
"control_unit_brand"=>"kýrk",
"control_unit_model"=>"dokuz",
"tool_axis_x"=>"50",
"tool_axis_y"=>"50",
"tool_axis_z"=>"50",
"rotary_axis_number"=>"4",
"linear_axis_number"=>"3",
"turning_mode"=>"t",
"milling_mode"=>"t",
"description"=>"desc",
"xml"=>#<ActionDispatch::Http::UploadedFile:0x00000004246dd8
@original_filename="deneme.xml",
@content_type="text/xml",
@headers="Content-Disposition: form-data; name=\"conf[xml]\";
filename=\"deneme.xml\"\r\nContent-Type: text/xml\r\n",
@tempfile=#<File:/tmp/RackMultipart20130823-13267-nlx5xv>>},
"commit"=>"Upload"}
Batch - type command that skips empty lines
Batch - type command that skips empty lines
Is it possible to have the type command skip empty lines in a text file?
Or is there an alternate command that will print out the contents of a
text file while skipping empty lines in that text file?
Is it possible to have the type command skip empty lines in a text file?
Or is there an alternate command that will print out the contents of a
text file while skipping empty lines in that text file?
Thursday, 22 August 2013
AS3: Create motion-tween though ActionScript
AS3: Create motion-tween though ActionScript
I've created a simple shape(MovieClip) in main Scene.
So, i wanna move that shape via Motion Tween in ActionScript.
Please tell me how can i do that ?
Notice :
I not talking about create Motion Tween in flash timeline. I need to do
that in ActionScript.
P.S :
I'm using Flash Professional.
I've created a simple shape(MovieClip) in main Scene.
So, i wanna move that shape via Motion Tween in ActionScript.
Please tell me how can i do that ?
Notice :
I not talking about create Motion Tween in flash timeline. I need to do
that in ActionScript.
P.S :
I'm using Flash Professional.
How to make list element editable
How to make list element editable
I'm trying to find the best way to make a list element editable when it is
double clicked. If I have something set up like this:
http://jsfiddle.net/sjfqX/3/
HTML
<ul>
<li>Hello</li>
<li>World</li>
</ul>
JS
$('li').dblclick(function() {
//something here?
});
what would be the best way of coding a double click action to let me
change the value of the list element clicked?
I'm trying to find the best way to make a list element editable when it is
double clicked. If I have something set up like this:
http://jsfiddle.net/sjfqX/3/
HTML
<ul>
<li>Hello</li>
<li>World</li>
</ul>
JS
$('li').dblclick(function() {
//something here?
});
what would be the best way of coding a double click action to let me
change the value of the list element clicked?
ASP.NET 4.0 CSS in a folder is not cached
ASP.NET 4.0 CSS in a folder is not cached
I converted an existing website from ASP.NET 2.0 to ASP.NET 4.0.
Now when I see the network tab in Firebug I see the css files in my
root/css folder are retrieved upon each request with 200 OK response. So
they are not cached.
Although the css files I have in my aspnet Theme are getting cached. So I
moved the /css folder files in Themes folder and those files are now
cached.
Why are styles in folder other than Themes aren't cached? I wonder if I am
missing some configuration setting?
P.S.: I am running the new website from VS2010/DevServer/FireFox.
I converted an existing website from ASP.NET 2.0 to ASP.NET 4.0.
Now when I see the network tab in Firebug I see the css files in my
root/css folder are retrieved upon each request with 200 OK response. So
they are not cached.
Although the css files I have in my aspnet Theme are getting cached. So I
moved the /css folder files in Themes folder and those files are now
cached.
Why are styles in folder other than Themes aren't cached? I wonder if I am
missing some configuration setting?
P.S.: I am running the new website from VS2010/DevServer/FireFox.
Can HTA's use HTML5 IndexedDB?
Can HTA's use HTML5 IndexedDB?
I'm having no luck using IndexedDB with HTA's nor finding any information
on the feasibility of doing so. Can hypertext applications (HTA's) use the
IndexedDB feature of HTML 5?
I'm having no luck using IndexedDB with HTA's nor finding any information
on the feasibility of doing so. Can hypertext applications (HTA's) use the
IndexedDB feature of HTML 5?
Get products Values and Names from Group Magento
Get products Values and Names from Group Magento
I have this code that I found on another post that it is supposed to get
the group's attributes.
<?php function printGroupAttributes($groupId) {
$attributesCollection =
Mage::getResourceModel('catalog/product_attribute_collection');
$attributesCollection->setAttributeGroupFilter($groupId);
foreach ($attributesCollection as $attribute) {
echo $attribute->getAttributeCode()."<br/>"; // I launch it from
browser
}
}
$attributeGroupId = 224; // Fill with yours
printGroupAttributes($attributeGroupId);
?>
Unfortunatelly this gives me only the group's ids. What should I enter on
this code so I can get Names and Values also?
Thank you
I have this code that I found on another post that it is supposed to get
the group's attributes.
<?php function printGroupAttributes($groupId) {
$attributesCollection =
Mage::getResourceModel('catalog/product_attribute_collection');
$attributesCollection->setAttributeGroupFilter($groupId);
foreach ($attributesCollection as $attribute) {
echo $attribute->getAttributeCode()."<br/>"; // I launch it from
browser
}
}
$attributeGroupId = 224; // Fill with yours
printGroupAttributes($attributeGroupId);
?>
Unfortunatelly this gives me only the group's ids. What should I enter on
this code so I can get Names and Values also?
Thank you
MySQL/C++ connector mysql_real_escape_string function
MySQL/C++ connector mysql_real_escape_string function
I wanted to use mysql_real_escape_string to handle apostrophe, backslashes
etc. I searched and found this function
unsigned long mysql_real_escape_string(MYSQL *mysql,
char *to, const char *from, unsigned long length)
But this takes MYSQL *, but I use this code to connect :
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
// Create a connection
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "anubha");
con->setSchema("db");
stmt = con->createStatement();
So if I don't have a MYSQL *mysql object as the function requires. If I do
connection like this :
MYSQL* conn = mysql_init(NULL);
mysql_real_connect(conn,"tcp://127.0.0.1:3306", "root",
"anubha", "db" ,0,NULL,0);
Then as I have MYSQL* object I can use the function, but should I change
the connection code just to use this function. Isn't there another
function available ? Also what is the difference between the 2 ways to
connect, is it C vs C++ mysql connector api difference ?
I wanted to use mysql_real_escape_string to handle apostrophe, backslashes
etc. I searched and found this function
unsigned long mysql_real_escape_string(MYSQL *mysql,
char *to, const char *from, unsigned long length)
But this takes MYSQL *, but I use this code to connect :
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
// Create a connection
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "anubha");
con->setSchema("db");
stmt = con->createStatement();
So if I don't have a MYSQL *mysql object as the function requires. If I do
connection like this :
MYSQL* conn = mysql_init(NULL);
mysql_real_connect(conn,"tcp://127.0.0.1:3306", "root",
"anubha", "db" ,0,NULL,0);
Then as I have MYSQL* object I can use the function, but should I change
the connection code just to use this function. Isn't there another
function available ? Also what is the difference between the 2 ways to
connect, is it C vs C++ mysql connector api difference ?
Can I create an array of auto_ptr?
Can I create an array of auto_ptr?
I have a base class, which is inherited by multiple derived classes. i
want to create array of autopointer of baseClass pointer. when i
initialise those autopointer i get some compile time error, then i tried
to do like that way
std::auto_ptr<base>pbase[3];
std::auto_ptr<base> b1(new derived1());
std::auto_ptr<base> b2(new derived2());
std::suto_ptr<base> b3(new derived3());
pbase[0] = b1;
pbase[2] = b2;
pbase[3] = b3;
then i get memory leaks. i can't get why it happens, do we can't use array
with auto_ptr.
I have a base class, which is inherited by multiple derived classes. i
want to create array of autopointer of baseClass pointer. when i
initialise those autopointer i get some compile time error, then i tried
to do like that way
std::auto_ptr<base>pbase[3];
std::auto_ptr<base> b1(new derived1());
std::auto_ptr<base> b2(new derived2());
std::suto_ptr<base> b3(new derived3());
pbase[0] = b1;
pbase[2] = b2;
pbase[3] = b3;
then i get memory leaks. i can't get why it happens, do we can't use array
with auto_ptr.
Wednesday, 21 August 2013
onPause and onResume causing issue
onPause and onResume causing issue
I currently am in the midst of completing my first app. However, onPause
and onResume are killing my dreams. This is the code
onPause:
public void onPause()
{
super.onPause();
cleanSlate();
for( int k = 0; k <
((ArrayHandler)getApplicationContext()).info.size(); k++)
{
String account =
((ArrayHandler)getApplicationContext()).info.get(k).getAccountName();
String name =
((ArrayHandler)getApplicationContext()).info.get(k).getUserName();
String pass =
((ArrayHandler)getApplicationContext()).info.get(k).getPassword();
writeFileToStorage(account, name, pass);
}
deleteArray();
Log.d("LifeCycle","onPause Called");
}
onResume:
protected void onResume()
{
super.onResume();
readfile();
Log.d("LifeCycle","onResume Called");
}
Now, the idea behind these methods are that when the system calls onPause
it will clear the views on the linear layout as well as clear the text
file that is being read in
This is the cleanSlate method
public void cleanSlate()
{
LinearLayout linearLayout =
(LinearLayout)findViewById(R.id.linear_layout);
linearLayout.removeAllViews();
try{
bufferedWriter = new BufferedWriter(new
OutputStreamWriter(openFileOutput(FILENAME, MODE_PRIVATE)));
bufferedWriter.flush();
bufferedWriter.close();
}catch (Exception err)
{
Toast.makeText(getBaseContext(), "Cannot Clean",
Toast.LENGTH_SHORT).show();
err.printStackTrace();
}
}
Then, it scans the array and rewrite the current array items to the file
that will be read in, in onResume.
The issue that im running into is that some of the items are being
duplicated when onResume is called. The items are being deleted from the
array when a button is pushed. So my speculation is that the file is not
being flushed which is then causing items to be duplicated.
My question to you fine folks is, what do you think is the issue and what
would be an appropriate solution?
Thanks.
I currently am in the midst of completing my first app. However, onPause
and onResume are killing my dreams. This is the code
onPause:
public void onPause()
{
super.onPause();
cleanSlate();
for( int k = 0; k <
((ArrayHandler)getApplicationContext()).info.size(); k++)
{
String account =
((ArrayHandler)getApplicationContext()).info.get(k).getAccountName();
String name =
((ArrayHandler)getApplicationContext()).info.get(k).getUserName();
String pass =
((ArrayHandler)getApplicationContext()).info.get(k).getPassword();
writeFileToStorage(account, name, pass);
}
deleteArray();
Log.d("LifeCycle","onPause Called");
}
onResume:
protected void onResume()
{
super.onResume();
readfile();
Log.d("LifeCycle","onResume Called");
}
Now, the idea behind these methods are that when the system calls onPause
it will clear the views on the linear layout as well as clear the text
file that is being read in
This is the cleanSlate method
public void cleanSlate()
{
LinearLayout linearLayout =
(LinearLayout)findViewById(R.id.linear_layout);
linearLayout.removeAllViews();
try{
bufferedWriter = new BufferedWriter(new
OutputStreamWriter(openFileOutput(FILENAME, MODE_PRIVATE)));
bufferedWriter.flush();
bufferedWriter.close();
}catch (Exception err)
{
Toast.makeText(getBaseContext(), "Cannot Clean",
Toast.LENGTH_SHORT).show();
err.printStackTrace();
}
}
Then, it scans the array and rewrite the current array items to the file
that will be read in, in onResume.
The issue that im running into is that some of the items are being
duplicated when onResume is called. The items are being deleted from the
array when a button is pushed. So my speculation is that the file is not
being flushed which is then causing items to be duplicated.
My question to you fine folks is, what do you think is the issue and what
would be an appropriate solution?
Thanks.
Windows 7 account picture
Windows 7 account picture
So recently I changed my account picture from the default hp thing to a
skull in crossbones BUT when I went to change it back (I was just testing
it) I saw that the default picture had been replaced with the skull and
crossbones!!!!!! Also when I went to C:\ProgramData\Microsoft\User Account
Pictures\Default Pictures it was not there??!! Please help me I have been
looking around and I really need this fixed thank you for reading this and
hopefully replying.
So recently I changed my account picture from the default hp thing to a
skull in crossbones BUT when I went to change it back (I was just testing
it) I saw that the default picture had been replaced with the skull and
crossbones!!!!!! Also when I went to C:\ProgramData\Microsoft\User Account
Pictures\Default Pictures it was not there??!! Please help me I have been
looking around and I really need this fixed thank you for reading this and
hopefully replying.
inter process communication in python
inter process communication in python
I have a cloud process which downloads certain files to the cloud. How can
I let my mother process know about success or failure to do some clean up
work if required?
Should I be using semaphores?
I have a cloud process which downloads certain files to the cloud. How can
I let my mother process know about success or failure to do some clean up
work if required?
Should I be using semaphores?
Python requests disable auto decoding
Python requests disable auto decoding
Can you disable the auto decoding feature in requests version 1.2.3?
I've looked through the documentation and couldn't find anything, I'm
currently experiencing a gzip decode error and want to manually debug the
data coming through the request.
Can you disable the auto decoding feature in requests version 1.2.3?
I've looked through the documentation and couldn't find anything, I'm
currently experiencing a gzip decode error and want to manually debug the
data coming through the request.
Push rejected, no Cedar-supported app detected
Push rejected, no Cedar-supported app detected
I know this question has been asked several times. But I couldnot stop
myself to post this here. I am nooby. I am trying to push the app from git
to heroku using the following command
ubuntu@ip-1x2-xx-xx-xxx:~/vexxx$ git push heroku master
I am getting the following error.
Counting objects: 8, done.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (8/8), 1015 bytes, done.
Total 8 (delta 0), reused 0 (delta 0)
! Push rejected, no Cedar-supported app detected
To git@heroku.com:fast-fortress-3889.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:fast-fortress-3889.git'
I am trying to use node.js framework
UPDATE
I have two files in my app folder name vxxxx/
1.README.md
2.venkat1.js
Inside venkat1.js
#!/usr/bin/env node
var fs = require('fs');
var outfile = "hello.txt";
var out = "A startup is a business built to grow rapidly.\n";
fs.writeFileSync(outfile, out);
console.log("Script: " + __filename + "\nWrote: " + out + "To: " + outfile);
I do not have any other files. Actually these two files are in my git
repo. I am trying to push it to heroku and run the app there using node.js
I know this question has been asked several times. But I couldnot stop
myself to post this here. I am nooby. I am trying to push the app from git
to heroku using the following command
ubuntu@ip-1x2-xx-xx-xxx:~/vexxx$ git push heroku master
I am getting the following error.
Counting objects: 8, done.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (8/8), 1015 bytes, done.
Total 8 (delta 0), reused 0 (delta 0)
! Push rejected, no Cedar-supported app detected
To git@heroku.com:fast-fortress-3889.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:fast-fortress-3889.git'
I am trying to use node.js framework
UPDATE
I have two files in my app folder name vxxxx/
1.README.md
2.venkat1.js
Inside venkat1.js
#!/usr/bin/env node
var fs = require('fs');
var outfile = "hello.txt";
var out = "A startup is a business built to grow rapidly.\n";
fs.writeFileSync(outfile, out);
console.log("Script: " + __filename + "\nWrote: " + out + "To: " + outfile);
I do not have any other files. Actually these two files are in my git
repo. I am trying to push it to heroku and run the app there using node.js
trying to identify if there is text present in a text fields with class="x"
trying to identify if there is text present in a text fields with class="x"
I have three text box's that a user can enter text into but I don't know
what there going to enter. I want to see if there is text in the box's. I
know I can use jQuery to find out if there is text if I know the text
entry
$( ".x:contains('John')" )
but I don't know what they are going to enter so is there a fix for this?
I have three text box's that a user can enter text into but I don't know
what there going to enter. I want to see if there is text in the box's. I
know I can use jQuery to find out if there is text if I know the text
entry
$( ".x:contains('John')" )
but I don't know what they are going to enter so is there a fix for this?
Tuesday, 20 August 2013
Data sorting out two new files
Data sorting out two new files
I have a logfile looks like this:
[2013-08-16 03:24:39,192][INFO ][AbstractServiceInvoker
[SID:187175558][] Received request of type [ReportNotification]
I need two write out every line to a new file if contains [INFO ] to a
file called the SID name, like 187175558_xyz.txt
Thanks for helping!
I have a logfile looks like this:
[2013-08-16 03:24:39,192][INFO ][AbstractServiceInvoker
[SID:187175558][] Received request of type [ReportNotification]
I need two write out every line to a new file if contains [INFO ] to a
file called the SID name, like 187175558_xyz.txt
Thanks for helping!
how can send variable value through pagination links?
how can send variable value through pagination links?
I was trying to create pagination based on the home page.
my default controller :
$route['default_controller'] ="home";
for pagination if I write-
$config['base_url'] = base_url() . 'home/index'; // index function
$config['uri_segment'] = 3;
$config['per_page'] = 10;
$limit = array($config['per_page'] => $this->uri->segment(3));
then it works but it shows 'localhost/baseurl/home/index/10' on browser
address bar.I want to show just 'localhost/baseurl/10' (while
'localhost/baseurl/' is my homepage and I want pagination on there).so I
wrote
$config['base_url'] = base_url(); // index function
$config['uri_segment'] = 1;
$config['per_page'] = 10;
$limitt = array($config['per_page'] => $this->uri->segment(1));
but that doesn't work. how can I do that ?
problem 2:
how can I send a variable value through pagination link like
localhost/baseurl/home/index?search=y/10
I wrote:
$config['base_url'] = base_url() . 'home/index?search=y';
but this doesn't work. it receives 'search=y/10'. not only 'y' and the
pagination doesn't find '10' on '$this->uri->segment(3))'
so whats the correct way to do that ?
-thanks.
I was trying to create pagination based on the home page.
my default controller :
$route['default_controller'] ="home";
for pagination if I write-
$config['base_url'] = base_url() . 'home/index'; // index function
$config['uri_segment'] = 3;
$config['per_page'] = 10;
$limit = array($config['per_page'] => $this->uri->segment(3));
then it works but it shows 'localhost/baseurl/home/index/10' on browser
address bar.I want to show just 'localhost/baseurl/10' (while
'localhost/baseurl/' is my homepage and I want pagination on there).so I
wrote
$config['base_url'] = base_url(); // index function
$config['uri_segment'] = 1;
$config['per_page'] = 10;
$limitt = array($config['per_page'] => $this->uri->segment(1));
but that doesn't work. how can I do that ?
problem 2:
how can I send a variable value through pagination link like
localhost/baseurl/home/index?search=y/10
I wrote:
$config['base_url'] = base_url() . 'home/index?search=y';
but this doesn't work. it receives 'search=y/10'. not only 'y' and the
pagination doesn't find '10' on '$this->uri->segment(3))'
so whats the correct way to do that ?
-thanks.
Error with setuptools in virtualenv
Error with setuptools in virtualenv
I had a mess of virtualenv/virtualenvwrapper and virtualenv burrito on my
machine. So I have removed all of it and installed virtualenvwrapper.
Now I have created a virtualenv: mkvirtualenv myenv
I have a simple setup.py
from setuptools import setup
from os.path import dirname, abspath
requirements = []
base_path = abspath(dirname(__file__))
with open(base_path + '/requirements.txt') as r_file:
requirements = r_file.readlines()
setup(
name='x',
version='0.1.0',
long_description="",
packages=['x', 'flume'],
install_requires=requirements,
)
Where 'requirement.txt' has: (its read properly)
distribute==0.6.46
pycassa==1.9.0
FirePython==0.9.0
Flask==0.10.1
Flask-Classy==0.6.3
newrelic==1.12.0.56
pycrypto==2.6
pep8==1.4.6
memorised==1.0.5
jsonpickle==0.4.0
thrift==0.9.0
When I run: python setup.py install inside the virtualenv, I get this error:
(myenv)zengr@x:y$ python setup.py install
running install
error: None
How can I troubleshoot the problem? Any suggestions?
I had a mess of virtualenv/virtualenvwrapper and virtualenv burrito on my
machine. So I have removed all of it and installed virtualenvwrapper.
Now I have created a virtualenv: mkvirtualenv myenv
I have a simple setup.py
from setuptools import setup
from os.path import dirname, abspath
requirements = []
base_path = abspath(dirname(__file__))
with open(base_path + '/requirements.txt') as r_file:
requirements = r_file.readlines()
setup(
name='x',
version='0.1.0',
long_description="",
packages=['x', 'flume'],
install_requires=requirements,
)
Where 'requirement.txt' has: (its read properly)
distribute==0.6.46
pycassa==1.9.0
FirePython==0.9.0
Flask==0.10.1
Flask-Classy==0.6.3
newrelic==1.12.0.56
pycrypto==2.6
pep8==1.4.6
memorised==1.0.5
jsonpickle==0.4.0
thrift==0.9.0
When I run: python setup.py install inside the virtualenv, I get this error:
(myenv)zengr@x:y$ python setup.py install
running install
error: None
How can I troubleshoot the problem? Any suggestions?
jQuery addEventListener not working in IE8
jQuery addEventListener not working in IE8
So I have a script that includes addEventListener and have discovered it
isn't supported in > IE8. All the fixes I have seen, do not work when
edited according to my script, so looking for some tailored help!
$(document).ready(function(){
var excuses = [
'excuse one',
'excuse two',
'excuse three',
'excuse four',
'excuse five',
'excuse six',
'excuse seven',
'excuse eight',
'excuse nine'
];
var bttn = document.getElementById('refresh');
var excuse = document.getElementById('excuse');
var rando = 0;
var makeExcuse = function(){
rando = Math.floor(Math.random()*excuses.length);
excuse.innerHTML = excuses[rando];
};
makeExcuse();
bttn.addEventListener('click',function(e){
e.preventDefault();
makeExcuse();
});
});
Thanks a lot!
So I have a script that includes addEventListener and have discovered it
isn't supported in > IE8. All the fixes I have seen, do not work when
edited according to my script, so looking for some tailored help!
$(document).ready(function(){
var excuses = [
'excuse one',
'excuse two',
'excuse three',
'excuse four',
'excuse five',
'excuse six',
'excuse seven',
'excuse eight',
'excuse nine'
];
var bttn = document.getElementById('refresh');
var excuse = document.getElementById('excuse');
var rando = 0;
var makeExcuse = function(){
rando = Math.floor(Math.random()*excuses.length);
excuse.innerHTML = excuses[rando];
};
makeExcuse();
bttn.addEventListener('click',function(e){
e.preventDefault();
makeExcuse();
});
});
Thanks a lot!
Ruby gives No such file or directory - text.txt =?iso-8859-1?Q?(Errno::ENOENT)=94_error?=
Ruby gives "No such file or directory - text.txt (Errno::ENOENT)" error
when am trying to run a ruby app ,it gives below error,
Could anyone put some light in to it .
ruby logger.rb
/home/swapnasa/Downloads/irclogger-master
logger.rb:14:in `read': No such file or directory - ./tmp/logger.pid
(Errno::ENOENT)
from logger.rb:14:in `<main>'
Code goes here:-
#!/usr/bin/env ruby
puts Dir.pwd
$: << File.join(File.dirname(__FILE__), 'lib')
require 'irclogger'
require 'irclogger/cinch_plugin'
require 'redis'
pidfile = File.join(File.dirname(__FILE__), 'tmp', 'logger.pid')
begin
old_pid = File.read(pidfile).to_i
Process.kill 0, old_pid
raise "An existing logger process is running with pid #{old_pid}.
Refusing to start"
rescue Errno::ESRCH
end
File.open(pidfile, 'w') do |f|
f.write Process.pid
end
bot = Cinch::Bot.new do
configure do |c|
c.server = Config['server']
c.channels = Config['channels']
c.user = Config['username']
c.nick = Config['nickname']
c.realname = Config['realname']
# cinch, oh god why?!
c.plugins.plugins = [IrcLogger::CinchPlugin]
end
end
IrcLogger::CinchPlugin.redis = Redis.new(url: Config['redis'])
bot.start
when am trying to run a ruby app ,it gives below error,
Could anyone put some light in to it .
ruby logger.rb
/home/swapnasa/Downloads/irclogger-master
logger.rb:14:in `read': No such file or directory - ./tmp/logger.pid
(Errno::ENOENT)
from logger.rb:14:in `<main>'
Code goes here:-
#!/usr/bin/env ruby
puts Dir.pwd
$: << File.join(File.dirname(__FILE__), 'lib')
require 'irclogger'
require 'irclogger/cinch_plugin'
require 'redis'
pidfile = File.join(File.dirname(__FILE__), 'tmp', 'logger.pid')
begin
old_pid = File.read(pidfile).to_i
Process.kill 0, old_pid
raise "An existing logger process is running with pid #{old_pid}.
Refusing to start"
rescue Errno::ESRCH
end
File.open(pidfile, 'w') do |f|
f.write Process.pid
end
bot = Cinch::Bot.new do
configure do |c|
c.server = Config['server']
c.channels = Config['channels']
c.user = Config['username']
c.nick = Config['nickname']
c.realname = Config['realname']
# cinch, oh god why?!
c.plugins.plugins = [IrcLogger::CinchPlugin]
end
end
IrcLogger::CinchPlugin.redis = Redis.new(url: Config['redis'])
bot.start
How do I obtain the Fishcake?
How do I obtain the Fishcake?
As the title states, how do I obtain the fishcake? is it still obtainable
or will I have to trade for it?
As the title states, how do I obtain the fishcake? is it still obtainable
or will I have to trade for it?
Database is UTF-8, data shows up as ????? in page
Database is UTF-8, data shows up as ????? in page
I have an issue, i had a script to get some fields from a database and
print em out but after some updates on the software something is wrong
with UTF8 imo.
English is printed out just fine but for any greek i see ??????. Fields in
the database are utf8_general_ci.
Below is the script
function getaffiliateclientname($inputid)
{
$database="XXXXXXXX";
mysql_connect ("XXXXXXXXXXXXXXXXXXX");
@mysql_select_db($database) or die( "Unable to select database");
$data = mysql_query("SELECT firstname, lastname FROM hb_client_details
WHERE id = (SELECT client_id FROM hb_aff WHERE id=$inputid )")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
return $info['firstname'];
}
}
Any ides on what might be wrong?
I have an issue, i had a script to get some fields from a database and
print em out but after some updates on the software something is wrong
with UTF8 imo.
English is printed out just fine but for any greek i see ??????. Fields in
the database are utf8_general_ci.
Below is the script
function getaffiliateclientname($inputid)
{
$database="XXXXXXXX";
mysql_connect ("XXXXXXXXXXXXXXXXXXX");
@mysql_select_db($database) or die( "Unable to select database");
$data = mysql_query("SELECT firstname, lastname FROM hb_client_details
WHERE id = (SELECT client_id FROM hb_aff WHERE id=$inputid )")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
return $info['firstname'];
}
}
Any ides on what might be wrong?
Monday, 19 August 2013
How to install NuGet-packages without internet connection?
How to install NuGet-packages without internet connection?
Currently I'm developing on a virtual pc which is not allowed internet
access. I managed to get the NuGet.Tools.vsix to add NuGet to Visual
Studio 2010, but cannot seem to find out how to deploy NuGet-packages
offline.
For example, I downloaded EntityFramework 5.0.0 nuget.org and moved it to
my virtual pc. How should I perform the last step of deploying this
package to my solution?
Thanks in advance
Currently I'm developing on a virtual pc which is not allowed internet
access. I managed to get the NuGet.Tools.vsix to add NuGet to Visual
Studio 2010, but cannot seem to find out how to deploy NuGet-packages
offline.
For example, I downloaded EntityFramework 5.0.0 nuget.org and moved it to
my virtual pc. How should I perform the last step of deploying this
package to my solution?
Thanks in advance
Searching a custom listview
Searching a custom listview
I was curious on how to make a listview with a custom adapter searchable.
I followed a tutorial and got everything set up, but the app crashes when
I try to type anything in the EditText. Now I know why the app crashes, I
just don't know how to fix it.
Here is the code to my MainActivity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context ctx = getApplication();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.item_ids);
String[] ids = res.getStringArray(R.array.item_names);
TypedArray icons = res.obtainTypedArray(R.array.item_images);
setListAdapter(new ItemIDAdapter(ctx, R.layout.idslistitem, ids,
options, icons));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Get the options menu view from menu.xml in menu folder
getSupportMenuInflater().inflate(R.menu.items_menu, menu);
// Locate the EditText in menu.xml
editsearch = (EditText)
menu.findItem(R.id.menu_search).getActionView();
// Capture Text in EditText
editsearch.addTextChangedListener(textWatcher);
// Show the search menu item in menu.xml
MenuItem menuSearch = menu.findItem(R.id.menu_search);
menuSearch.setOnActionExpandListener(new
OnActionExpandListener() {
// Menu Action Collapse
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Empty EditText to remove text filtering
editsearch.setText("");
editsearch.clearFocus();
return true;
}
// Menu Action Expand
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Focus on EditText
editsearch.requestFocus();
// Force the keyboard to show on EditText focus
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
return true;
}
});
// Show the settings menu item in menu.xml
MenuItem menuSettings = menu.findItem(R.id.home);
// Capture menu item clicks
menuSettings.setOnMenuItemClickListener(new
OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent2 = new Intent(ItemId.this, Home.class);
startActivity(intent2);
return true;
}
});
return true;
}
// EditText TextWatcher
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.getFilter().filter(text);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int
arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
};
And here is the code to my custom listview adapter:
public class ItemIDAdapter extends ArrayAdapter<String> {
public LayoutInflater mInflater;
public String[] mStrings;
public String[] mIds;
public TypedArray mIcons;
public int mViewResourceId;
ArrayAdapter<String> adapter;
public ItemIDAdapter(Context ctx, int viewResourceId,
String[] strings, String[] ids, TypedArray icons) {
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater)ctx.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIds = ids;
mIcons = icons;
mViewResourceId = viewResourceId;
}
@Override
public int getCount() {
return mStrings.length;
}
@Override
public String getItem(int position) {
return mStrings[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));
TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);
TextView tv1 = (TextView)convertView.findViewById(R.id.itemids);
tv1.setText(mIds[position]);
return convertView;
}
}
The reason the app crashes when I try to search, is because in the
TextWatcher, this line: adapter.getFilter().filter(text); adapter is only
defined at the top of my main activity, but it isn't used with my listview
at ALL. I'm stuck here and really don't know what to replace adapter with,
because ItemIDAdapter doesn't work. Thanks for your help!
I was curious on how to make a listview with a custom adapter searchable.
I followed a tutorial and got everything set up, but the app crashes when
I try to type anything in the EditText. Now I know why the app crashes, I
just don't know how to fix it.
Here is the code to my MainActivity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context ctx = getApplication();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.item_ids);
String[] ids = res.getStringArray(R.array.item_names);
TypedArray icons = res.obtainTypedArray(R.array.item_images);
setListAdapter(new ItemIDAdapter(ctx, R.layout.idslistitem, ids,
options, icons));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Get the options menu view from menu.xml in menu folder
getSupportMenuInflater().inflate(R.menu.items_menu, menu);
// Locate the EditText in menu.xml
editsearch = (EditText)
menu.findItem(R.id.menu_search).getActionView();
// Capture Text in EditText
editsearch.addTextChangedListener(textWatcher);
// Show the search menu item in menu.xml
MenuItem menuSearch = menu.findItem(R.id.menu_search);
menuSearch.setOnActionExpandListener(new
OnActionExpandListener() {
// Menu Action Collapse
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Empty EditText to remove text filtering
editsearch.setText("");
editsearch.clearFocus();
return true;
}
// Menu Action Expand
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Focus on EditText
editsearch.requestFocus();
// Force the keyboard to show on EditText focus
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
return true;
}
});
// Show the settings menu item in menu.xml
MenuItem menuSettings = menu.findItem(R.id.home);
// Capture menu item clicks
menuSettings.setOnMenuItemClickListener(new
OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent2 = new Intent(ItemId.this, Home.class);
startActivity(intent2);
return true;
}
});
return true;
}
// EditText TextWatcher
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.getFilter().filter(text);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int
arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
};
And here is the code to my custom listview adapter:
public class ItemIDAdapter extends ArrayAdapter<String> {
public LayoutInflater mInflater;
public String[] mStrings;
public String[] mIds;
public TypedArray mIcons;
public int mViewResourceId;
ArrayAdapter<String> adapter;
public ItemIDAdapter(Context ctx, int viewResourceId,
String[] strings, String[] ids, TypedArray icons) {
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater)ctx.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIds = ids;
mIcons = icons;
mViewResourceId = viewResourceId;
}
@Override
public int getCount() {
return mStrings.length;
}
@Override
public String getItem(int position) {
return mStrings[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));
TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);
TextView tv1 = (TextView)convertView.findViewById(R.id.itemids);
tv1.setText(mIds[position]);
return convertView;
}
}
The reason the app crashes when I try to search, is because in the
TextWatcher, this line: adapter.getFilter().filter(text); adapter is only
defined at the top of my main activity, but it isn't used with my listview
at ALL. I'm stuck here and really don't know what to replace adapter with,
because ItemIDAdapter doesn't work. Thanks for your help!
javascript 'for each in' using array
javascript 'for each in' using array
I was testing out the the for each in construct of javascript using an
array. I know it's recommended for objects. But it turns out that the code
wont work. It outputs nothing. So i tried in in the chrome console and it
said "Unidentified identifier" and the Firefox console said: "SyntaxError:
missing ( after for". I have no idea what's the problem. Any suggestions?
Here is the code:
var cars = ['Ferrari', 'Bugatti', 'Ford', 'Lambo'];
var total = '';
for each(var value in cars)
{
total += value + "--";
}
document.write(total);
I was testing out the the for each in construct of javascript using an
array. I know it's recommended for objects. But it turns out that the code
wont work. It outputs nothing. So i tried in in the chrome console and it
said "Unidentified identifier" and the Firefox console said: "SyntaxError:
missing ( after for". I have no idea what's the problem. Any suggestions?
Here is the code:
var cars = ['Ferrari', 'Bugatti', 'Ford', 'Lambo'];
var total = '';
for each(var value in cars)
{
total += value + "--";
}
document.write(total);
Accessing obj as property vs method param (style preferences)
Accessing obj as property vs method param (style preferences)
When it comes to accessing objects from different methods in the same
class, from what I understand, these are two ways to do it. Given that I
DO want to hold a property pointer to this object, which is the better way
to go about this? I've been thinking about this for a while, and wondered
if there is a preference consensus.
#1:
NSArray *array = ... // Get array from somewhere
self.myArray = array;
[self doSomethingToMyArray];
This method takes no parameter and accesses the array via its own property
via self
- (void)doSomethingToMyArray
{
// Do stuff to the array via self.myArray
[self.myArray ...];
}
Vs #2:
NSArray *array = ... // Get array from somewhere
self.myArray = array;
[self doSomething:array];
This method takes an array and accesses the array via its own method
parameter
- (void)doSomething:(NSArray *)array
{
// Do stuff to the array via method parameter "array"
[array ...];
}
When it comes to accessing objects from different methods in the same
class, from what I understand, these are two ways to do it. Given that I
DO want to hold a property pointer to this object, which is the better way
to go about this? I've been thinking about this for a while, and wondered
if there is a preference consensus.
#1:
NSArray *array = ... // Get array from somewhere
self.myArray = array;
[self doSomethingToMyArray];
This method takes no parameter and accesses the array via its own property
via self
- (void)doSomethingToMyArray
{
// Do stuff to the array via self.myArray
[self.myArray ...];
}
Vs #2:
NSArray *array = ... // Get array from somewhere
self.myArray = array;
[self doSomething:array];
This method takes an array and accesses the array via its own method
parameter
- (void)doSomething:(NSArray *)array
{
// Do stuff to the array via method parameter "array"
[array ...];
}
JSON doesn't fill the backbone collection directly
JSON doesn't fill the backbone collection directly
I have JSON that is returned from the server, and I'm populating a
Backbone collection with it.
Models
Person = Backbone.Model.extend({
});
PersonCollection = Backbone.Collection.extend({
model: Person
});
The JSON for example-
var jsonString = "[
{ \"name\": \"Anna\", \"id\": 5 },
{ \"name\": \"Lina\", \"id\": 26 },
{ \"name\": \"Melissa\", \"id\": 55 }
]"
var people = JSON.parse(jsonString); //people is now an array of 3 persons
Works:
var personCollection = new PersonCollection();
for (var i = 0; i < people.length; i++) {
personCollection.add(people[i]);
}
var personCollectionView = new PersonCollectionView({ collection:
personCollection});
Doesn't work :(
var personCollectionView = new PersonCollectionView({ collection: people});
My JSON is returning an array of models, I'm not sure why I can't pass
this array directly to the PersonCollectionView? Is there something I need
to do in the parse method of PersonCollection, such that when given an
array of models, it will convert it into a collection of models?
I'm sure I'm missing something. Can someone point out what that is?
I have JSON that is returned from the server, and I'm populating a
Backbone collection with it.
Models
Person = Backbone.Model.extend({
});
PersonCollection = Backbone.Collection.extend({
model: Person
});
The JSON for example-
var jsonString = "[
{ \"name\": \"Anna\", \"id\": 5 },
{ \"name\": \"Lina\", \"id\": 26 },
{ \"name\": \"Melissa\", \"id\": 55 }
]"
var people = JSON.parse(jsonString); //people is now an array of 3 persons
Works:
var personCollection = new PersonCollection();
for (var i = 0; i < people.length; i++) {
personCollection.add(people[i]);
}
var personCollectionView = new PersonCollectionView({ collection:
personCollection});
Doesn't work :(
var personCollectionView = new PersonCollectionView({ collection: people});
My JSON is returning an array of models, I'm not sure why I can't pass
this array directly to the PersonCollectionView? Is there something I need
to do in the parse method of PersonCollection, such that when given an
array of models, it will convert it into a collection of models?
I'm sure I'm missing something. Can someone point out what that is?
Array.splice doesn't change the length
Array.splice doesn't change the length
I have a function where I delete some parts of an Array using .splice, but
when I look about console.log on it's length it hasn't changed.. and with
hexdump I also saw that the "deleted" string is still there
e.g.
Array = [3, 7]
function...
Array.splice(Array.indexOf(3), 1)
console.log(Array, Array.length, Hexdump.dump(Array))
= [7] 2 /*Zusammenfassung des hex:*/ 3, 7
(the value that shall be deleted comes from an other var, that's why I
wrote the part with the "indexOf")
What can I do, to delete the value once and for all?
because I have an IF that needs to know the length of my Arrays...
I have a function where I delete some parts of an Array using .splice, but
when I look about console.log on it's length it hasn't changed.. and with
hexdump I also saw that the "deleted" string is still there
e.g.
Array = [3, 7]
function...
Array.splice(Array.indexOf(3), 1)
console.log(Array, Array.length, Hexdump.dump(Array))
= [7] 2 /*Zusammenfassung des hex:*/ 3, 7
(the value that shall be deleted comes from an other var, that's why I
wrote the part with the "indexOf")
What can I do, to delete the value once and for all?
because I have an IF that needs to know the length of my Arrays...
Sunday, 18 August 2013
Curvature Using Circles
Curvature Using Circles
Given the equation $(x - h)^2 + (y - k)^2 = r^2$ representing the family
of all circles of radius r at the point $(h,k)$ if we try to form the
differential equation representing this family we find an equation of the
form
$$\kappa = \frac{1}{r} = \frac{y''}{\sqrt{(1 + y'^2)^3}}$$
which is surprisingly the equation for the curvature of a plane curve
(ignoring absolute values which arise in the derivation).
But this expression was derived interpreting $y$ as part of a circle, how
in the world can one justify plugging in other functions & saying this
represents the curvature of that curve at the point? I know you're trying
to say that, locally, the curve moves as though it were moving along the
arc of a circle of radius $r$, but there seems to be a jump in my mind as
to how you get that interpretation out of what I've written.
Given the equation $(x - h)^2 + (y - k)^2 = r^2$ representing the family
of all circles of radius r at the point $(h,k)$ if we try to form the
differential equation representing this family we find an equation of the
form
$$\kappa = \frac{1}{r} = \frac{y''}{\sqrt{(1 + y'^2)^3}}$$
which is surprisingly the equation for the curvature of a plane curve
(ignoring absolute values which arise in the derivation).
But this expression was derived interpreting $y$ as part of a circle, how
in the world can one justify plugging in other functions & saying this
represents the curvature of that curve at the point? I know you're trying
to say that, locally, the curve moves as though it were moving along the
arc of a circle of radius $r$, but there seems to be a jump in my mind as
to how you get that interpretation out of what I've written.
Why my gnome terminal is set to root by default?
Why my gnome terminal is set to root by default?
When I try to open up a new terminal in Ubuntu to do some operations, it
always defaults to an admin based terminal with [sudo] password for
xxxxxxxx: $
I need a regular terminal. How do I do this? I like having to type sudo
before my commands as this makes it safe.
When I d type in my password it closes out and then nothing not even a
peep. What is going on?
By the way xterm works fine.
When I try to open up a new terminal in Ubuntu to do some operations, it
always defaults to an admin based terminal with [sudo] password for
xxxxxxxx: $
I need a regular terminal. How do I do this? I like having to type sudo
before my commands as this makes it safe.
When I d type in my password it closes out and then nothing not even a
peep. What is going on?
By the way xterm works fine.
How to draw an image multiple times
How to draw an image multiple times
So here's my problem I'm doing a basic platformer with tiles drawn as
ground. The tiles are basicly a texture with a hitbox drawn in a grid. But
I cant draw the same image multiple times. so do I just makes thousends of
image variables or is there a better way?
Thanks
So here's my problem I'm doing a basic platformer with tiles drawn as
ground. The tiles are basicly a texture with a hitbox drawn in a grid. But
I cant draw the same image multiple times. so do I just makes thousends of
image variables or is there a better way?
Thanks
Python: Can we Loop inside a string?
Python: Can we Loop inside a string?
Like for example I have a string of HTML Ordered List. Inside that ordered
list, I want to write n number of lists. How can I accomplish the task of
adding the lists to this string?
Here is the example code:
html = """
<ol>
<li>
<!--Something-->
</li>
... <!--n lists-->
{} #str().format()
<li>
<!--Something-->
</li>
</ol>
"""
for li in html_lists: #where li is <li>...</li> and is inside the
python list.
html.format(li)
As far as I know, Strings are immutable and .format() will add <li> at {}.
Hence this won't work for more than one <li>.
Like for example I have a string of HTML Ordered List. Inside that ordered
list, I want to write n number of lists. How can I accomplish the task of
adding the lists to this string?
Here is the example code:
html = """
<ol>
<li>
<!--Something-->
</li>
... <!--n lists-->
{} #str().format()
<li>
<!--Something-->
</li>
</ol>
"""
for li in html_lists: #where li is <li>...</li> and is inside the
python list.
html.format(li)
As far as I know, Strings are immutable and .format() will add <li> at {}.
Hence this won't work for more than one <li>.
Get back when back button pressed
Get back when back button pressed
When i press back back button my app closses. How to get back to the
previous page when i pressing back button? I tried with
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
event.startTracking();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
&& !event.isCanceled()) {
// *** DO ACTION HERE ***
return true;
}
return super.onKeyUp(keyCode, event);
}
but i cant make it work.
When i press back back button my app closses. How to get back to the
previous page when i pressing back button? I tried with
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
event.startTracking();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
&& !event.isCanceled()) {
// *** DO ACTION HERE ***
return true;
}
return super.onKeyUp(keyCode, event);
}
but i cant make it work.
MongoDB: How to find key by value
MongoDB: How to find key by value
I'm using Node.js with express framework and Mongoose (MongoDB), and I
have a question about how to effectively retrieve data.
Let's say I have something like this on a mongo document:
test : {a:1, b:2, c:2, d:1};
It's easy to retrieve the value of keys (a,b,c, or d), but how to do the
inverse, for example retrieve all the letters that have value 2 (in my
example it would be 'b' and 'c')
Thanks!
I'm using Node.js with express framework and Mongoose (MongoDB), and I
have a question about how to effectively retrieve data.
Let's say I have something like this on a mongo document:
test : {a:1, b:2, c:2, d:1};
It's easy to retrieve the value of keys (a,b,c, or d), but how to do the
inverse, for example retrieve all the letters that have value 2 (in my
example it would be 'b' and 'c')
Thanks!
Saturday, 17 August 2013
How to connect to a servlet when both machines are on the same wifi?
How to connect to a servlet when both machines are on the same wifi?
Is it possible to connect to a servlet hosted on one machine from another
machine when both are sharing the same wifi network. What is the IP
address that we can provide for the servlet hosting machine? I need to
test a functionality in my android app where i am inserting data into a DB
via a servlet. Problem is my server (servlet+db hosting) and the android
dev. machine both share the same wifi network.
Is it possible to connect to a servlet hosted on one machine from another
machine when both are sharing the same wifi network. What is the IP
address that we can provide for the servlet hosting machine? I need to
test a functionality in my android app where i am inserting data into a DB
via a servlet. Problem is my server (servlet+db hosting) and the android
dev. machine both share the same wifi network.
Fields of characteristic zero
Fields of characteristic zero
Let $\mathcal{F}$ be the class of free fields of characteristic zero and
let $X\neq \emptyset$ be a set. How would one show that there are no free
fields in $\mathcal{F}$?
Also, how would one identify the free field of characteristic zero that is
generated by the empty set?
Let $\mathcal{F}$ be the class of free fields of characteristic zero and
let $X\neq \emptyset$ be a set. How would one show that there are no free
fields in $\mathcal{F}$?
Also, how would one identify the free field of characteristic zero that is
generated by the empty set?
USB booting problem
USB booting problem
It can't boot from a USB disc, i have tried to edit the boot setting to
make USB-HDD the first and the second boot device and it still booting
windows, Md5 is correct i am using LinuxLive USB Creator 2.8.23
It can't boot from a USB disc, i have tried to edit the boot setting to
make USB-HDD the first and the second boot device and it still booting
windows, Md5 is correct i am using LinuxLive USB Creator 2.8.23
Packed-Symmetric-Matrix Matrix Multiplication with CUDA
Packed-Symmetric-Matrix Matrix Multiplication with CUDA
Is there any standard CUDA library that has a function for
packed-symmetric-matrix and matrix multiplication ? If possible, I need to
use C-style row-major matrices. I thought cuBLAS symm functions were doing
exactly this, but it appears that they do not accept symmetric matrices
with packed storage format. Thanks.
Is there any standard CUDA library that has a function for
packed-symmetric-matrix and matrix multiplication ? If possible, I need to
use C-style row-major matrices. I thought cuBLAS symm functions were doing
exactly this, but it appears that they do not accept symmetric matrices
with packed storage format. Thanks.
Line bundle determined by a linear surjection $V \to V/W$
Line bundle determined by a linear surjection $V \to V/W$
I am new to things like line bundles and have just been reading page 10 of
this document here. Now I have some elementary questions:
Given a finite dimensional complex vector space $V$ and a one -
dimensional vector space $W$, we can form $V/W$ together with $\pi : V \to
V/W$ the canonical projection. Now I understand that upon taking
projectivizations we have a map $\Bbb{P}(\pi) : \Bbb{P}(V) - (\Bbb{P}(W) =
\{\ast\}) \longrightarrow \Bbb{P}(V/W)$. But why is this latter thing a
line bundle? I can see that given a line $L \subseteq V/W$, the inverse
image $\pi^{-1}(L)$ consists of all two dimensional subspaces $K$ in $V$
that contain $W$. But now how can I see that the fibre
$\Bbb{P}(\pi)^{-1}([L])$ "is" a one-dimensional vector space? Also, how
does one verify the local triviality condition?
Given a section $s$ of the map $\pi : V \to V/W$, we have a section
$\Bbb{P}(s)$ of the map $\Bbb{P}(\pi)$. However it is claimed in the
document I linked to that the image of $\Bbb{P}(V/W)$ in
$\Bbb{P}(V)\setminus \{\ast\}$ is a hypersurface. Why is this so?
I am new to things like line bundles and have just been reading page 10 of
this document here. Now I have some elementary questions:
Given a finite dimensional complex vector space $V$ and a one -
dimensional vector space $W$, we can form $V/W$ together with $\pi : V \to
V/W$ the canonical projection. Now I understand that upon taking
projectivizations we have a map $\Bbb{P}(\pi) : \Bbb{P}(V) - (\Bbb{P}(W) =
\{\ast\}) \longrightarrow \Bbb{P}(V/W)$. But why is this latter thing a
line bundle? I can see that given a line $L \subseteq V/W$, the inverse
image $\pi^{-1}(L)$ consists of all two dimensional subspaces $K$ in $V$
that contain $W$. But now how can I see that the fibre
$\Bbb{P}(\pi)^{-1}([L])$ "is" a one-dimensional vector space? Also, how
does one verify the local triviality condition?
Given a section $s$ of the map $\pi : V \to V/W$, we have a section
$\Bbb{P}(s)$ of the map $\Bbb{P}(\pi)$. However it is claimed in the
document I linked to that the image of $\Bbb{P}(V/W)$ in
$\Bbb{P}(V)\setminus \{\ast\}$ is a hypersurface. Why is this so?
how to numerate Chapters in Lyx
how to numerate Chapters in Lyx
I'm new working with Lyx. What I want is to numerate all the chapters in
my paper. I tryed this code for my first chapter:
\setcounter{chapter}{1}.
but immediately I got this error message:
\maketitle
Your command was ignored. Type I to replace it with another command, or to
continue without it.
Do I need to add any package, library.... I'd really appreciate any answer.
Best regards.
I'm new working with Lyx. What I want is to numerate all the chapters in
my paper. I tryed this code for my first chapter:
\setcounter{chapter}{1}.
but immediately I got this error message:
\maketitle
Your command was ignored. Type I to replace it with another command, or to
continue without it.
Do I need to add any package, library.... I'd really appreciate any answer.
Best regards.
Maths in php and mysql
Maths in php and mysql
im trying to do a simple sum in php using entryies in my database by
displaying them in the file. all other fields show perfectly apart from
the sum
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT make, id, model, bcosts, rcosts, value, id FROM referb';
mysql_select_db('ely');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
echo "<tbody><tr class=\"odd\">
<td>{$row['make']} </td>".
"<td>{$row['model']} </td> ".
"<td>{$row['id']}</td> ".
"<td>{$row['bcosts']}</td> ".
"<td>{$row['value']}</td> ".
"<td>{$row['rcosts']}</td> ".
"<td> £
$first_number = {$row['bcosts']};
$second_number = {$row['rcosts']};
$third_number = {$row['value']};
$sum_total = $third_number - $second_number - $first_number;
print ($sum_total);
</td> ";
}
?>
the out put i get for this is
£ = 100; = 25; = 300; = - - ; print ();
im trying to do a simple sum in php using entryies in my database by
displaying them in the file. all other fields show perfectly apart from
the sum
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT make, id, model, bcosts, rcosts, value, id FROM referb';
mysql_select_db('ely');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
echo "<tbody><tr class=\"odd\">
<td>{$row['make']} </td>".
"<td>{$row['model']} </td> ".
"<td>{$row['id']}</td> ".
"<td>{$row['bcosts']}</td> ".
"<td>{$row['value']}</td> ".
"<td>{$row['rcosts']}</td> ".
"<td> £
$first_number = {$row['bcosts']};
$second_number = {$row['rcosts']};
$third_number = {$row['value']};
$sum_total = $third_number - $second_number - $first_number;
print ($sum_total);
</td> ";
}
?>
the out put i get for this is
£ = 100; = 25; = 300; = - - ; print ();
Friday, 16 August 2013
How to investigate "Exception form Deps recompute" what are the clues?
How to investigate "Exception form Deps recompute" what are the clues?
I am on a big project, first exposure to Meteor, and I am starting to get
this very often. It will be hard to trace it back to a particular commit,
as it seemed intermittent.
What is a fruitful way to approach finding the problem? Is there anything
in the exception that helps narrow it down? How do I step through/set
breakpoints in/rule out the Deps? All my deps are the auto ones from mongo
operations, or one on a session var, nothing explicit.
Thank you
https://gist.github.com/jimmack1963/6254452
I am on a big project, first exposure to Meteor, and I am starting to get
this very often. It will be hard to trace it back to a particular commit,
as it seemed intermittent.
What is a fruitful way to approach finding the problem? Is there anything
in the exception that helps narrow it down? How do I step through/set
breakpoints in/rule out the Deps? All my deps are the auto ones from mongo
operations, or one on a session var, nothing explicit.
Thank you
https://gist.github.com/jimmack1963/6254452
Saturday, 10 August 2013
Can I use LINQ to compare what is missing, added or updated between two collections
Can I use LINQ to compare what is missing, added or updated between two
collections
I have the following class. To make it so I could compare I added an
Equals method:
public ObjectiveDetail()
public int ObjectiveDetailId { get; set; }
public int Number { get; set; }
public string Text { get; set; }
public override bool Equals(object obj)
{
return this.Equals(obj as ObjectiveDetail);
}
public bool Equals(ObjectiveDetail other)
{
if (other == null)
return false;
return this.Number.Equals(other.Number) &&
(
this.Text == other.Text ||
this.Text != null &&
this.Text.Equals(other.Text)
);
}
}
I have two ICollection collections:
ICollection<ObjectiveDetail> _obj1; // Reference
ICollection<ObjectiveDetail> _obj2; // May have more, less or different
objectDetails from the reference.
The common tfield with the collections is ObjectiveDetailId. Is there a
way I can use three LINQ expressions to create:
A collection of rows in _obj2 and not _obj1
A collection of rows in _obj1 and not _obj2
A collection of rows different between _obj1 and _obj2
Note this is similar to another question I asked earlier but I think this
is a bit simpler now I have added the Equals method. uld do this?
collections
I have the following class. To make it so I could compare I added an
Equals method:
public ObjectiveDetail()
public int ObjectiveDetailId { get; set; }
public int Number { get; set; }
public string Text { get; set; }
public override bool Equals(object obj)
{
return this.Equals(obj as ObjectiveDetail);
}
public bool Equals(ObjectiveDetail other)
{
if (other == null)
return false;
return this.Number.Equals(other.Number) &&
(
this.Text == other.Text ||
this.Text != null &&
this.Text.Equals(other.Text)
);
}
}
I have two ICollection collections:
ICollection<ObjectiveDetail> _obj1; // Reference
ICollection<ObjectiveDetail> _obj2; // May have more, less or different
objectDetails from the reference.
The common tfield with the collections is ObjectiveDetailId. Is there a
way I can use three LINQ expressions to create:
A collection of rows in _obj2 and not _obj1
A collection of rows in _obj1 and not _obj2
A collection of rows different between _obj1 and _obj2
Note this is similar to another question I asked earlier but I think this
is a bit simpler now I have added the Equals method. uld do this?
Jquery hover get Id issue
Jquery hover get Id issue
Hi I have an img and when I hover over it I want it to unhide a div,
however It won't work. Here is my attempt.
$("img").hover(
function () {
var currentID = $(this).attr('id');
$('.'+currentID).show();
},
function () {
var currentID = $(this).attr('id');
$('.'+currentID).hide();
}
);
Here is the HTML
//intially hidden via display:none
<div class="Alligator sinensis"
style="display:none;border:solid;float:right;">
//this is the image
<img id="Alligator sinensis" class="circular resultss imgs"
src="http://media.eol.org/content/2013/02/20/13/27869_orig.jpg">
Hi I have an img and when I hover over it I want it to unhide a div,
however It won't work. Here is my attempt.
$("img").hover(
function () {
var currentID = $(this).attr('id');
$('.'+currentID).show();
},
function () {
var currentID = $(this).attr('id');
$('.'+currentID).hide();
}
);
Here is the HTML
//intially hidden via display:none
<div class="Alligator sinensis"
style="display:none;border:solid;float:right;">
//this is the image
<img id="Alligator sinensis" class="circular resultss imgs"
src="http://media.eol.org/content/2013/02/20/13/27869_orig.jpg">
Subscribe to:
Comments (Atom)