text
stringlengths 8
267k
| meta
dict |
---|---|
Q: How can i see SQLite Database (No emulator)? For development , sometimes we need for a faster programming , the SQLite database state of our programs . But i can only extract database if it's on emulator , not mobile .
Then my exactly question is ¿Is there a way to see the android sqlite db or a way to extract it?
If there isn't a good answer to that question . How do you manage with that programming issues when you need to know the db state of the tables?
A: You can use
adb shell
to get a root shell of the device, then use anything you like directly on the DB. Export it, run scripts etc etc.
You can check out this link for details:
developer.android.com/studio/command-line/sqlite3.html
Abount SQLite commands:
http://www.sqlite.org/sqlite.html
A: You can do this from shell as vbence mentioned. Another way is to copy the database file to sd card programatically. Call this in onStop():
File source = new File("data/data/com.ACME/databases/" + DATABASE_NAME);
File dest = new File(Environment.getExternalStorageDirectory() + "/" + DATABASE_NAME + ".db");
public static void copyFile(File sourceFile, File destFile) {
FileChannel source = null;
FileChannel destination = null;
try {
if (!destFile.exists()) {
destFile.createNewFile();
}
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} catch (Exception e) {
/* handle exception... */
} finally {
try {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
} catch (Exception e) {
/* handle exception... */
}
}
}
A: For exploring the SQLite database you can use the addon of mozilla firefox named SQLite Manager. And after running the app pull the database to your system using file explorer and open the firefox-->Tools-->SQLite Manager. A window will come and on that there is an option to open the database, click on that and direct to the path where you have pulled your DB. Open that DB you can see the tables created and the values you have entered. Also you have the option to add, edit, delete and update the values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How does git find subtree, when we use subree merging strategy? How does git find subtree, when we use subtree merging strategy? I find only one mention here: "It actually guesses the subtrees that you want to merge. Usually, this magically turns out to be correct, but if your subtree contains a lot of changes (or was originally empty, or whatever), then it can fail spectacularly."
How does it guess and what can i do, if it fails?
Is something changed since aug'09, when that answer were written?
A: Here are some helpful articles about subtree merging:
http://blog.brad.jones.name/2011/10/52/merging-two-git-repositories-history
http://kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html
https://help.github.com/articles/working-with-subtree-merge
The state of subtree merges has changed since the date asked, including the addition of --Xsubtree= parameter to allow you to bypass the "guess".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Plone Authentication failing for only 1 user (Apologies for being new to Plone - previous administrator has moved on.)
One of our Plone users is failing to authenticate to Plone but we cannot find any reason for it. She logs into Novell successfully and tries to access Plone pages to edit them and the LDAP authentication used by Plone returns the message "Login failed. Both login name and password are case sensitive, check that caps lock is not enabled".
We have and LDAP plugin installed and have established nothing unusual about the user. All cookies have been removed without success.
We are running:
-Plone 3.2.2
-CMF 2.1.2
-Zope (Zope 2.10.9-final, python 2.4.2, linux2)
-Python 2.4.2 (#1, Dec 2 2008, 00:09:07) [GCC 4.1.2 20070115 (SUSE Linux)]
-PIL 1.1.5
Has anyone got any hints on how to solve this?
Thanks in advance
A: Try one or more of these options:
*
*are you sure that this particular user is imported from the ldap and is not local to plone? If it's local, she probably didn't activate it from the received automatic email.
*did you check if the user password is expired in your ldap? the user is active?
*does your ldap plugin imports users using some filter (es. group, attributes..)? If so, compare her ldap group/attributes with other users.
*the user needs some phosphorus? Try to reset her password in the ldap.
*did she use special characters in her password? It could be an error of password transmission between plone and the ldap because of these special chars. Plone can smoothly handle local user's password with special chars, but sometime it fails to transmit these password to the authentication source. I've experienced this error once but i don't remember much more.
*if everything else fails you could remove the cached user in the ldap plugin and re-import it. It could be a cache error.
A: Check in the ZMI. Look in /acl_users/source_users/manage_users below the Plone site, and /acl_users/users/manage_users at the Zope root, and any acl_users in between.
This is what Giacomo meant by "local to plone". If she is defined in one of those places, and that source has priority over LDAP (likely), then her LDAP credentials aren't being used.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ThreadPools from different processes Task Parallel Library is a great wrapper around ThreadPool that ensures close to optimal use of all cores. This means not only spawning threads but also limiting the amount of active threads in order not to overwhelm the system with by too many active threads. For instance two concurrent Parallel.ForEach() won't result into 16 active threads on 8 core machine. There will be 8 active threads and the work from both ForEach() will be balanced between them. But this balancing works on process level. What about the whole system?
I am concerned about possible contention when running 2 or more instances of my CPU-bound applications using TPL. Question is: is it ok from performance point of view to have many concurrent CPU-bound apps OR it worth moving all logic to one process and make use of PTL work balancing?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery - datatable plugin - sorting issue I'm using DataTables plugin from http://datatables.net.
The plugin it self is very useful,but I have a big of a problem with it.
It is return a list of address for some searches in the following format.
1 Main Street
12 Main Street
13 Main Street
14 Main Street
...
2 Main Street
3 Main Street
4 Main Street
5 Main Street
..
As you can see the sorting is not what I would expected. Will return all numbers starting with 1 eg, 11, 111, 1111 before 2.
Have any of you have some expirience with the plugin?
*
*know to solve this sorting issue?
*or know the way to disable the sorting on first initiate(display the data as it is coming form db)?
Any suggestions much appreciated.
A: To solve this particular issue you can use natural-sort plugin for datatables. Read all about it at http://datatables.net/plug-ins/sorting (search for "Natural sorting").
In short, provided you've downloaded and embedded naturalSort function, you then define sort handle for datatables like this:
jQuery.fn.dataTableExt.oSort['natural-asc'] = function(a,b) {
return naturalSort(a,b);
};
jQuery.fn.dataTableExt.oSort['natural-desc'] = function(a,b) {
return naturalSort(a,b) * -1;
};
You also need to specify the sSortDataType parameter for the column, to tell it which plug-in function to use (in example below I set the sorting to natural for the third column of my table):
$('#example').dataTable( {
"aoColumns": [
null,
null,
{ "sType": "natural" }
]
});
Here's working fiddle http://jsfiddle.net/zhx32/14/
Note: it seems that you, in fact, number of elements on "aoColumns" have to be equal to number of columns in the table, otherwise you'll get an error. Null value indicates that datatables plugin should use default sort method for that column.
A: You should use a sorting plugin for that something like this:
jQuery.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
var x = a.replace( /<.*?>/g, "" );
var y = b.replace( /<.*?>/g, "" );
x = parseFloat( x );
y = parseFloat( y );
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
var x = a.replace( /<.*?>/g, "" );
var y = b.replace( /<.*?>/g, "" );
x = parseFloat( x );
y = parseFloat( y );
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
and then specify that type in aoColumns
"aoColumns": [
null,
null,
null,
{ "sType": "num-html" },
null
]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to include(attach) javascript to a certain PHP Control (Class) I'm writing php and I have a custom made control that is Grid and I would wanna know how to attach its javascript with it and everytime someone uses that control the javascript will be included automatically and if it's already included then it should not be included again.
For example I have the following page:
<html>
<head>
//Notice that nothing is included here
</head>
<body>
<?php grid = new Grid() ?>
</body>
</html>
A: I believe you want to attach a specific js file (in this case the grid.js) to your html file which in turn will be used by the php grid class.
<html>
<head>
<?php if(isset(loadgridjs)){ ?>
<script type="text/javascript" src="grid.js"></script>
<?php } ?>
</head>
<body>
<?php grid = new Grid() ?>
</body>
If loadgridjs has been set then it will include the grid.js to your html. There are other ways how to do this and I believe this is the simplest one
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Export GridView to multiple Excel sheet I have two Gridview in my Web application.I need ,while clicking the (ExcelExpot) button the values to be Export in Excel Accordingly Sheet1 and Sheet2.
protected void ExportToExcel()
{
this.GridView1.EditIndex = -1;
Response.Clear();
Response.Buffer = true;
string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection sqlconnection = new SqlConnection(connectionString);
String sqlSelect = "select * from login";
sqlconnection.Open();
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(sqlSelect, connectionString);
//DataTable dt1
DataTable dt1 =new DataTable();
mySqlDataAdapter.Fill(dt1);
//LinQ Query for dt2
var query = (from c in dt.AsEnumerable()
select new {id= c.Field<string>("id"),name=c.Field<string>("name"),city=c.Field<string>("city")}) ;
DataTable dt2 = new DataTable();
d2=query.CopyToDatatable();
DataSet ds=new DataSet();
ds.Tabls.Add(dt1);
ds.Tabls.Add(dt2);
Excel.Application excelHandle1 = PrepareForExport(ds);
excelHandle1.Visible = true;
}
// code for PrepareForExport(ds);
PrepareForExport(ds)
{
two tables in two worksheets of Excel...
}
A: Doing this with EPPlus is a piece of cake. No Interop assemblies required and literally 2 lines of code do all the magic:
ws.Cells["A1"].LoadFromDataTable(dt1, true);
ws2.Cells["A1"].LoadFromDataTable(dt2, true);
Complete code:
protected void ExportExcel_Click(object sender, EventArgs e)
{
//LinQ Query for dt2
var query = (from c in dt.AsEnumerable()
select new {id= c.Field<string>("id"),name=c.Field<string>("name"),city=c.Field<string>("city")}) ;
DataTable dt2 = new DataTable();
dt2=query.CopyToDatatable();
//DataTable dt1
DataTable dt1 =new DataTable();
mySqlDataAdapter.Fill(dt1);
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Page 1");
ExcelWorksheet ws2 = pck.Workbook.Worksheets.Add("Page 2");
ws.Cells["A1"].LoadFromDataTable(dt1, true);
ws2.Cells["A1"].LoadFromDataTable(dt2, true);
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
Response.Flush();
Response.End();
}
}
Note that I copied and paste it your code to gather the data. I expect these lines to produce a DataTable.
A: I agree with @Andrew Burgess and have implemented his code into one of my projects. Just for the record theres a few small errors in the code which will cause some COM Exceptions. The corrected code is below (the issue was that Excel numbers sheets, rows, columns from 1 to n not from zero).
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
//Print using Ofice InterOp
Excel.Application excel = new Excel.Application();
var workbook = (Excel._Workbook)(excel.Workbooks.Add(Missing.Value));
for (var i = 0; i < dataset.Tables.Count; i++)
{
if (workbook.Sheets.Count <= i)
{
workbook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
}
//NOTE: Excel numbering goes from 1 to n
var currentSheet = (Excel._Worksheet)workbook.Sheets[i + 1];
for (var y = 0; y < dataset.Tables[i].Rows.Count; y++)
{
for (var x = 0; x < dataset.Tables[i].Rows[y].ItemArray.Count(); x++)
{
currentSheet.Cells[y+1, x+1] = dataset.Tables[i].Rows[y].ItemArray[x];
}
}
}
string outfile = @"C:\APP_OUTPUT\EXCEL_TEST.xlsx";
workbook.SaveAs( outfile, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
workbook.Close();
excel.Quit();
A: You'll need to create the workbook, add more sheets if needed (defaults with three), and then fill out the cells.
Top of the file:
using Excel=Microsoft.Office.Interop.Excel;
And then the main code for generating the Excel file
Excel.Application excel = new Application();
var workbook = (Excel._Workbook) (excel.Workbooks.Add(Missing.Value));
for (var i = 0; i < dataset.Tables.Count; i++)
{
if (workbook.Sheets.Count <= i)
{
workbook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
}
var currentSheet = (Excel._Worksheet)workbook.Sheets[i];
for (var y = 0; y < dataset.Tables[i].Rows.Count; y++)
{
for (var x = 0; x < dataset.Tables[i].Rows[y].ItemArray.Count(); x++)
{
currentSheet.Cells[y, x] = dataset.Tables[i].Rows[y].ItemArray[x];
}
}
}
workbook.SaveAs("C:\\Temp\\book.xlsx", Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
workbook.Close();
excel.Quit();
Response.WriteFile(C:\\Temp\\book.xlsx");
Don't know exactly if this will work, but it should get you in the right direction
(also: Type.Missing and Missing.Value come from the namespace System.Reflection, just FYI)
A: Rather than using some 3rd party library or the Excel automation (with it's added overhead) you can just use ADO.NET.
http://support.microsoft.com/kb/316934#10
You would simply use the T-SQL your used to with OleDbCommand objects.
CREATE TABLE Sheet1 (id INT, name char(255))
CREATE TABLE Sheet2 (id INT, name char(255))
// for inserts use a parameterized command with ?'s
INSERT INTO Sheet1 (id, name) VALUES(?, ?)
INSERT INTO Sheet1 (id, name) VALUES(?, ?)
You'd create your temp excel file using the Path.GetTempFileName and output it, after which you can delete the temp file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: FMS 4 playing P2P stream with RTMFP Proper disclosure: I posted this question on the Adobe forums too. Since I didn't get any answer - I am posting it here. Sorry if it disturbs.
We are working with FMS 4 server for a while for a 2 directions video application, and it works great with RTMP.
We now want to use its rtmfp abilities after we used Cirrus for testing in the last few days and it also worked well.
Locally - everything is working fine, but when we try the application on a remote server - we have some problems.
Each side get the NetStatusEvent code "NetConnection.Connect.Success" and "NetStream.Publish.Start" when publish starts.
However, when we are trying to play the stream, nothing happens for a minute and than we get " NetStream.Connect.Closed" after about a minute.
(Locally, we are getting "NetStream.Play.Start" and "NetStream.Play.Reset").
I did open ports 1024-65535 UDP on the server and since we are able to connect Cirrus, I believe the clients are fine.
I also changed the Adaptor.xml HostPort element to
:19350-65535 where xxx.xxx.xxx.xxx is the same public IP of our FMS Server as the one used by the client.
Again, it is working beautifully both locally and with Cirrus. RTMP also works well with the remote server.
What am I missing?
A: I'm sorry, I can't really help but tell you that I had a very similar problem but the other way around.
When I tried to connect two devices via Cirrus over our WLAN, I got the same error as you. When testing with one device in WLAN and the other in another Network it worked. Then I tested them both in the same WLAN (but in a WLAN other than ours) and it also worked. My collegue then updated some firmware (on the router? I'm not sure...) and deleted some VOIP data. Then it worked here, too.
I think maybe there is some problem at the remote server. UDP has to be allowed... but I'm sure you know that.
Sorry again for not really helping - but maybe this is at least a bit encouraging.
Do you know this sample: http://labs.adobe.com/technologies/cirrus/samples/ ?
I always tested with that so I knew it wasn't some problem with my code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Content-Length and httpCompression dilemma My ASP.NET app returns JSON object to user, it contains binary encoded data. Due to this I decided to enable HTTP compression and the problem begun with Content-Length.
If I enable compression the Content-Length header is ignored while response s send and connection is not closed immediately. The connection is still open for about 15 seconds after all data has been sent.
I would like to have HTTP compression enabled but don't know how to solve the problem with Content-Length header.
context.Response.AddHeader("Content-Length", jsonObject.ToString().Length.ToString());
context.Response.Write(jsonObject);
context.Response.Flush();
context.Response.Close();
A: Content-Length represents the length of the data being transferred in your case it is the compressed bytes. See this SO question whose answer links to relevant RFC: content-length when using http compression
In case, HTTP Compression is happening via web server (and not by your code) then I will suggest you to try adding content-length header by your self. Hopefully, web server will add it correctly.
This can be verified using Chrome on http://httpd.apache.org/ if you look at the developer console you would see the Content-Length to be much smaller than the actual uncompressed page in bytes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to access Safari history from iPhone App using Private Frameworks I got a situation something like, i can use Private Frameworks of Apple in order to know the operations being performed on iPhone Safari( i.e History the Tabs being browsed and time spend on browsing kind of info).
I have gone through some of the things like Dumping Private frameworks. But i don't know which Framework to Dump i guess WebKit may help.
Can some body please give the needful info to solve this problem.
i have imported the Dumped classes to Frameworks i.e WebHistory.h, WebHistoryItem.h, WebPreferences.h
Please let me know in case i miss anything
#import "WebHistory.h"
- (void)viewDidLoad {
[super viewDidLoad];
WebHistory *history=[WebHistory optionalSharedHistory];
NSLog(@"%@",history);
}
A: You can't access the Safari History. Apps are sandboxed.
If this is for an in-house app, then you might be able to jailbreak the phones and figure out a way around the sandboxing.
Update:
see this SO link: how-to-access-iphone-safari-history-in-an-app
A: We can find the history.plist in /var/mobile/Media/Safari/ and this we can read in jailbreaken iPhone.
A: I think you need a good web developer who will create the web page in such a way so that you can communicate with javascript and get the message you want to get. And for dumping the framework I think you should get with uikit+ webkit framework.
I hacked my framework by using this link - http://aralbalkan.com/2106 I hope this will help to you .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Asp.net custom control and javascript function There's a custom a asp.net control named PhoneTextBox2. It uses ext.net library, but I doesn't matter.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PhoneTextBox2.ascx.cs"
Inherits="Loginet.Web.Controls.PhoneTextBox2" %>
<script type="text/javascript">
var <%=ClientID%>_getNumber = function () {
return alert( 'some value');
}
</script>
<ext:CompositeField runat="server" ID="eCompositeField">
<Items>
<ext:Label ID="PhoneBoxTitle" runat="server" />
</Items>
</ext:CompositeField>
In aspx page I call the javascript method of PhoneTextBox2 by this way
<uc:PhoneTextBox2 runat="server" ID="txtb" />
<ext:Button Text="test" runat="server">
<Listeners>
<Click Handler="#{txtb}_getNumber();"></Click>
</Listeners>
</ext:Button>
#{txtb}_getNumber() is the unique name of the javascript function, and #{txtb} - is the unique name of the PhoneTextBox2.
What can I do to call getNumber by dot?
<Click Handler="#{txtb}.getNumber();">
UPDATE:
public partial class PhoneTextBox2 : System.Web.UI.UserControl {
/// <summary>
/// Допускаются ли, чтобы все поля были пустыми
/// True - Допускаются. Используется тогда, когда данные из этого контрола необязательные.
/// </summary>
public bool EnableEmptyValues { get; set; }
public string Title { get; set; }
protected void Page_Load(object sender, EventArgs e) {
txtCountryCode.AllowBlank = EnableEmptyValues;
txtCityCode.AllowBlank = EnableEmptyValues;
txtMainPhoneNumber.AllowBlank = EnableEmptyValues;
if (!IsPostBack && !Ext.Net.ExtNet.IsAjaxRequest) {
PhoneBoxTitle.Text = Title;
if (!string.IsNullOrWhiteSpace(DataSource)) {
string[] phoneNumberArray = DataSource.Split('-');
if (phoneNumberArray.Length >= _standartDimension) {
txtCountryCode.Text = phoneNumberArray[0];
if (txtCountryCode.Text[0] == _plus) {
txtCountryCode.Text = txtCountryCode.Text.Remove(0, 1);
}
txtCityCode.Text = phoneNumberArray[1];
txtMainPhoneNumber.Text = phoneNumberArray[2];
if (phoneNumberArray.Length >= _extraDimension) {
txtExtraPhoneNumber.Text = phoneNumberArray[3];
}
}
}
}
}
public string DataSource { get; set; }
private const string _phoneNumberMask = "+{0}-{1}-{2}-{3}";
private const char _plus = '+';
private const int _standartDimension = 3;
private const int _extraDimension = 4;
public string Number {
get {
if (!string.IsNullOrWhiteSpace(txtCountryCode.Text) &&
!string.IsNullOrWhiteSpace(txtCityCode.Text) &&
!string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text)) {
//Если добавочный номер пустой, то возвратить значения без него
if (!string.IsNullOrWhiteSpace(txtExtraPhoneNumber.Text))
return string.Format(_phoneNumberMask, txtCountryCode.Text, txtCityCode.Text, txtMainPhoneNumber.Text, txtExtraPhoneNumber.Text);
string phoneNumber = string.Format(_phoneNumberMask, txtCountryCode.Text, txtCityCode.Text, txtMainPhoneNumber.Text, string.Empty);
return phoneNumber.Remove(phoneNumber.Length - 1);
}
return string.Empty;
}
}
public bool IsEmpty {
get {
return (string.IsNullOrWhiteSpace(txtCountryCode.Text) &&
string.IsNullOrWhiteSpace(txtCityCode.Text) &&
string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text) &&
string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text));
}
}
/// <summary>
/// Validate
/// </summary>
public void Validate() {
if (EnableEmptyValues) {
if (!IsEmpty && Number == string.Empty)
MarkInvalid();
else
MarkValid();
}
else {
if (IsEmpty)
MarkInvalid();
else {
if (Number == string.Empty)
MarkInvalid();
else
MarkValid();
}
}
}
public void MarkInvalid(string msg = null) {
txtCountryCode.MarkInvalid(msg);
txtCityCode.MarkInvalid(msg);
txtMainPhoneNumber.MarkInvalid(msg);
txtExtraPhoneNumber.MarkInvalid(msg);
}
public void MarkValid() {
txtCountryCode.MarkAsValid();
txtCityCode.MarkAsValid();
txtMainPhoneNumber.MarkAsValid();
txtExtraPhoneNumber.MarkAsValid();
}
public const string InvalidCheckBoxCssStyle = "border-color:#C30; background: url('/extjs/resources/images/default/grid/invalid_line-gif/ext.axd') repeat-x scroll center bottom white; width: 40px !important;";
public const string ValidCheckBoxCssStyle = "border-color:#000; background: none repeat scroll 0 0 transparent;";
}
Note, in my case I can't use the server side property Number because of feature of ext.net. Therefore I need to use javascript to get Number.
A: Handler points to a .NET custom method/delegate, and they can't have period signs in their names.
You can extend any object type, for example:
String.prototype.getNumber = function() {
alert('here: ' + this);
};
and then
'txtElement'.getNumber();
so you can change your code to
<Click Handler="'{txtb}'.getNumber();">
A: There's no need to assign a dynamic name to your javascript function. Simply register the method when the first control is created, and check to see if it's already registered when the next instance of the control is created.
Registering a script block:
if (!Page.ClientScript.IsClientScriptBlockRegistered("getNumberScript"))
Page.ClientScript.RegisterClientScriptBlock(GetType(), "getNumberScript", "getNumber = function () { return alert( 'some value'); }", true);
Registering an include file (external js):
if (!Page.ClientScript.IsClientScriptIncludeRegistered("getNumberScript"))
Page.ClientScript.RegisterClientScriptInclude("getNumberScript", "getNumberScript.js");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make a select option change options in another select I have two drop down. SelCurrentManuf and selCurrentModel. I want the option in selCurrentModel to change depending on the option selected in selCurrentManuf. How do i do it?
<asp:DropDownList runat="server" ID="selCurrentManuf"></asp:DropDownList>
<asp:DropDownList runat="server" ID="selCurrentModel"></asp:DropDownList>
This is how i am currently populating selCurrentModel
Public Sub PopulateCurrentModel()
Dim mySelectQuery As String = "SELECT * FROM Model where ManufID = "+ selCurrentManuf.Text+";"
Dim myConnection As New MySqlConnection(Session("localConn"))
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader()
While myReader.Read
Dim newListItem As New ListItem
newListItem.Value = myReader.GetString("Modelid")
newListItem.Text = myReader.GetString("desc")
selCurrentModel.Items.Add(newListItem)
End While
myReader.Close()
myConnection.Close()
End Sub
but it only populates the first selected manuf, and doesnt change after
Private Sub selCurrentManuf_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles selCurrentManuf.SelectedIndexChanged
PopulateCurrentModel()
End Sub
A: Change selCurrentManuf.Text to selCurrentManuf.SelectedItem.Value
PLEASE NOTE: You have a SQL Injection security vulnerability. Please search on SQL Injection and fix.
A: This was all that was needed! autopostback="true" !!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the proper way to work with files in C++? I'm studying C++, now I'm reading about working with files. As I have read, there is quite a lot of variants. So I wanna ask, what is the right way to work with files in C++? Using fstream(ifstream and ofstream)? I have read some opinions that fopen works much faster, so it is better to use it, but it will be no C++.
Thanks for attention!
A: Use ifstream and ofstream when working in C++. It should not be much slower than FILE*, but is much safer.
See this related question.
A: I agree with Juraj's assessment of i/ofstream vs. FILE*, I just wanted a word about memory-mapped files. In Boost.SpiritClassic, there's a lesser-known gem called a mmap_file_iterator:
http://www.boost.org/doc/libs/1_47_0/boost/spirit/home/classic/iterator/file_iterator.hpp
I believe that it will memory-map your file if you're in a windows or POSIX environment, and it is a RandomAccessIterator, rather than a Input/OutputIterator.
As for what method is "proper", it all depends on your application's requirements. It is definitely good to explore all of your options and compare the results along as many dimensions as you can conceive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I make MVC discard requests with verbs other than specified in the constraint? In my MVC application I want behavior as was previously specified in <httpHandlers> in web.config, namely that if I register a handler like this:
<system.webServer>
<handlers>
<add name="processData" verb="POST" path="processData" type="RightType, RightAssembly"/>
</handlers>
</system.webServer>
then all requests to /processData that have verbs other than "POST" result in HTTP 404.
I tried to register a route like this:
routes.MapRoute(
@"ProcessData", @"processData",
new { controller = @"Api", action = @"ProcessData" },
new { httpMethod = new HttpMethodConstraint( "POST" ) } );
and now once a request has a verb other than POST the route isn't matched, route resolution falls through and proceeds to the default page.
How do I make MVC produce an HTTP error message (code 404 or anything like that) once a path matches but a verb mismatches?
A: You could just register another route with the verbs that you don't want and make that lead to a NotFound action.
A: Routing works by following routes in the order specified until it finds one that matches. By adding the constraint you make this route fail and so it goes down the list to find the next matching route (your default).
To get the behaviour you want you need to have your route catch the request and then handle the error.
Take the constraint out of the route and on your controller do the following:
[HttpPost]
public ActionResult processData(myModel myPostedModel)
{
DoStuff();
Return View();
}
public ActionResult processData()
{
throw new HttpException(404);
}
I am assuming that you do model binding on your action method here because you do need differing method signatures. If not then you'll need to take off the HttpPost attribute and test for the request method there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I determine touch screen device in a bash script? I am trying out the eGalax touch screen driver for my touch screen, as an alternative to the evdev/xinput_calibrator combination.
The calibration tool that comes with the eGalax driver, TKCal, takes the device to which the touch screen is connected as a command line argument.
Now I would like to start the calibration tool from a bash script. Is there some smart way to determine the device within the script, instead of hard coding "/dev/hidraw0" as in this example:
TKCal /dev/hidraw0 Cal
I presume that I can't rely on the touch screen landing on hidraw0 every time, can I? If I run my software on a different system, with a mouse and a keyboard and touch screen, I guess I have to handle that the devices can be conneted to different hdrawX devices. Please correct me if I am wrong.
Thank you very much!
/Fredrik Israelsson
A: Try looking at /sys/class/hidraw/hidraw*/device/uevent.
A: The guys developing the eGalax drive told be to try a much simpler solution:
Write a udev rule that will map the touch screen to a device name of my choice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Asynchronous ADO.NET I'm trying to write an asynchronous server that queries a SQL Server database and am concerned that my DB side is too synchronous. Specifically, I can call ExecuteReader asynchronously but cannot then call reader.Item asynchronously and is where 57% of the time is spent (blocking my precious thread!).
Is this the most asynchronous I can do with ADO.NET or is there an asynchronous way to do reader.Item as well?
A: Looks like this issue is to be fixed in the next version of the framework:
DbDataReader.ReadAsync
and
DbDataReader.NextResultAsync
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: FreeMarker how to find corresponding java classes I am investigating large project that uses FreeMarker. I am newbie to FreeMarker. How I can find which classes of java are used to receive values for templates? Investigate all project seems enormous work.
Thanks.
May be need some plugins for Eclipse?
A: FreeMarker is a typical "dynamic language", which means refactoring/changing is hard. The templates don't declare what they expect to be in the data-model. Furthermore, when a template tries to read a value from the data-model, like with ${foo.bar}, it could mean foo.get("bar") or foo.getBar() or whatever the ObjectWrapper used makes possible, and it's only decided when the template is executed. Certainly you will need to fall back to good-old search-and-replace and lot of testing (a good test suite is essential...) if you change something. And of course, you could look at the place in the program where the data-model is built, and see what was put into it. Or dump the data-model somehow on runtime.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to draw a ImageView in the middle of the screen? (programatically) I want to draw a simple ImageView in the middle of the screen, horizontally and vertically. But i want to do it without using XML files, i need to do it programatically.
I tryed with the next code, but it doesn't works fine, it draws the image a little to the right and a little to the bottom. How to solve it?
ARImage = new ImageView(getApplicationContext());
ARImage.setImageResource(R.drawable.x);
rl.addView(ARImage); //rl is the relative layout that it's inserted into a frame layout
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int w = display.getWidth();
int h = display.getHeight();
RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
position.leftMargin = (int)(w/2);
position.topMargin = (int)(h/2);
ARImage.setLayoutParams(position);
A: It works for me like this:
package pete.android.study;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class Main extends Activity {
/*
* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView ARImage = new ImageView(getApplicationContext());
ARImage.setImageResource(R.drawable.icon);
RelativeLayout rl = new RelativeLayout(this);
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int w = display.getWidth();
int h = display.getHeight();
RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ARImage.setLayoutParams(position);
position.addRule(RelativeLayout.CENTER_IN_PARENT);
rl.addView(ARImage, position);
setContentView(rl);
}
}
A: Try to use
position.leftMargin = (int)(w/2 - whalf);
position.topMargin = (int)(h/2 - hhalf);
where whalf and hhalf are halfs of your image parameters.
A: I don't think you can set the left and top margin like that:
position.leftMargin = (int)(w/2);
position.topMargin = (int)(h/2);
Try setting the margins like this:
position.setMargins((int)(w/2), (int)(h/2), 0, 0); // left, top, right, bottom
A: Knowing that it is inside of RelativeLayout, you can place it in center of this layout:
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
rl.addView(ARImage, lp);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to upload a file in a directory containing the record ID on Symfony I have a file upload form in the frontend.
At the moment, when a new record is created, the file is uploaded to
%sf_data_dir%/files/
but due to some business logic I need the file to be uploaded to
%sf_data_dir%/files/%record_id%/
Therefore the uploaded file should be saved AFTER the record is created.
How can I achieve that?
A: If you use file upload, your form certainly make use of the sfValidatorFile (if not, that's wrong):
$this->validatorSchema['image'] = new sfValidatorFile(array(
'required' => true,
'mime_types' => 'web_images',
));
This validator return a sfValidatedFile instance that can be saved anywhere you want (it's safer than move_uploaded_file, there is checks on the directory, filename...).
In your action (or in the form, as you want/need), you can now do this:
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind(
$request->getParameter($form->getName()),
$request->getFiles($form->getName())
);
if ($form->isValid())
{
$job = $form->save();
// Saving the file to filesystem
$file = $form->getValue('my_upload_field');
$file->save('/path/to/save/'.$job->getId().'/myimage.'.$file->getExtension());
$this->redirect('job_show', $job);
}
}
Don't hesitate to open sfValidatedFile to see how it work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check SQLite Database exists Is there a way of checking that a sqlite database exists in blackberry? I have seen a suggestion that you can check it through the sdcard by going to media -> explore -> media options, however I am working on a simulator and do not have a sdcard.
A: If you are testing on Simulator you have to attach SD card,for this go to
Simulate->Chage SD card->Add Directory in your simulator window header tabs.
To check your database go through your directory after adding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create subitems menus under the application name on OSX? How to add TMenuItem under Project1 and above Quit on the screenshot below?
I have created a TMenuBar with property UseOSMenu checked.
The first TMenuItem I added is the second one in the main bar...
A: You can do this by assigning a TMenuBar of IItemsContainer implementing class to the Application.ApplicationMenuItems property.
Example:
If there was a menu bar component on the form called MenuBar1, then you would just call the following in your forms constructor (or OnCreate).
Application.ApplicationMenuItems := Menubar1;
You can then have a second TMenuBar component to define the other menu items.
I'd point you to the wiki topic on the ApplicationMenuItems property, but it has no additional help...
http://docwiki.embarcadero.com/VCL/XE2/en/FMX.Forms.TApplication.ApplicationMenuItems
A: I have created a unit to try to manage what I would like...
With it, I can use a specific TMenuItem... and move its subitems to the application submenu... (I still don't know how to add one from scratch...)
I also use the answer from Mehmed Ali to manage the separators...
unit uMenu;
interface
uses
FMX.Dialogs, System.SysUtils,
FMX.Menus
{$IFDEF MACOS}
,Macapi.ObjectiveC,MacApi.AppKit,MacApi.Foundation,FMX.Platform.Mac
{$ENDIF}
;
type
ManageMenu = class
private
{$IFDEF MACOS}
class procedure FixSeparatorItemsForMenuItem (MenuItem: NSMenuItem);
class procedure MoveItemsToMacApplicationMenu(source, target: NSMenuItem); overload;
class procedure MoveItemsToMacApplicationMenu(index: Integer); overload;
{$ENDIF}
public
class procedure FixSeparatorItemsForMac;
class procedure MoveItemsToMacApplicationMenu(index: Integer; menu: TMainMenu); overload;
class procedure MoveItemsToMacApplicationMenu(index: Integer; menu: TMenuBar); overload;
end;
implementation
{ ManageMenu }
{$IFDEF MACOS}
class procedure ManageMenu.FixSeparatorItemsForMenuItem(MenuItem:NSMenuItem);
var
i : Integer;
subItem: NSMenuItem;
begin
if (MenuItem.hasSubmenu = False) then exit;
for i := 0 to Pred(MenuItem.submenu.itemArray.count) do
begin
subItem := MenuItem.submenu.itemAtIndex(i);
if (subItem.title.isEqualToString(NSSTR('-'))= True) then
begin
MenuItem.submenu.removeItemAtIndex(i);
MenuItem.submenu.insertItem(TNSMenuItem.Wrap(TNSMenuItem.OCClass.separatorItem), i);
end
else
begin
FixSeparatorItemsForMenuItem(subItem);
end;
end;
end;
{$ENDIF}
class procedure ManageMenu.FixSeparatorItemsForMac;
{$IFDEF MACOS}
var
NSApp : NSApplication;
MainMenu: NSMenu;
AppItem : NSMenuItem;
i : Integer;
{$ENDIF}
begin
{$IFDEF MACOS}
NSApp := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication);
MainMenu := NSApp.mainMenu;
if (MainMenu <> nil) then
begin
for i := 0 to Pred(MainMenu.itemArray.Count) do
begin
AppItem := mainMenu.itemAtIndex(i);
FixSeparatorItemsForMenuItem(AppItem);
end;
end;
{$ENDIF}
end;
{$IFDEF MACOS}
class procedure ManageMenu.MoveItemsToMacApplicationMenu(source, target: NSMenuItem);
var
iLoop, iMax: Integer;
subItem : NSMenuItem;
begin
if (source.hasSubmenu = False) then exit;
iMax := Pred(source.submenu.itemArray.count);
for iLoop := iMax downto 0 do
begin
subItem := source.submenu.itemAtIndex(iLoop);
source.submenu.removeItemAtIndex(iLoop);
target.submenu.insertItem(subItem, 0);
end;
// Hide the parent
source.setHidden(True);
end;
{$ENDIF}
{$IFDEF MACOS}
class procedure ManageMenu.MoveItemsToMacApplicationMenu(index: Integer);
var
NSApp : NSApplication;
MainMenu: NSMenu;
source : NSMenuItem;
target : NSMenuItem;
begin
NSApp := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication);
MainMenu := NSApp.mainMenu;
if (MainMenu <> nil) then
begin
begin
if (MainMenu.itemArray.count > 1) then
begin
source := mainMenu.itemAtIndex(Succ(index));
target := mainMenu.itemAtIndex(0);
MoveItemsToMacApplicationMenu(source, target);
end;
end;
end;
end;
{$ENDIF}
class procedure ManageMenu.MoveItemsToMacApplicationMenu(index: Integer; menu: TMainMenu);
begin
{$IFDEF MACOS}
MoveItemsToMacApplicationMenu(index);
{$ELSE}
// (menu.Children[Succ(index)] as TMenuItem).Visible := False;
// menu.RemoveObject(...);
// ... I don't knwo how to remove items on Windows ;o(((
{$ENDIF}
end;
class procedure ManageMenu.MoveItemsToMacApplicationMenu(index: Integer; menu: TMenuBar);
begin
{$IFDEF MACOS}
MoveItemsToMacApplicationMenu(index);
{$ELSE}
if (menu.ChildrenCount > Succ(index)) and (menu.Children[Succ(index)] is TMenuItem) then
begin
// (menu.Children[Succ(index)] as TMenuItem).Visible := False;
// menu.RemoveObject(...);
// ... I don't knwo how to remove items on Windows ;o(((
// menu.BeginUpdate;
// menu.RemoveObject((menu.Children[Succ(index)] as TMenuItem));
// menu.RemoveFreeNotify((menu.Children[Succ(index)] as TMenuItem));
// menu.DeleteChildren;
// (menu.Children[Succ(index)] as TMenuItem).View.Visible := False;
// .Free;
// (menu.Children[Succ(index)] as TMenuItem).Destroy;
// menu.EndUpdate;
end;
{$ENDIF}
end;
end.
It works as expected and it is what I want on OSX...
procedure TfrmMain.FormActivate(Sender: TObject);
begin
if not bAlreadyActivated then
begin
bAlreadyActivated := True;
ManageMenu.FixSeparatorItemsForMac;
ManageMenu.MoveItemsToMacApplicationMenu(0, MainMenu1);
end;
end;
but now, I have an issue on Windows because whatever I try, I still have the menu I added for Mac displayed under Windows... ;o(
A: As of Delphi XE7, the Application.ApplicationMenuItems property no longer exists.
You now have to create a TMainMenu item to get the expected result, no need to assign it. Just drop a TMainMenu on to your main form and add your items, and they will appear in the OSX application menu.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Cant Post To Facebook with Graph API iPhone i have implemented this sample code below to get a connection to the user feed post
- (void)viewDidLoad
{
[super viewDidLoad];
facebook = [[Facebook alloc] initWithAppId:@"197765190297119" andDelegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
}
and this sample code is called when the user logs in... it calls now by a button pressed for check, but dosent do any, perhaps i can get a dialog feed insted
NSString *str=@"Your String to post";
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
str,@"message",
@"Test it!",@"name",
nil];
Facebook *fb = [[Facebook alloc] init];
[fb requestWithGraphPath:@"me/feed" // or use page ID instead of 'me'
andParams:params
andHttpMethod:@"POST"
andDelegate:self];
A: This is a walkthrough of uploading an image to the facebook wall. I copied this out of an older application, the current facebook API works a little bit different. I think you can see my main point of using a shared facebook object, which you use to do the authentication and also the requests to the API. I took out a few things to make it easier to understand. Apple actually wants you to check for an existing internet connection. I hope it helps.
@synthesize facebook;
//login with facebook
- (IBAction) facebookButtonPressed {
if (!facebook || ![facebook isSessionValid]) {
self.facebook = [[[Facebook alloc] init] autorelease];
NSArray *perms = [NSArray arrayWithObjects: @"read_stream", @"create_note", nil];
[facebook authorize:FACEBOOK_API_KEY permissions:perms delegate:self];
}
else {
[self fbDidLogin];
}
}
//upload image once you're logged in
-(void) fbDidLogin {
[self fbUploadImage];
}
- (void) fbUploadImage
{
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
resultImage, @"picture",
nil];
[facebook requestWithMethodName: @"photos.upload"
andParams: params
andHttpMethod: @"POST"
andDelegate: self];
self.currentAlertView = [[[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"Facebook", @"")
message:NSLocalizedString(@"Uploading to Facebook.", @"")
delegate:self
cancelButtonTitle:nil
otherButtonTitles: nil] autorelease];
[self.currentAlertView show];
}
//facebook error
- (void)request:(FBRequest*)request didFailWithError:(NSError*)error
{
[self.currentAlertView dismissWithClickedButtonIndex:0 animated:YES];
self.currentAlertView = nil;
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"Error", @"")
message:NSLocalizedString(@"Facebook error message", @"")
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"OK", nil];
[myAlert show];
[myAlert release];
}
//facebook success
- (void)request:(FBRequest*)request didLoad:(id)result
{
[self.currentAlertView dismissWithClickedButtonIndex:0 animated:YES];
self.currentAlertView = nil;
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"Facebook", @"")
message:NSLocalizedString(@"Uploaded to Facebook message", @"")
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"OK", nil];
[myAlert show];
[myAlert release];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Walking, bicycle and public transport directions with time required in each mode , iPhone I am using following url to get driving directions between two locations.
NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.google.com/maps?output=dragdir&saddr=%@&daddr=%@", saddr, daddr];
What changes need to be done in above query to get directions for bicycle, walking or public transport and corresponding distance, time required between two places?
Thanks in advance for any help.
A: You must use the "dirflg=?" parameter, where "?" can be:
dirflg Route type.
dirflg=h Switches on "Avoid Highways" route finding mode.
dirflg=t Switches on "Avoid Tolls" route finding mode.
dirflg=r Switches on "Public Transit" - only works in some areas. Can also set date and time info described below.
dirflg=w Switches to walking directions - still in beta.
dirflg=b Switches to biking directions - only works in some areas and still in beta.
There are many other params available, read the Google Maps Parameters doc, but of course not all of them are supported by the Maps native API (which is updated at every iOS release). Is up to you to test them as the official Apple doc is not always up to date with all features.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Dependency injection into a static class
Possible Duplicate:
Configure Property of a static class via spring .net
I want to inject the value for a property inside the static class using spring .net.
Code snippet:
Public static Abc
{
Public static IInterface IInterface{get;set;}
}
here i want to inject the IInterface value inside the Abc staic class though spring .net config.
A: I doubt if you can do it.
Static classes don't really work well with dependency injection.
You will be better off creating the class as a normal class and setting it up as a singleton within the container. I'm pretty sure spring.net will allow this..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Struts2 - how to generate internationalized url's? I have an application that needs to redirect to several internationalized urls, ie
*
*www.mydomain.com/us/myapp/xxx.action
*www.mydomain.com/fi/myapp/xxx.action
*dwww.mydomain.com/de/myapp/xxx.action
We have a proxy server where the url is mapped to myapp/xxx.action?country=us and redirected to the application server. The problem is how to redirect to the next action with the format above?
Now the url for the next action is generated by using country from url and adding context path and action name and opened by javascript in jsp.
Example:
<body onload="javascript:top.location='${generatedPath}';return true;"></body>
Example form submit:
<s:form id="form" action="%{generatedPath}" theme="simple" method="post" includeContext="false">
Would like to do this in a less hackish way, and have tested a bit with struts.xml and type redirectAction, but cannot seem to be able to generate the url above, with the country before context path.
I have not found any struts2 documentation describing this, but are unsure if im looking at the right place as well? Should this be handled elsewhere?
A: I think the following discussion can help you:
How to do dynamic URL redirects in Struts 2?
Here, your result will look like:
<result name="redirect" type="redirect">${url}</result>
And, the action would be:
private String url;
private String country;
public void setCountry(String country) {
this.country = country;
}
public String getUrl()
{
return url;
}
public String execute()
{
url = "www.mydomain.com/" + country + "/myapp/xxx.action";
return "redirect";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is there a way to actively listen on bluetooth audio channel? I want to be able to use the bluetooth headset as a microphone.
Is it possible to set it to microphone mode?
A: Yes, you have to use startBluetoothSco()
This method can be used by applications wanting to send and received audio to/from a bluetooth SCO headset while the phone is not in call.
A: AudioManager localAudioManager = (AudioManager) getSystemService("audio");
localAudioManager.setBluetoothScoOn(true);
localAudioManager.startBluetoothSco();
localAudioManager.setMode(2);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find the count of elements using jQuery I have a span tag and that holds some n number of span tags.. can I get the number of span tags available with in the parent span using Jquery.
example:
<span class="x">
<span id="1">one</span>
<span id="2">two</span>
<span id="3">three</span>
</span>
now i should find the count of number of span tags inside the parent span and my output is 3 according to the above scenario.
please help me..
A: $("span.x").children("span").size()
Demo: http://jsfiddle.net/AZXv3/
A: From the documentation you can use length or size(). You can chain jquery selectors with find to count the inner spans. For example,
<script>
var n = $(".x").find("span").length;
alert(n);
</script>
A: my version :)
$('span.x > span').length
A: Try:
$("#id od 1st span").children("span").size();
I think this will help you.
A: $('.x span').length
this should work
http://jsfiddle.net/6kWdf/
A: You could use this for example:
$('#showTotalBarcodeCnt').html($("#barcodeLabelList").find("label").length);
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How do I create a route for matching all paths starting with a given prefix? In my MVC application I want to create a route such that when a user requests a URL starting with a prefix some specific action is invoked.
For example, I want a route that would map processData{whatever} onto an action so that when a user requests processData, processData.asmx or processDataZOMG or whatever else with processData prefix that action is invoked.
I tried the following route
routes.MapRoute(
@"ProcessData", @"processData*", //<<<< note asterisk
new { controller = @"Api", action = @"ProcessData" } );
but it doesn't match processData and anything with that prefix - route matching falls through and the request is redirected to the main page.
How do I make a route that matches all paths with a specific prefix onto a specific controller-action pair?
A: Try the following: Update: This solution does not work, please refer to the solution I offer in my comment to this answer.
routes.MapRoute(
@"ProcessData", @"processData/{*appendix}", //<<<< note asterisk
new { controller = @"Api", action = @"ProcessData" } );
A: You could use route constraints:
routes.MapRoute(
"ProcessData", // Route name
"{token}", // URL with parameters
new { controller = "Api", action = "ProcessData" }, // Parameter defaults
new { token = @"^processdata.*" } // constraints
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a reason why ('img').load doesn't work (jQuery)? I have a set of images that I wanted to load first before executing the next line of code. The code is like:
$('div.some_class img').load(function() {
// do something to div.some_class img
});
However, the images do not load before executing the commands. When I try (window).load though, it works.
My question is, why doesn't ('div.some_class img').load work? Or is it because I'm using a class selector which is the slowest way to select an element?
A: from http://api.jquery.com/load-event/
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load()
shortcut is to execute a function when an image (or collection of
images) have completely loaded. There are several known caveats with
this that should be noted. These are:
*
*It doesn't work consistently nor reliably cross-browser
*It doesn't fire correctly in WebKit if the image src is set to the same src as before
*It doesn't correctly bubble up the DOM tree
*Can cease to firefor images that already live in the browser's cache
Hope this answers your question.
A: https://gist.github.com/268257 - this is a jQuery plugin to check for all images loaded
I don't think that load checks for the image to have actually loaded as much as that the tag has loaded? I had the same problem so used the above plugin
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facebook PHP API constructor - is local variable ignored for a reason? Caveat : I am not a PHP guru by any stretch - hopefully someone can explain what this code is doing - why is he applying something to a local variable ($state) and then ignoring it? This code is in the 3.1.1 php sdk and I noticed it when debugging an issue with js sdk and php interactions during an authResponse trigger.
public function __construct($config) {
$this->setAppId($config['appId']);
$this->setApiSecret($config['secret']);
if (isset($config['fileUpload'])) {
$this->setFileUploadSupport($config['fileUpload']);
}
$state = $this->getPersistentData('state');
if (!empty($state)) {
$this->state = $this->getPersistentData('state');
}
}
Is it as simple as he meant to use $this->state = $state?
A: It isn't being ignored. On the next line, it's used as a parameter for empty.
Parameters to empty must be variables (see manual), which is why it's being used like that.
However, they could probably have used it in the $this->state assignment as well. Why they didn't I wouldn't know.
A: It's an oversight on the programmers side I think. He could and should have assigned $state to $this->state.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Auto-web test : ExpectedResponseUrl error While running my auto-web test, I received this message :
Response URL Validation The value of the ExpectedResponseUrl properity 'http://localhost:4800/FirstPage.aspx' isn't equal to the effective response URL 'http://localhost:4800/SecondPage.aspx'. The QueryString parameters have been ignored.
Note: for the redirection, I am using:
Response.Redirect(Url2, false);
event while changing the parameter with true, I receive the same message.
A: I found the solution, and I didn't understand why! but it is Oky :
The solution is to use Server.Transfere() instead of Response.Redirect()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting.bundle only for app store configuration - iOS I'm trying to find a way to have setting.bundle for Debug Configuration but not to have it for App Store release.
I tried to write a pre build script that deletes the Setting.bundle file in case it's not Debug, however because the setting.bundle is being copied as part of the "Copy Bundle Resource" phase, it issues error.
Any way to achieve it ?
A: Create a new Target for the AppStore release. In the file inspector of the Settings.bundle deselect this new target in "Target Membership".
A: Or add a build phase that runs a build script that deletes the settings bundle for your release config:
#!/bin/bash
if [ "$CONFIGURATION" == "Release" ]; then
rm -rf ${CODESIGNING_FOLDER_PATH}/Settings.bundle
fi
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JSF 2.0/Facelets - JavaScript characters get encoded as html entities I'm using jQuery inside Faceletes template. The problem is that special characters are encoded as html entities, eg if (y >= top) { to if (y >= top) {
I'm using JSF 2.0 with Glassfish 3.
A: Try this
<script type="text/javascript">
//<![CDATA[
//your script here
//]]>
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GridView Paging is not working? I have a grid in that i am using this code on page init
UpagedList = new PagedListAdapter<User>(UserListGridView);
UpagedList.MaxRows = ConfigurationService.DefaultPageSize;
UserListGridView.PageIndexChanged += delegate
{
Presenter.FillDataOnDropDown();
};
UserListGridView.Sorting += new GridViewSortEventHandler(UserListGridView_Sorting);
UserListGridView.Sorted += delegate {Presenter.SortChanged(); };
my grid code:
<asp:GridView CssClass="Greed" ID="UserListGridView" runat="server" DataSourceID="ListUserDataSource"
AutoGenerateColumns="false" EmptyDataText="No data found" DataKeyNames="Id" OnSorting="UserListGridView_Sorting" AllowSorting="True"
PageSize="25" AllowPaging="True" GridLines="None" EnableViewState="false">
<Columns></Columns>
</asp:GridView>
Paging is not working...? what else i need to do for paging.. when i am clicking on 2nd page page is not getting change but data is getting appended in grid
A: I think you missing the OnPageIndexChanging event in the gridview. Try adding this to your gridview OnPageIndexChanging="UserListGridViewIndexChanging"
and in the backend code
protected void UserListGridViewIndexChanging(object sender, GridViewPageEventArgs e)
{
UserListGridView.PageIndex = e.NewPageIndex;
Bind(); // you data bind code
}
hope this helps
A: protected void UserListGridViewIndexChanging(object sender, GridViewPageEventArgs e)
{
UserListGridView.PageIndex = e.NewPageIndex;
UserListGridView.DataBind();
Bind(); // you data bind code is here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add comments to Drupal 7 in PHP using Drupal Services Module As far as I know, Drupal Services Module can allow PHP scripts to communicate with Drupal 7. But how to add a comment to a post using this module?
Example will be appreciated.
A: here is the testcode that does exactly that
http://drupalcode.org/project/services.git/blob/refs/heads/7.x-3.x:/tests/functional/ServicesResourceCommentTests.test#l100
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: .HTACCESS REWRITE Hi I need to rewrite this :
http://www.xxx.co.uk/holidays/resort/courchevel/chalet/chalet-xx/pricing.html
to this:
http://www.xxx.co.uk/holidays/courchevel/chalet-xx/pricing.html
though the chalet name and resort changes so i would need the $1 and $2 in there i think
thanks in advance for any help
A: If i've understood your question correctly, something along these lines should do it (based on your edit)...
^holidays/([^/]+)/([^/]+)/pricing.html /holidays/resort/$1/chalet/$2/pricing.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: ERROR/ActivityManager(98): Reason: keyDispatchingTimedOut i playing live video from api in my app. when i click play video then Progress dialog will come in between progress when i press back button 2 or 3 times of device then after some times it will give this error
ERROR/ActivityManager(98): Reason: keyDispatchingTimedOut
so how i can handle this error plz give me solution.
Thnax in advace.
A: This happens due to many reasons. I can't diagnose without your stack traces.
The most common reason for this error is when you are doing an CPU intensive task in a UI thread. Use threading or AsyncTask to delegate such CPU intensive work.
A: Is any ANR thrown? If so go in DDMS->File Explorer -> data/anr/traces.txt and check at which point ANR occurred.
keyDispatchingTimedOut when you are doing heavy calculation on main thread. Move what you are doing in a new background thread (if possible)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why doesn't this work (NavigationService on Singleton)? public class Navigator : PhoneApplicationPage
{
private static Navigator _instance;
private static object _lock = new object();
public static Navigator Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new Navigator();
}
return _instance;
}
}
private set
{
lock (_lock)
{
_instance = value;
}
}
}
private Navigator(){}
public bool NavigateTo(string uri)
{
lock (_lock)
{
return NavigationService.Navigate(new Uri(uri, UriKind.Relative));
}
}
}
It is called in a ViewModel class:
Navigator.Instance.NavigateTo("/NotePage.xaml");
So I've got this, and NavigationService.Navigate(..) throws a NullReferenceException.
How can I fix this / what is an alternative? I want to use the NavigationService from a ViewModel class.
I'd prefer a solution without the need for installing more componets (MVVM light). If that is absolutely not possible I'll check out the Messenger / Message class.
EDIT
I pretty much gave up. I solved my problem by creating a style for hyperlink button which can wrap around everything.
A: your singleton is not thread safe. look at this implementation:
http://www.yoda.arachsys.com/csharp/singleton.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Counting total per day with my result in SQL I have 50 rows/entrys in my table Orders. I have a column, that holds when the order is claimed at, named claimed_at.
The date in this field are in this format: 2011-10-03 07:07:33
This is in the format (yy/mm/dd time).
I also have a column called price, this price is how much they paid.
I would like to display totals per day.
So for 6 orders from the date 2011-10-03, it should take the 6 order's price value, and plus them together.
So I can display:
2011-10-03 -- Total: 29292 Euros
2011-10-02 -- Total: 222 Euros
2011-09-28 -- Total: 4437 Euros
How can i do this?
A: You need to use aggregate functionality of MySQL in conjuction with some DATE conversion.
SELECT DATE(claimed_at) AS day
, SUM(price) AS total
FROM Orders
GROUP BY day
A: Create a new field say day with DATE_FORMAT(claimed_at,'%Y-%m-%d') AS day , sum the price and group by day so you will get the result you want.
Something like
SELECT DATE_FORMAT(claimed_at,'%Y-%m-%d') AS day,SUM(price) as total FROM orders GROUP BY day ORDER BY day DESC
A: Use grouping like this :
SELECT claimed_at, SUM(price) AS total
FROM Orders
GROUP BY claimed_at
You need to use function to get only date part(not time) in grouping. I dont know which function is used in mysql, in MSSQL it's CONVERT() function.
A: SELECT TRUNC(claimed_at), SUM(PRICE)
FROM my_orders_table
GROUP BY TRUNC(claimed_at)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: FileIOException: File already exists error on blackberry i get thumbnail image using fileconnection.
I get image using thread constructor. I pass the url and get image.
If the two image url are same , i got exception "FileIOException: File already exists "
My code is here.,
FileConnection fConn = null;
try
{
String fileString = MD5.encodeStringMD5(url);
fConn = (FileConnection) Connector.open(fileTempPath+fileString+".png");
if(!fConn.exists())
{
fConn.create();
GetImageFromURL(url,fConn,id);
}
else
{
GetImageFromFolder(fConn, id);
}
fConn.close();
}
catch (Exception e)
{
System.out.println("------"+e);
}
If the urls are differ. No problem occur. But if two or three url r same , Only one image only stored and load on screen. others same url not displaying.
After stored on device memory, its loadding all image.
The Exception throws in this line - "fConn.create();"
A: Before creating a new file, try to open a file with the same name/path. If it already exists remove it.
A: If file already exits then do like this:
if(!fConn.exists())
{
fConn.create();
GetImageFromURL(url,fConn,id);
}
else
{
fConn.truncate();//it removes the data in that file;
GetImageFromFolder(url,fConn, id);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Workflow Fails to Compile and Publish in SharePoint Designer 2010 The SharePoint install is a SP2010 install on a 2008 R2 server. Everything is fully patched. I am running the SP Designer on the SharePoint Server directly.
I have a workflow which is intended to send an email when a new document is created in a custom list. I have deliberately kept the workflow very simple in order to illustrate this problem.
After creating this single step workflow in SP Designer, I click "Check for Errors" and SP Designer reports "The workflow contains no errors".
I then click "Publish" but the Workflow Error dialog is displayed with the message
Errors were found when compiling the workflow. The workflow files
were saved but cannot be run.
Clicking the advanced button reveals more information:
Could not publish the workflow because the workflow configuration file
contains errors
Any suggestions gratefully received
A: I'll share what fixed it for me - deactivating all workflow features at the site collection level (that is, Workflows, Three-state workflow, Publishing Approval Workflow) and then reactivating the features. I was then able to publish my workflow. This post helped, not sure whether this only works for 365 though, but it's sure worth trying first if you are considering a reinstall.
A: after googling for quite some time, i think it's an authentication issue. How is your SharePoint set up? Do you use HTTPS for authentication? If so check out this article.
A: I know this error message from sharepoint. I got this by dealing with multiple lookup fields refering to other lists. Even when I check the worfklow for errors SharePoint says that its all fine but i can't publish it at all.
Try to build a new Test-Site on your Site Collection. Build a Custom Document Library, leave it standard and then set up a new simple workflow just sending a mail.
Fill out the needed fields in mail only using simple values. Send to your mailadress, simple mail subject and simple mail body.
Set the workflow to run only manually.
Try to publish the workflow.
When this is working, then compair to your existing workflow and change your values by trail and error.
A: After doing a clean install of the OS and SharePoint, workflows are working flawlessly. I can only conclude that the problems were caused by left over registry settings from MOSS 2007. Thanks for the suggestions that people made.
A: This could also happens if you chage the URL of the web application, all you have do is click the Design button from the library itself.
when changinf the URL from http://server/Site to example: http://server.xx1.net/site, and you try to publish it tries the old url.
A: what helped in my situation is changing from start workflow automatically to manually.some times answers for critical situation is very easy. hope it helps, many thanks
A: I ran into this problem and after digging for days and folks suggesting to rebuild the servers, disabling and re-enabling site features, remove previous workflow versions, etc. and trying everything except rebuilding the servers (not practical for clients production environment). I decided to try some tests and found that this issue was only happening on one particular list no matter how simple or complex the workflow was... And when I would check the box for start automatically on item create (or when item changed) it would fail to publish and give the error above, but if I published it with just manually start worked fine. Finally after deleting views and some more testing, I discovered that there was over 240+ columns in this list (I did not create it...) and 50+ workflows set to run on create... Thankfully I have a test environment I built out for the client so I sync'd the Site Collection database back to test environment from Production re-ran my tests and got same error... So what resolved the problem and what was the ultimate cause of the problem, there was to many columns defined in the list and I had to delete several columns to publish the workflow in the test environment. This actually issue translates into the there is a limit in SQL Server on how much data the list can store each type of column takes up so much space read more about it here:
https://technet.microsoft.com/en-us/library/cc262787(v=office.15).aspx#Column
So what I did in production was worked with my client to determine how to break up the list into multiple lists and have relationships between them, thus moving some of the columns and data to another list (Think database/list normalization)... I hope this solution helps someone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Reading xls file in Cocoa For my application development, I am using MAC OS, Cocoa and objective-c.
In my application, I have following 2 requirements.
1)Reading of xls file saved in 'UTF-16 Unicode Text' format.
If I saves xls in above format, file type is becoming Text and extension is becoming .txt.
I have used [NSString stringWithContentsOfURL:importURL encoding:NSUTF16StringEncoding error:&readError].
Code is working fine without any issues.
2)Reading of xls file saved in 'Excel Workbook' format.
If I saves xls in above format, file extension is becoming .xls.
Can any one suggest how to read xls file saved in 'Excel Workbook' format.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to extract images from running .Net application? I would ask about just ".net application" but my app is obfuscated, encrypted and compressed, and I cannot get anything from just a binary file on the disk.
This is my own app, and because of disk crash, I had to retrieve it from SVN. It appeared that I didn't include images, so I am figuring out how to get it back from installed .exe file.
So -- is there a tool to extract images from running .Net application? I think this is my last chance.
A: You could use a tool like Cropper to take screenshots of the images within the app?
A: You can do Assembly.Load against a .NET EXE file; I'm wondering if you can then reflect into that image and extract the resources you need ?
My thinking is, is by that time, the OS/CLR will have done whatever processing is required to unpack your image.
A: Assuming that this is a .Net application, you can probably use Reflector to view all the embeded resources of the various assemblies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Expected response to be a <:redirect> but was <200> I've got an issue with my rspec tests and having looked through previous questions I haven't been able to resolve it. The test fails with the above error but the code works in practice, does anyone know how to resolve this?
Rspec:
describe "authentication of edit/update pages" do
before(:each) do
@user = Factory(:user)
end
describe "for non-signed in users" do
it "should deny access to 'edit'" do
get :edit, :id => @user
response.should redirect_to(signin_path)
end
it "should deny access to 'update'" do
put :update, :id => @user, :user => {}
response.should redirect_to(signin_path)
end
end
end
Sessions Helper:
def deny_access
redirect_to signin_path, :notice => "Please sign in to access this page."
end
Users Controller
class UsersController < ApplicationController
before_filter :authenticate, :only => [:edit, :update]
private
def authenticate
deny_access unless signed_in?
end
end
A: I guess you should change your code a bit:
def deny_access
redirect_to signin_path, :notice => "Please sign in to access this page." and return
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: BlazeDS / Tomcat Configuration I'm new to blazeDS/Tomcat..
I made a Flex application that communicates with a blazeDS server...
Everything works good, I have only one problem, the console app is accessible from everywhere (local network, internet), I'd like to secure it, with password or something else...
I have not edited any tomcat/blazeDS file, except remoting.xml to setting up my app destination...
There are no users...
Thank you..
A: I would remove the console application from a production environment (just delete ds-console.war from tomcat/webapps/). If you still want to keep it you can find a lot of articles on internet about how to secure an war application. Some examples: Basic authentication, Secure authentication.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pyro and file sequencing When I add new files through patch it messes up File Sequence table and at the same time the size of the patch becomes the same as the size of the product installation. I'm using PatchGroup element to overcome this behavior but as the number of new files added through the patch grows it becomes hard to keep track of the last used number in PatchGroup. I found this post bu Rob Mensching:
http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/how-to-control-File-Sequence-no-in-WIX-td5933489.html#a5934096
If I understand it correctly pyro should automatically add new files to the File Sequence end. Am I doing something wrong or pyro isn't working as expected?
A: In WiX v3.5 and v3.6 file sequencing should just be handled for you using pyro and the Patch element. WiX v3.0 things were a bit more touchy and PatchCreation element never did things for you automatically. PatchGroup shouldn't be needed using the newest tools.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Permission to Send data Is there a permission to send data to the server ?
Because my data sent to the server when I use java project but when the code written in android project the data can not be uploaded.
Thanks...
A: Do you have Internet permission in Manifest file? If not, add this
<uses-permission
android:name="android.permission.INTERNET" />
into manifest file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails - do AJAX update using HTML template Apologies if this is asked before, but I can't find it...
I've got a page with a button bar that I need to update as the state of the page changes. The button bar is rendered with a partial.
The user can update the state with various AJAX actions on the page, and I'm doing various updates to the required elements. Mostly these are simple text strings, but the button bar is a bit more complex.
I'd have thought I should be able to do some variation on:
$('.button_bar').html( '<%= render :partial => 'buttons.html.erb' %>' );
But I'd need to somehow escape the render output for use in a string. While searching I came across render_to_string, but that just gives undefined method in my application.
A: I am not sure if I understand right, but
$('.button_bar').html( "<%= escape_javascript(render "buttons") %>" );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "DisableCreatedUser" is not working properly I am using a ASP.NET CreateUserWizard to registering users.
I wanted user to not automatically log after registration until they login manually.
<asp:CreateUserWizard ID="RegisterUser" runat="server" EnableViewState="false" RequireEmail="false"
DisableCreatedUser="true" LoginCreatedUser="false" OnCreatedUser="RegisterUser_CreatedUser">
In here I have set the DisableCreatedUser="true" and LoginCreatedUser="false" in order to not logged the user after registration until they logged in as CreateUserWizard.DisableCreatedUser Property describes.
Any ideas about the reason this settings not working will be appreciate.
Thanks
A: I did that by adding FormsAuthentication.SignOut() in the OnCreatedUser. that works !!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Multiple UIPickerView with same data in one view. How can I get the content of both picker? I have 2 UIPickerviews with the same data.
At the moment sb is clicking the save-Button I want to get the data from both PickerViews.
I already set a tag to both pickers and I also implemented the function:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [symbolList objectAtIndex:row];
}
But I have no idea how to get on both datas at the same time.
A: For each picker view, use selectedRowInComponent: to find out the current selection. Use this to obtain the value from each picker view's data source, e.g:
NSString *pickerViewOneSelection = [symbolList objectAtIndex:[pickerViewOne selectedRowInComponent:0]];
NSString *pickerViewTwoSelection = [symbolList objectAtIndex:[pickerViewTwo selectedRowInComponent:0]];
I'm assuming that pickerViewOne and pickerViewTwo are pointers to your two picker views and you've already worked that part out. I have also assumed that your picker has only one component.
A: Set tag of pickerview.
first create IBOutlet of both picker view.
and set tag of picker view.
pickerview.tag == 10;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add Service archive generator and code generator plugin in Eclipse I have downloaded Service archive and code generator wizard plugin for Eclipse (From http://axis.apache.org/axis2/java/core/tools/index.html). I am following steps mentioned here http://axis.apache.org/axis2/java/core/tools/eclipse/plugin-installation.html.
I extracted the content of plugin folder into dropin folder but not able to see Service archive or code generator wizard.I tried copying all content into Plugin folder but no luck.
How can we add this two plugins ?
PS: I am using Eclipse Helios.
~Ajinkya.
A: I'm assuming you're using the latest version (1.6.1) of the plugins
There's an open apache issue for a problem loading the plugin
https://issues.apache.org/jira/browse/AXIS2-5145
Altho this is for Indigo it might be the same problem you're having (just check)
If that's the case I'd either wait for a fix or try an older version of the plugins (I'm using 1.5.4 which works just fine)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to log all the errors on exception in C# and then show?
I've written some code, in C# windows forms, binded to validation button.
The code is here: my validation button. The code is checking validation of an XML file with XSD schema. If exception occurs then it throws the exception text into textbox and program is stopping validation.
I'd like to log the errors/exceptions into something like an array and then print the errors into the textbox.
How to do it?
private void validateButton_Click(object sender, System.EventArgs e)
{
resultTextBox.Text = String.Empty;
if (ValidateForm())
{
try
{
Cursor.Current = Cursors.WaitCursor;
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(String.Empty, XmlReader.Create(new StreamReader(xmlSchemaFileTextBox.Text)));
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas = schemaSet;
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(new StringReader(inputXmlTextBox.Text), settings);
while (reader.Read()) { }
resultTextBox.Text = "The XML file is OK :)" +
Environment.NewLine +
DateTime.Now.ToLongDateString();
}
catch (XmlSchemaException schemaEx)
{
resultTextBox.Text = "The XML file is invalid:" +
Environment.NewLine +
schemaEx.LineNumber +
": " +
schemaEx.Message;
}
catch (Exception ex)
{
resultTextBox.Text = ex.ToString();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
else
{
MessageBox.Show(null, "You have to load XML and XSD files to validate.", "There's XML file reading error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
A: If you want to show the exception to your application's user, you can use ExceptionMessageBox.
try {
throw new ApplicationException("test");
}
catch (ApplicationException ex)
{
ExceptionMessageBox box = new ExceptionMessageBox(ex);
box.Show(this);
}
A: you should open the XmlReader with the XmlReaderSettings object and use the ValidationEventHandler to catch errors and report them to the user.
see full documentation and working example at: XmlReaderSettings.ValidationEventHandler Event
basically write something like this:
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class ValidXSD {
public static void Main() {
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);
// Parse the file.
while (reader.Read());
}
// Display any warnings or errors.
private static void ValidationCallBack (object sender, ValidationEventArgs args) {
if (args.Severity==XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Groovy: indexes of substrings? How do I find the indexes of all the occurances of a substring in a large string -
(so basically ,and extension of the "indexOf" function) . Any ideas?
Current situation:
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexOf(sub)
// = 9
I want something like:
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexesOf(sub)
// = [9,15]
Is there such a function? How should I implement it otherwise? (in a non trivial way)
A: You could write a new addition to the String metaClass like so:
String.metaClass.indexesOf = { match ->
def ret = []
def idx = -1
while( ( idx = delegate.indexOf( match, idx + 1 ) ) > -1 ) {
ret << idx
}
ret
}
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexesOf(sub)
There is nothing I know of that exists in groovy currently that gets you this for free though
A: This is a relatively easy approach:
String.metaClass.indexesOf = { arg ->
def result = []
int index = delegate.indexOf(arg)
while (index != -1) {
result.add(index);
index = delegate.indexOf(arg, index+1);
}
return result;
}
Note that this will find overlapping instances (i.e. "fooo".indexesOf("oo") will return [1, 2]). If you don't want this, replace index+1 with index+arg.length().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: save Contact in isolated storage in windows phone 7 c# Can I save Contacts in Isolated Storage in Windows phone 7 ? and How can I access it in c# ? and which is the best way to save it using linq to sql or Files or Values ?
A: No No No, you can NOT save even one Contact Object of type "Microsoft.Phone.UserData.Contact" in the isolated storage. The reason is simple: Contact object is un-serializable.
I have tried this by myself and did not work, for sure. Consequently, you can NOT save a list of contacts.
Details:
I tried the following scenario: created a contact object, saved it in the isolated storage, tired read it from the isolated storage while the application is running (still alive). The result: it worked and read all the data I previously filled.
BUT
When I closed the application, I tried to retrieve the contact data (contact object that I previously saved) there application crashes and the debugger told me "KeyNotFoundException" which means that no "contact" were stored at all with the same "key" I used to store the "contact" in the first time.
So, why the application can read the stored "contact" in the first time before closing and reopening that application? It was reading form the isolated storage object in the memory not from the one saved on the phone.
A: Yes, you can read contact information (see http://msdn.microsoft.com/en-us/library/hh286416(v=vs.92).aspx) and save it to Isolated Storage in the same way you could save anythign else there.
The "best" way to save it will depend on what you wnat to do with it and how you want to access it.
Remember that you'll have to keep your copy of the contact information in sync with the actual data though. Unless you have a REALLY good reason to keep this copy of the data I'd avoid doing this and just query the actual contact data store when you need it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create a windows panel that is invisible that still accepts click message I'm using c++/cli with visual studio 2010 express edition.
What I want to do is create a panel that is invisible but that still accepts/receives the click and double click messages and possibly other mouse input. If I set the controls visibility to FALSE then this seems to disable any mouse input.
I have tried getting the paint message and doing nothing (as was suggested by other sources) to try and make the panel simply not draw but not be invisible however the panel still seems to be drawing.
What should I be doing in the paint message to tell windows that I have draw the panel?
My panel drawing function is:
private: System::Void panel1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
}
If there are any other suggestions about how I could achieve this then that would be helpful.
A: In the end I scrapped this idea all together, the problem was to get a way of getting the mouse input from a window that had been "parentented" by a NativeWindow class. This meant that the window I was expecting to receive messages (the child window) was not receiving the messages.
In order to get the messages you need to override the event handler in your parent NativeWindow class. Here you can handle the event This is where I got the solution:
http://msdn.microsoft.com/en-us/library/system.windows.forms.nativewindow.createhandle.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I need advise choosing a NoSQL database for a project with a lot of minute related information I am currently working on a private project that is going to use Google's GTFS spec to get information about 100s of Public Transit agencies, their routers, stations, times, and other related information. I will be getting my information from here and the google code wiki page with similar info. There is a lot of data and its partitioned into multiple CSV formatted text files. These can be huge, some ranging in 80-100mb of data.
With the data I have, I want to translate it all into a nice solid database that I can build layers on top of to use for my project. I will be using GPS positioning to pinpoint a location and all surrounding stations/stops.
My goal is to access all the information for all these stops and stations with as few calls as possible, while keeping datasets small for queried results.
I am currently leaning towards MongoDB and CouchDB for their GeoSpatial support that can really optimize getting small datasets. But I also need to be sure to link all the stops on a route because I will be propagating information along a transit route for that line. In this case I have found that I can benefit from a Graph DB like Neo4j and OrientDB, but from what I know, neither has GeoSpatial support nor am I 100% sure that a Graph DB would be what I need.
The perfect solution might not exist, but I come here asking for help on finding the best possible for my situation. I know I will possible have to work around limitations of whatever I choose, but I want to at least have done my research and know that its the best I can get at the moment.
I have also been suggested to splinter the data into multiple DBs, but that could get very messy because all the information is very tightly interconnected through IDs.
Any help would be appreciated.
A: Obviously a graph database fits 100% your problem. My advice here is to go for some geo spatial module over neo4j or orientdb, althought you have some others free and open source implementation.
I think the best one right now, with all the geo spatial thing implemented is neo4j-spatial package. But as far as I know, you can also reproduce most of the geo spatial thing on your own if necessary.
BTW talking about splitting, if the amount of data/queries will be high, I strongly recommend you to share the load and think the model in this terms. Sure you can do something.
A: I've used Mongo's GeoSpatial features and can offer some guidance if you need help with a C# or javascript implementation - I would recommend it to start because it's super easy to use. I'm learning all about Neo4j right now and I am working on a hybrid approach that takes advantage of both Mongo and Neo4j. You might want to cross reference the documents in Mongo to the nodes in Neo4j using the Mongo object id.
For my hybrid implementation, I'm storing profiles and any other large static data in Mongo. In Neo4j, I'm storing relationships like friend and friend-of-friend. If I wanted to analyze movies two friends are most likely to want to watch together (or really any other relationship I hadn't thought of initially), by keeping that object id reference I can simply add some code instructing each node go out and grab a list of movies from the related profile.
Added 2011-02-12:
Just wanted to follow up on this "hybrid" idea as I created prototypes for and implemented a few more solutions recently where I ended up using more than one database. Martin Fowler refers to this as "Polyglot Persistence."
I'm finding that I am often using a combination of a relational database, document database and a graph database (in my case this is generally SQL Server, MongoDB and Neo4j). Since the question is related to data modeling as much as it is to geospatial, I thought I would touch on that here:
I've used Neo4j for site organization (similar to the idea of hypermedia in the REST model), modeling social data and building recommendations (often based on social data). As a result, I will generally model this part of the application before I begin programming.
I often end up using MongoDB for prototyping the rest of the application because it provides such a simple persistence mechanism. I like to start developing an application with the user interface, so this ends up working well.
When I start moving entities from Mongo to SQL Server, the context is usually important - for instance, if I have an application that allows users to build daily reports based on periodically collected data, it may make sense to run a procedure that builds those reports each night and stores daily report objects in Mongo that may be combined into larger aggregate reports as needed (obviously this doesn't consider a few special cases, but that is not relevant to the point)...on the other hand, if users need to pull on-demand reports limited to very specific time periods, it may make sense to keep everything in SQL server and build those reports as needed.
That said, and this deserves more intense thought, here are some considerations that may be helpful:
*
*I generally try to store entities in a relational database if I find that pulling an entity from the database [in other words(in the context of a relational database) - querying data from the database that provides the data required to generate an entity or list of entities that fulfills the requested parameters] does not require significant processing (multiple joins, for instance)
*Do you require ACID compliance(aside:if you have a graph problem, you can leverage Neo4j for this)? There are document databases with ACID compliance, but there's a reason Mongo is not: What does MongoDB not being ACID compliant really mean?
One use of Mongo I saw in the wild that I thought was worthy of mention - Hadoop was being used to compute massive hash tables that were then stored in Mongo. I believe a similar approach is used by TripAdvisor for user based customization in terms of targeting offers, advertising, etc..
A: NoSQL only exists because MySQL users assume that all databases have their performance problems when their database grows large and/or becomes complex.
I suggest that you use PostGIS. You can use the same database for the rest of your data needs as well.
http://postgis.refractions.net/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get user name in session bean when redirected to error page? Can anyone tell me how to get user name in session bean correctly? In our application we do it by calling this method:
@Resource
private EJBContext _context;
private String getUserName() {
return _context.getCallerPrincipal().getName();
}
And this works fine till everything's fine. But when we get some 500 or 404 error and redirect user to corresponding page (which is set in web.xml) this method returns "WLS KERNEL" as user name. How to get correct user name in this case?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: memory increase in meego when use PageStack When I use pagestack to move between pages, the memory of device increases.
Please see memory increase when use PageStack to see more clearly my problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Possible to change Window background colour of a Dialog without a theme? At the moment I extend a Dialog and use the constructor Dialog(Context context, int theme) to set the background colour via a theme. This dialog is an overlay, so it sits above everything showing on the screen. The theme is as follows:
<style
name="Theme.example"
parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:backgroundDimEnabled">false</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">false</item>
<item name="android:windowFullscreen">false</item>
<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowBackground">@color/background_color</item>
</style>
Note that this theme sets the background colour via the android:windowBackground attribute. I need the entire screen to change colour, including the notification bar. But I also want to be able to change the background dynamically in Java after the dialog is displayed. The best way I've come up with is using getWindow().setBackgroundDrawableResource(R.drawable.background), where the Drawable is just a single pixel of the colour I want.
Is there a better way to do this? My current method works fine, but it would be nice to be able to use colours that I haven't predefined in R.drawable.
A: Try it with the ColorDrawable class.
You can create a new instance of the ColorDrawable class and set it as the background. Whenever you need to change the color you can just call setColor(int color)
on that class.
ColorDrawable colorDrawable = new ColorDrawable();
// ColorDrawable colorDrawable =
// new ColorDrawable(0xFF00FF00); // With a custom default color.
colorDrawable.setColor(0xFFFF0000);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Inserting html into the current tab through chrome extention? I am trying to insert some extra code into the current tab page in chrome using an extension
i.e add a submit button on top of the page. Where does this go? and how would I initialize every page like this?
A: If you put this in your manifest.json,
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["example.js"],
"css": ["example.css"]
}]
then example.js and example.css will be injected into every page you visit. See http://code.google.com/chrome/extensions/content_scripts.html for more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Numpy: find first index of value fast How can I find the index of the first occurrence of a number in a Numpy array?
Speed is important to me. I am not interested in the following answers because they scan the whole array and don't stop when they find the first occurrence:
itemindex = numpy.where(array==item)[0][0]
nonzero(array == item)[0][0]
Note 1: none of the answers from that question seem relevant Is there a Numpy function to return the first index of something in an array?
Note 2: using a C-compiled method is preferred to a Python loop.
A: I think you have hit a problem where a different method and some a priori knowledge of the array would really help. The kind of thing where you have a X probability of finding your answer in the first Y percent of the data. The splitting up the problem with the hope of getting lucky then doing this in python with a nested list comprehension or something.
Writing a C function to do this brute force isn't too hard using ctypes either.
The C code I hacked together (index.c):
long index(long val, long *data, long length){
long ans, i;
for(i=0;i<length;i++){
if (data[i] == val)
return(i);
}
return(-999);
}
and the python:
# to compile (mac)
# gcc -shared index.c -o index.dylib
import ctypes
lib = ctypes.CDLL('index.dylib')
lib.index.restype = ctypes.c_long
lib.index.argtypes = (ctypes.c_long, ctypes.POINTER(ctypes.c_long), ctypes.c_long)
import numpy as np
np.random.seed(8675309)
a = np.random.random_integers(0, 100, 10000)
print lib.index(57, a.ctypes.data_as(ctypes.POINTER(ctypes.c_long)), len(a))
and I get 92.
Wrap up the python into a proper function and there you go.
The C version is a lot (~20x) faster for this seed (warning I am not good with timeit)
import timeit
t = timeit.Timer('np.where(a==57)[0][0]', 'import numpy as np; np.random.seed(1); a = np.random.random_integers(0, 1000000, 10000000)')
t.timeit(100)/100
# 0.09761879920959472
t2 = timeit.Timer('lib.index(57, a.ctypes.data_as(ctypes.POINTER(ctypes.c_long)), len(a))', 'import numpy as np; np.random.seed(1); a = np.random.random_integers(0, 1000000, 10000000); import ctypes; lib = ctypes.CDLL("index.dylib"); lib.index.restype = ctypes.c_long; lib.index.argtypes = (ctypes.c_long, ctypes.POINTER(ctypes.c_long), ctypes.c_long) ')
t2.timeit(100)/100
# 0.005288000106811523
A: @tal already presented a numba function to find the first index but that only works for 1D arrays. With np.ndenumerate you can also find the first index in an arbitarly dimensional array:
from numba import njit
import numpy as np
@njit
def index(array, item):
for idx, val in np.ndenumerate(array):
if val == item:
return idx
return None
Sample case:
>>> arr = np.arange(9).reshape(3,3)
>>> index(arr, 3)
(1, 0)
Timings show that it's similar in performance to tals solution:
arr = np.arange(100000)
%timeit index(arr, 5) # 1000000 loops, best of 3: 1.88 µs per loop
%timeit find_first(5, arr) # 1000000 loops, best of 3: 1.7 µs per loop
%timeit index(arr, 99999) # 10000 loops, best of 3: 118 µs per loop
%timeit find_first(99999, arr) # 10000 loops, best of 3: 96 µs per loop
A: There is a feature request for this scheduled for Numpy 2.0.0: https://github.com/numpy/numpy/issues/2269
A: This problem can be effectively solved in pure numpy by processing the array in chunks:
def find_first(x):
idx, step = 0, 32
while idx < x.size:
nz, = x[idx: idx + step].nonzero()
if len(nz): # found non-zero, return it
return nz[0] + idx
# move to the next chunk, increase step
idx += step
step = min(9600, step + step // 2)
return -1
The array is processed in chunk of size step. The step longer the step is, the faster is processing of zeroed-array (worst case). The smaller it is, the faster processing of array with non-zero at the start. The trick is to start with a small step and increase it exponentially. Moreover, there is no need to increment it above some threshold due to limited benefits.
I've compared the solution with pure ndarary.nonzero and numba solution against 10 million array of floats.
import numpy as np
from numba import jit
from timeit import timeit
def find_first(x):
idx, step = 0, 32
while idx < x.size:
nz, = x[idx: idx + step].nonzero()
if len(nz):
return nz[0] + idx
idx += step
step = min(9600, step + step // 2)
return -1
@jit(nopython=True)
def find_first_numba(vec):
"""return the index of the first occurence of item in vec"""
for i in range(len(vec)):
if vec[i]:
return i
return -1
SIZE = 10_000_000
# First only
x = np.empty(SIZE)
find_first_numba(x[:10])
print('---- FIRST ----')
x[:] = 0
x[0] = 1
print('ndarray.nonzero', timeit(lambda: x.nonzero()[0][0], number=100)*10, 'ms')
print('find_first', timeit(lambda: find_first(x), number=1000), 'ms')
print('find_first_numba', timeit(lambda: find_first_numba(x), number=1000), 'ms')
print('---- LAST ----')
x[:] = 0
x[-1] = 1
print('ndarray.nonzero', timeit(lambda: x.nonzero()[0][0], number=100)*10, 'ms')
print('find_first', timeit(lambda: find_first(x), number=100)*10, 'ms')
print('find_first_numba', timeit(lambda: find_first_numba(x), number=100)*10, 'ms')
print('---- NONE ----')
x[:] = 0
print('ndarray.nonzero', timeit(lambda: x.nonzero()[0], number=100)*10, 'ms')
print('find_first', timeit(lambda: find_first(x), number=100)*10, 'ms')
print('find_first_numba', timeit(lambda: find_first_numba(x), number=100)*10, 'ms')
print('---- ALL ----')
x[:] = 1
print('ndarray.nonzero', timeit(lambda: x.nonzero()[0][0], number=100)*10, 'ms')
print('find_first', timeit(lambda: find_first(x), number=100)*10, 'ms')
print('find_first_numba', timeit(lambda: find_first_numba(x), number=100)*10, 'ms')
And results on my machine:
---- FIRST ----
ndarray.nonzero 54.733994480002366 ms
find_first 0.0013148509997336078 ms
find_first_numba 0.0002839310000126716 ms
---- LAST ----
ndarray.nonzero 54.56336712999928 ms
find_first 25.38929685000312 ms
find_first_numba 8.022820680002951 ms
---- NONE ----
ndarray.nonzero 24.13432420999925 ms
find_first 25.345200140000088 ms
find_first_numba 8.154927100003988 ms
---- ALL ----
ndarray.nonzero 55.753537260002304 ms
find_first 0.0014760300018679118 ms
find_first_numba 0.0004358099977253005 ms
Pure ndarray.nonzero is definite looser. The numba solution is circa 5 times faster for the best case. It is circa 3 times faster in the worst case.
A: Although it is way too late for you, but for future reference:
Using numba (1) is the easiest way until numpy implements it. If you use anaconda python distribution it should already be installed.
The code will be compiled so it will be fast.
@jit(nopython=True)
def find_first(item, vec):
"""return the index of the first occurence of item in vec"""
for i in xrange(len(vec)):
if item == vec[i]:
return i
return -1
and then:
>>> a = array([1,7,8,32])
>>> find_first(8,a)
2
A: If your list is sorted, you can achieve very quick search of index with the 'bisect' package.
It's O(log(n)) instead of O(n).
bisect.bisect(a, x)
finds x in the array a, definitely quicker in the sorted case than any C-routine going through all the first elements (for long enough lists).
It's good to know sometimes.
A: I've made a benchmark for several methods:
*
*argwhere
*nonzero as in the question
*.tostring() as in @Rob Reilink's answer
*python loop
*Fortran loop
The Python and Fortran code are available. I skipped the unpromising ones like converting to a list.
The results on log scale. X-axis is the position of the needle (it takes longer to find if it's further down the array); last value is a needle that's not in the array. Y-axis is the time to find it.
The array had 1 million elements and tests were run 100 times. Results still fluctuate a bit, but the qualitative trend is clear: Python and f2py quit at the first element so they scale differently. Python gets too slow if the needle is not in the first 1%, whereas f2py is fast (but you need to compile it).
To summarize, f2py is the fastest solution, especially if the needle appears fairly early.
It's not built in which is annoying, but it's really just 2 minutes of work. Add this to a file called search.f90:
subroutine find_first(needle, haystack, haystack_length, index)
implicit none
integer, intent(in) :: needle
integer, intent(in) :: haystack_length
integer, intent(in), dimension(haystack_length) :: haystack
!f2py intent(inplace) haystack
integer, intent(out) :: index
integer :: k
index = -1
do k = 1, haystack_length
if (haystack(k)==needle) then
index = k - 1
exit
endif
enddo
end
If you're looking for something other than integer, just change the type. Then compile using:
f2py -c -m search search.f90
after which you can do (from Python):
import search
print(search.find_first.__doc__)
a = search.find_first(your_int_needle, your_int_array)
A: As far as I know only np.any and np.all on boolean arrays are short-circuited.
In your case, numpy has to go through the entire array twice, once to create the boolean condition and a second time to find the indices.
My recommendation in this case would be to use cython. I think it should be easy to adjust an example for this case, especially if you don't need much flexibility for different dtypes and shapes.
A: I needed this for my job so I taught myself Python and Numpy's C interface and wrote my own. http://pastebin.com/GtcXuLyd It's only for 1-D arrays, but works for most data types (int, float, or strings) and testing has shown it is again about 20 times faster than the expected approach in pure Python-numpy.
A: If you are looking for the first non-zero element you can use a following hack:
idx = x.view(bool).argmax() // x.itemsize
idx = idx if x[idx] else -1
It is a very fast "numpy-pure" solution but it fails for some cases discussed below.
The solution takes advantage from the fact that pretty much all representation of zero for numeric types consists of 0 bytes. It applies to numpy's bool as well. In recent versions of numpy, argmax() function uses short-circuit logic when processing the bool type. The size of bool is 1 byte.
So one needs to:
*
*create a view of the array as bool. No copy is created
*use argmax() to find the first non-zero byte using short-circuit logic
*recalculate the offset of this byte to the index of the first non-zero element by integer division (operator //) of the offset by a size of a single element expressed in bytes (x.itemsize)
*check if x[idx] is actually non-zero to identify the case when no non-zero is present
I've made some benchmark against numba solution and build it np.nonzero.
import numpy as np
from numba import jit
from timeit import timeit
def find_first(x):
idx = x.view(bool).argmax() // x.itemsize
return idx if x[idx] else -1
@jit(nopython=True)
def find_first_numba(vec):
"""return the index of the first occurence of item in vec"""
for i in range(len(vec)):
if vec[i]:
return i
return -1
SIZE = 10_000_000
# First only
x = np.empty(SIZE)
find_first_numba(x[:10])
print('---- FIRST ----')
x[:] = 0
x[0] = 1
print('ndarray.nonzero', timeit(lambda: x.nonzero()[0][0], number=100)*10, 'ms')
print('find_first', timeit(lambda: find_first(x), number=1000), 'ms')
print('find_first_numba', timeit(lambda: find_first_numba(x), number=1000), 'ms')
print('---- LAST ----')
x[:] = 0
x[-1] = 1
print('ndarray.nonzero', timeit(lambda: x.nonzero()[0][0], number=100)*10, 'ms')
print('find_first', timeit(lambda: find_first(x), number=100)*10, 'ms')
print('find_first_numba', timeit(lambda: find_first_numba(x), number=100)*10, 'ms')
print('---- NONE ----')
x[:] = 0
print('ndarray.nonzero', timeit(lambda: x.nonzero()[0], number=100)*10, 'ms')
print('find_first', timeit(lambda: find_first(x), number=100)*10, 'ms')
print('find_first_numba', timeit(lambda: find_first_numba(x), number=100)*10, 'ms')
print('---- ALL ----')
x[:] = 1
print('ndarray.nonzero', timeit(lambda: x.nonzero()[0][0], number=100)*10, 'ms')
print('find_first', timeit(lambda: find_first(x), number=100)*10, 'ms')
print('find_first_numba', timeit(lambda: find_first_numba(x), number=100)*10, 'ms')
The result on my machine are:
---- FIRST ----
ndarray.nonzero 57.63976670001284 ms
find_first 0.0010841979965334758 ms
find_first_numba 0.0002308919938514009 ms
---- LAST ----
ndarray.nonzero 58.96685277999495 ms
find_first 5.923203580023255 ms
find_first_numba 8.762269750004634 ms
---- NONE ----
ndarray.nonzero 25.13398071998381 ms
find_first 5.924289370013867 ms
find_first_numba 8.810063839919167 ms
---- ALL ----
ndarray.nonzero 55.181210660084616 ms
find_first 0.001246920000994578 ms
find_first_numba 0.00028766007744707167 ms
The solution is 33% faster than numba and it is "numpy-pure".
The disadvantages:
*
*does not work for numpy acceptable types like object
*fails for negative zero that occasionally appears in float or double computations
A: In case of sorted arrays np.searchsorted works.
A: You can convert a boolean array to a Python string using array.tostring() and then using the find() method:
(array==item).tostring().find('\x01')
This does involve copying the data, though, since Python strings need to be immutable. An advantage is that you can also search for e.g. a rising edge by finding \x00\x01
A: As a longtime matlab user I a have been searching for an efficient solution to this problem for quite a while. Finally, motivated by discussions a propositions in this thread I have tried to come up with a solution that is implementing an API similar to what was suggested here, supporting for the moment only 1D arrays.
You would use it like this
import numpy as np
import utils_find_1st as utf1st
array = np.arange(100000)
item = 1000
ind = utf1st.find_1st(array, item, utf1st.cmp_larger_eq)
The condition operators supported are: cmp_equal, cmp_not_equal, cmp_larger, cmp_smaller, cmp_larger_eq, cmp_smaller_eq. For efficiency the extension is written in c.
You find the source, benchmarks and other details here:
https://pypi.python.org/pypi?name=py_find_1st&:action=display
for the use in our team (anaconda on linux and macos) I have made an anaconda installer that simplifies installation, you may use it as described here
https://anaconda.org/roebel/py_find_1st
A: Just a note that if you are doing a sequence of searches, the performance gain from doing something clever like converting to string, might be lost in the outer loop if the search dimension isn't big enough. See how the performance of iterating find1 that uses the string conversion trick proposed above and find2 that uses argmax along the inner axis (plus an adjustment to ensure a non-match returns as -1)
import numpy,time
def find1(arr,value):
return (arr==value).tostring().find('\x01')
def find2(arr,value): #find value over inner most axis, and return array of indices to the match
b = arr==value
return b.argmax(axis=-1) - ~(b.any())
for size in [(1,100000000),(10000,10000),(1000000,100),(10000000,10)]:
print(size)
values = numpy.random.choice([0,0,0,0,0,0,0,1],size=size)
v = values>0
t=time.time()
numpy.apply_along_axis(find1,-1,v,1)
print('find1',time.time()-t)
t=time.time()
find2(v,1)
print('find2',time.time()-t)
outputs
(1, 100000000)
('find1', 0.25300002098083496)
('find2', 0.2780001163482666)
(10000, 10000)
('find1', 0.46200013160705566)
('find2', 0.27300000190734863)
(1000000, 100)
('find1', 20.98099994659424)
('find2', 0.3040001392364502)
(10000000, 10)
('find1', 206.7590000629425)
('find2', 0.4830000400543213)
That said, a find written in C would be at least a little faster than either of these approaches
A: how about this
import numpy as np
np.amin(np.where(array==item))
A: You can covert your array into a list and use it's index() method:
i = list(array).index(item)
As far as I'm aware, this is a C compiled method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "127"
} |
Q: CSS - Nested table border showing. How do I stop this? I am using ie 8.
I have the following CSS where I want to show the border for the outer table, but not the table nested inside one of the cells;
table#ScheduledLeaveCalendar
{
table-layout:fixed;
}
/* Calendar that shows annual leave */
#ScheduledLeaveCalendar
{
border-collapse:collapse;
}
#ScheduledLeaveCalendar td, #ScheduledLeaveCalendar th
{
font-size:0.8em;
border:1px solid #2906A6; /* dark blue */
}
#ScheduledLeaveCalendar th
{
width:30px;
font-size:0.9em;
text-align:center;
padding:5px 3px 4px 3px;
padding-top:5px;
padding-bottom:4px;
background-color:#6640EE; /* blue */
color:#ffffff;
}
#ScheduledLeaveCalendar td
{
padding: 0px;
margin: 0px;
}
#ScheduledLeaveCalendar table
{
border-collapse: collapse;
border: 0px;
margin: 0px;
padding: 0px;
}
This CSS gives me
The Markup is;
<table id="ScheduledLeaveCalendar">
<tr>
<th colspan="2"></th>
<th colspan="6">Oct 2011</th>
<th colspan="1"></th>
</tr>
<tr>
<th>F</th><th></th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th></th><th>M</th>
</tr>
<tr>
<th>14</th><th></th><th>17</th><th>18</th><th>19</th><th>20</th><th>21</th><th></th><th>24</th>
</tr>
<tr>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td><table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%"><tr><td />
<td class="StandardCellHeight AnnualLeaveColour" />
</tr></table></td>
<td><table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%"><tr><td class="StandardCellHeight AnnualLeaveColour" />
<td />
</tr></table></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
</tr>
</table>
See http://jsfiddle.net/Dqm68/1/
A: You can use
#ScheduledLeaveCalendar td td {
border: 0;
}
which means the td elements that are nested in other td elements should have no border..
Demo at http://jsfiddle.net/Dqm68/5/
A: Simply add another line to remove the border from the nested table td.
#ScheduledLeaveCalendar table td {border:none}
http://jsfiddle.net/blowsie/Dqm68/3/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Find string in URL - joomla/jQuery I've got a "simple" problem that I can't get my head around, I want to search my URL, and find either /nl/ or /en/ or /fr/ and add a class to the body accordingly.
I've searched high and low and can't seem to find the right answer.
The URL is build "cleanly', so it reads: www.mysite.com/nl/mypage.
A: You could try something like -
if (location.href.indexOf('/en/') > -1) {
$("body").addClass("enClass");
}
A: Try this:
$url = 'www.mysite.com/nl/mypage...';
$url_parts = explode('/', $url);
foreach($url_parts as $part):
if($part = 'nl'){ var_dump($part); }
endforeach;
A: Use regular expressions. Capture the URL as a variable:
var url = window.location;
Then search for the languages:
var pattern = /\/en\/|\/nl\/|\/fr\//
if (url.match(pattern)) {
// there's a match
} else {
// there isn't
}
If you want to do an if statement for just one language, change the pattern to only include that one language. For example, en:
var pattern = /\/en\//;
if (url.match(pattern)) {
// on en
} else {
// not on en
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Seam and Spring does anyone know any good site which talks about Spring 3 and Seam 2 integration. I am really struggling to find something on this on the net. we are thinking about moving to spring 3 from EJB 3. i will really appreciate any good site suggestion. also a humble request to you is to keep the discussion on the topic.
thanks in advance
A: The Seam manual is a good place to start: http://docs.jboss.org/seam/2.2.2.Final/reference/en-US/html/spring.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need information on ethernet bootloader for AT32UC3A0512 I am planning to develop ethernet bootloader. So I wanted to modify the existing DFU Bootloader program. I want to delete the already existing bootloader on micro-controller flash and put my own bootloader.
Currently my MCU is AT32UC3A0512. I am using AVR Dragon and AVR One debugger/programmer. Is it possible to reprogram the bootloader region with AVR Dragon or AVR One? or I must need to have MKII debugger?
A: It is absolutely possible to reprogram the boot loader with AVR One and I would guess that
the AVR Dragon works too (if you can use it to program the AVR32s generally).
The boot loader (if present) resides in the beginning of internal flash and is written as any other bit of code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Email log4j errors to different groups Am using log4j for my error reporting. Ive set my log 4j to also append errors to emails. However i need it to send emails to separate groups depending on the level of the message. For example
info messages go to management- [email protected], [email protected], [email protected]
debug messages go to programmers - [email protected], [email protected]
warn messages go to administrator - [email protected]
In such a fashion, is it possible? And has anyone implemented said procedure (a sample properties file would be appreciated)
A: Is should be easy to configure something like this using the SMTPAppender from log4j. But be aware, that emailing logs takes quite a bit of load, especially if you consider mailing DEBUG reports to developers.
A: You can use a log4j Filter to do this (http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/Filter.html)
The example below writes messages to different files according to the log level.
This can be easily adapted to an SMTPAppender instead of a FileAppender.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="management" class="org.apache.log4j.FileAppender">
<param name="File" value="management.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%m"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="INFO" />
<param name="LevelMax" value="INFO" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<appender name="programmers" class="org.apache.log4j.FileAppender">
<param name="File" value="programmers.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%m"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="DEBUG" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<appender name="admin" class="org.apache.log4j.FileAppender">
<param name="File" value="admin.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%m"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="WARN" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<category name="a">
<level value="ALL" />
<appender-ref ref="management"/>
<appender-ref ref="programmers"/>
<appender-ref ref="admin"/>
</category>
</log4j:configuration>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: codeigniter arabic keyboard form validation In my code I provided the form validation like 'alpha'. But when we will use the arabic keyboard, I am getting an error message 'District only contain alphabetic characters'.
How to solve this issue?
A: I think you may rather modifying in the core libraries of Codeigniter,Or you may use your own custom validations by Regex in Arabic characters
And if you can please provide a code sample it may helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need python Regex for handling sub-string I want to check where the string (Product Name) contains the word beta, Since I am not so good in regex writing :
eg.
"Crome beta"
"Crome_beta"
"Crome beta2"
"Crome_betaversion"
"Crome 3beta"
"CromeBerta2.3"
"Beta Crome 4"
So that I can raise error that this is not valid product name , its a product version.
i wrote a regex which is able to cought the above strings
parse_beta = re.compile( "(beta)", re.I)
if re.search(parse_data, product_name):
logging error 'Invalid product name'
But if the product name contains the word having substring beta init like "tibetans product" so the above regex it is parsing beta and raising error. i want to handle this case.Any one can suggest me some regex.
Thanks a lot.
A: Try ((?<![a-z])beta|cromebeta). (the word beta not preceded by a letter or the full word cromebeta)
I'll add a quote from http://docs.python.org/library/re.html to explain the first part.
(?<!...) Matches if the current position in the string is not preceded
by a match for .... This is called a negative lookbehind assertion.
Similar to positive lookbehind assertions, the contained pattern must
only match strings of some fixed length. Patterns which start with
negative lookbehind assertions may match at the beginning of the
string being searched.
A: Seems like you've actually got two concepts in the Product Name string: Product and version, with a separator of whitespace and underscore, from the examples you gave. Use a regex such that splits the two concepts, and search for the word beta only in the version concept.
A: "[Bb]eta(\d+|$|version)|^[Bb]eta "
test with grep:
kent$ cat a
Crome beta
Crome_beta
Crome beta2
Crome_betaversion
Crome 3beta
CromeBeta2.3
tibetans product
Beta Crome 4
kent$ grep -P "[Bb]eta(\d+|$|version)|^[Bb]eta " a
Crome beta
Crome_beta
Crome beta2
Crome_betaversion
Crome 3beta
CromeBeta2.3
Beta Crome 4
A: We should cover all the cases of beta version names, where the regexp should give a match.
So we start writing the pattern with the first example of beta "Crome beta":
' [Bb]eta'
We use [Bb] to match B or b in the second place.
The second example "Crome_beta" adds _ as a separator:
'[ _][Bb]eta'
The third "Crome beta2" and the forth "Crome_betaversion" examples are covered by the last regexp.
The fifth example "Crome 3beta" forces us to change the pattern this way:
'[ _]\d*[Bb]eta'
where \d is a substitute for [0-9] and * allows from 0 to infinity elements of \d.
The sixth example "CromeBeta2.3" shows that Beta can have no preceding _ or space, just start with the capital. So we cover it with | construction which is the same as or operator in Python:
'[ _]\d*[Bb]eta|Beta'
The seventh example Beta Crome 4 is matched by the least regexp (since it starts with Beta). But it can also be beta Chrome 4, so we would change the pattern this way:
'[ _]\d*[Bb]eta|Beta|^beta '
We don't use ^[Bb]eta since Beta is already covered.
Also, I should mention, we can't use re.I since we have to differentiate between beta and Beta in the regex.
So, the test code is (for Python 2.7):
from __future__ import print_function
import re, sys
match_tests = [
"Crome beta",
"Chrome Beta",
"Crome_beta",
"Crome beta2",
"Crome_betaversion",
"Crome 3beta" ,
"Crome 3Beta",
"CromeBeta2.3",
"Beta Crome 4",
"beta Chrome ",
"Cromebeta2.3" #no match,
"betamax" #no match,
"Betamax"]
compiled = re.compile(r'[ _]\d*[Bb]eta|Beta|^beta ')
for test in match_tests:
search_result = compiled.search(test)
if search_result is not None:
print("{}: OK".format(test))
else:
print("{}: No match".format(test), file=sys.stderr)
I don't see any need to use negative lookbehind.
Also, you used a capturing group (beta) (parenthesis). There is no need for it either. It would just slow down the regexp.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to gather info similar to panopticlick.eff.org I saw that the website http://panopticlick.eff.org/ gather info about your browser, which makes you unique, even without cookies or IP tracking.
My question: How do you use javascript to see this info?
A: There's a download in this article on corephp.com that includes javascript to fingerprint browsers and convert the results to an MD5 hash sum - probably not as heavyweight as panopticlick but it is pretty good.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to change url's in Joomla I have created a website and my client want that the URLs shows in tab according like Login URL is www.domain.com/index.php?option=com_user&view=login and he want that there will be set in url www.domain.com/login instead of this. So please tell me how can I do this I am new in Joomla
A: Check This:
http://www.teachmejoomla.net/joomla-mambo-tutorials-and-howtos/general-questions/how-to-enable-seo-on-joomla.html
On SEO URL's , apache mod_re-write from you Global Configuration option.
A: Make sure you check yes to apache mod_rewrite, enable SEO, in global configuration, but also a very important part... in your root folder for Joomla you need to rename htaccess.txt to .htaccess - that's VERY important!
That should help you get what you want. I recommend doing some reading up on the documentation - it's all covered in there!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there a online Javadoc for the Phonegap Android API? I'm searching for the Javadoc of the Phonegap Android API, for the classes like DroidGap and the others in the phonegapp jar.
I didn't find it on the Phonegap site or wiki.
Is there an online version of this documentation ? Is this part of the support ?
Thank you,
A: Try building them yourself.
I downloaded the source from GitHub, extracted it, and then at the command line did:
javadoc -d docs -sourcepath framework/src/ com.phonegap
I did this from within the folder where the files were extracted.
docs/ is the name of the new folder it created, in there is an index.html I was able to launch int he browser.
A: Follow the bellow link.
http://docs.phonegap.com/en/1.1.0/index.html
This link consist of the API references for the PhoneGap.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: how to save the xml tag result when we click on the save button? hi all i have xml code like below
<root>
<key>
<Question>Is the color of the car</Question>
<Ans>black?</Ans>
</key>
<key>
<Question>Is the color of the car</Question>
<Ans>black?</Ans>
</key>
<key>
<Question>Is the news paper </Question>
<Ans>wallstreet?</Ans>
</key>
<key>
<Question>fragrance odor</Question>
<Ans>Lavendor?</Ans>
</key>
<key>
<Question>Is the baggage collector available</Question>
<Ans></Ans>
</key>
</root>
Display on the screen as:
List form
Is the color of the car black? Check box
Is the baggage collector available? Check box
if the check box is checked - Yes otherwise vlaue is no.
on save button: we need to save it into a xml file
here i am getting question with answer when i am checked but my problem is how to save checked list items into the xml file after click on the save button so give me the solution any one of you.
A: You may refer to the [Creating XML] section in [Working with XML on Android] at http://www.ibm.com/developerworks/opensource/library/x-android/index.html. Once you have the XML generated, you can save it to a file with the help of File and Stream classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Releasing OpenCV IplImage crashes the application? I have an problem freeing up memory allocated for an IplImage.I have given a similar situation as in my application below.(it reflects the same bug occurs in my application.)
But instead of the line
char* originalData=loadedImage->imageData;
I get my "originalData" from a QT QImage class.
Code crashes at the line where I free "image_gray".
cvReleaseImage(&img_gray); // <-- crashes
Error message -
OpenCV Error: Assertion failed (udata < (uchar*)ptr && ((uchar*)ptr -
udata) <= (ptrdiff_t)(sizeof(void*)+16)) in fastFree, file
C:\opt\OpenCV-2.2.0\modules\co e\src\alloc.cpp, line 76 terminate
called after throwing an instance of 'cv::Exception' what():
C:\opt\OpenCV-2.2.0\modules\core\src\alloc.cpp:76: error: (-215) uda a
< (uchar*)ptr && ((uchar*)ptr - udata) <=
(ptrdiff_t)(sizeof(void*)+16) in fu ction fastFree
But if I use cvReleaseImageHeader() instead, if works fine but leaving a memory leak.
Any suggestions please?
void test2( char *imageFileName)
{
IplImage *loadedImage=cvLoadImage(imageFileName);
int xsize=loadedImage->width;
int ysize=loadedImage->height;
int totalBytes=xsize*ysize;
//In my application this "originalData" data comes from a QT QImage.
char* originalData=loadedImage->imageData;
unsigned char* datacopy = new unsigned char [totalBytes];
memcpy(datacopy, originalData, totalBytes);
IplImage* img_gray = cvCreateImage( cvSize(xsize, ysize), IPL_DEPTH_8U, 1 );
IplImage* img_gray_copy = cvCreateImage( cvSize(xsize, ysize), IPL_DEPTH_8U, 1 );
IplImage* img_edge = cvCreateImage( cvSize(xsize, ysize), IPL_DEPTH_8U, 1 );
IplImage* img_mask = cvCreateImage(cvSize(xsize, ysize), IPL_DEPTH_8U, 1);
cvSet(img_mask, cvScalar(255));
cvSet(img_gray_copy, cvScalar(255));
cvSetZero(img_mask);
cvSetData(img_gray, datacopy, xsize);
cvCopy(img_gray, img_gray_copy, img_mask);
//cvThreshold(img_gray_copy, img_edge, threshold, 255, CV_THRESH_BINARY_INV);
//cvFindContours(img_edge, storage, contours, sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
cvReleaseImage(&img_gray); /// <--- this crashes the application
//cvReleaseImageHeader(&img_gray); //<--- this works.but leaving a memory leak ???
cvReleaseImage(&img_gray_copy);
cvReleaseImage(&img_edge);
cvReleaseImage(&img_mask);
}
A: Ok found the issue.
I should have used cvCreateImageHeader() for img_gray .And then manually delete allocated memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Permalink, .htaccess pretty urls I'm really sorry if i'm annoying you guys but this is my final question in regards to .htaccess tricks
I need wordpress style, 'pretty permalinks'
But It's too confusing for me.
I need, this url http://test.com/?page=test&ID=1 to be http://test.com/test/NAMEFROMDATABASE
How? I know how to get ID=1 by using $_GET['ID'], but how do I put a value from the database in the url, and read it?
A: you can not get ID value by $_GET['ID'] directly from this URL : http://test.com/test/NAMEFROMDATABASE.
You can get ID by following below logic.
*
*create link by category name. i.e. if you have category laptop then create link like http://test.com/category/CATNAME
*Write rewrite code in htaccess.RewriteRule ^category/(.*)$ categories\.php?CNAME=$2&%{QUERY_STRING} [L]
*in PHP code get category ID from category name.$catName=$_GET['CNAME']
OR
*
*create link by category name and category ID. i.e. if you have category laptop then create link like http://test.com/category/CATNAME-ID-CATID
*Write rewrite code in htaccess. RewriteRule ^category/(.*)-ID-([0-9]+)$ categories\.php?ID=$2&%{QUERY_STRING} [L]
*in PHP code get category ID directly. $catID= $_GET['ID']
A:
How? I know how to get ID=1 by using $_GET['ID'], but how do I put a value from the database in the url, and read it?
You get the value from the database like so:
$id = mysql_real_escape_string($_GET['id']);
$sql = "SELECT folder, urlname FROM urls WHERE id = '$id' ";
// don't forget to single quote '$id' ^ ^ or you'll get errors
// and even worse mysql_real_escape_string() will not protect you.
if ($result = mysql_query($sql)) {
$row = mysql_fetch_row($result);
$pagename = $row['urlname'];
$folder = $row['folder'];
}
If you know id is an integer you can also use $id = intval($_GET['id']);
I recommend always using mysql_real_escape_string() because it works for all values and intval only works for integers.
In SQL it is never a problem to quote numbers, so make a habit of always quoting everything.
That way you cannot make mistakes.
You can never do
$sql = "SELECT urlname FROM urls WHERE id = '{$_GET['id']}' ";
Because that's an SQL-injection security hole.
See:
How does the SQL injection from the "Bobby Tables" XKCD comic work?
http://php.net/manual/en/function.mysql-query.php
http://php.net/manual/en/function.mysql-fetch-row.php
http://php.net/manual/en/function.mysql-connect.php
http://php.net/manual/en/function.mysql-close.php
A: You can't do that in htaccess, you will need to adjust your script so instead of receiving id=1 will receive name=xxx. Than it will look for the name in database and compute the ID
Okay, so in .htaccess you'll have something like this
RewriteRule ^something/(.+)\.htm$ something/file.php?djname=$1
In your php script you'll have
$name = mysql_real_escape_string($_GET['djname']);
$sql = "SELECT * FROM djtable where name='" . $name . "' LIMIT 1";
OBS: 1. Use proper escaping of the sql.
2. Make sure the dj names are distinct in the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: why can a CacheDependency be invalid right after creating it! (ASP.NET-MVC3) Whenever I make a CacheDependency in a testbed, it works fine.
If I write
var dep = new CacheDependency(null, new string[] { "dep" });
dep will be a new CacheDependency, with the properties: HasChanged = false, UtcLastModified = the current datetime.
But somehow in one of my projects the same line of code instantiates a cachedependency with HasChanged = true, UtcLastModified = 1/1/0001 12:00:00 AM
This dependency is invalid/useless by default. What can cause this? Is it possible that it is because I don't instantiate the dependency directly in the controller, but in an extension method of one of my objects?
But HttpRuntime.Cache works fine there without dependencies.
If you have any idea what can cause this please share.
A: I have found out that if the cache item that you depend on is null, then the cache dependency is automatically invalid.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add button to Window Border I have a WPF window with property WindowStyle="SingleBorderWindow".
Now I want to know how to set a button on left upper corner of the window border.
A: You probably need to use window chrome library which is described here.
A: I assume this is so you can re-create the Minimize/Maximize/Close buttons.
You have two options, use a Grid or a DockPanel. I have included a sample for a Grid below.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Margin="2,0" HorizontalAlignment="Right" VerticalAlignment="Top">
</StackPanel>
</Grid>
A Grid with a RowDefinition Height="Auto" that has a StackPanel Orientation="Horizontal" that is right-aligned.
However
If you want to make a true border-less window, you will have more work to do than simply setting the WindowStyle to None.
One main stumbling block I encountered was that when WindowStyle is None, it will not respect the task bar (i.e. overlap it) and you will need to hook into the message pump to set the correct window constraints.
Let me know in the comments if you want to know how to do this, will happy post sample code.
A: You need to make custom window by setting transparency, background and style like below :
<Window x:Class="WpfApplication2.Window2"
Name="Window2xx"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Title="window1"
xmlns:m="clr-namespace:WpfApplication2"
AllowsTransparency="True" WindowStyle="None"
WindowStartupLocation="CenterOwner" d:DesignWidth="410" StateChanged="Window_StateChanged"
SizeToContent="WidthAndHeight" ShowInTaskbar="False" Background="Transparent">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Style.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<m:MasterWindow Width="400">
<m:MasterWindow.WindowTitle>
<ContentPresenter Content="window1" MouseLeftButtonDown="Window_MouseLeftButtonDown"></ContentPresenter>
</m:MasterWindow.WindowTitle>
<m:MasterWindow.Content>
<Grid>
</Grid>
</m:MasterWindow.Content>
</m:MasterWindow>
</Grid>
</Window>
Code behind window2 :
namespace WpfApplication2
{
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
}
private void Window_StateChanged(object sender, EventArgs e)
{
if (((Window)sender).WindowState == WindowState.Maximized)
((Window)sender).WindowState = WindowState.Normal;
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
try
{
DragMove();
}
catch ()
{}
}
}
}
Master window is like below :
namespace WpfApplication2
{
public class MasterWindow : ContentControl
{
public static RoutedCommand CloseWindowCommand;
static MasterWindow()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MasterWindow), new FrameworkPropertyMetadata(typeof(MasterWindow)));
CloseWindowCommand = new RoutedCommand("CloseWindow", typeof(MasterWindow));
CommandManager.RegisterClassCommandBinding(typeof(MasterWindow), new CommandBinding(CloseWindowCommand, CloseWindowEvent));
}
public static readonly DependencyProperty WindowTitleProperty = DependencyProperty.Register("WindowTitle", typeof(object), typeof(MasterWindow), new UIPropertyMetadata());
public object WindowTitle
{
get { return (object)GetValue(WindowTitleProperty); }
set { SetValue(WindowTitleProperty, value); }
}
private static void CloseWindowEvent(object sender, ExecutedRoutedEventArgs e)
{
MasterWindow control = sender as MasterWindow;
if (control != null)
{
Window objWindow = Window.GetWindow(((FrameworkElement)sender));
if (objWindow != null)
{
if (objWindow.Name.ToLower() != "unlockscreenwindow")
{
Window.GetWindow(((FrameworkElement)sender)).Close();
}
}
}
}
}
}
Styles for master window :
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:local="clr-namespace:WpfApplication2"
x:Class="MasterWindow">
<Style x:Key="WindowTitle" TargetType="ContentPresenter">
<Setter Property="Control.FontFamily" Value="Segoe UI"></Setter>
<Setter Property="Control.FontSize" Value="14"></Setter>
<Setter Property="Control.FontWeight" Value="SemiBold"></Setter>
<Setter Property="Control.Foreground" Value="White"></Setter>
<Setter Property="Control.VerticalAlignment" Value="Top"></Setter>
<Setter Property="Control.HorizontalAlignment" Value="Left"></Setter>
<Setter Property="Control.VerticalContentAlignment" Value="Top"></Setter>
</Style>
<Style x:Key="closebutton" BasedOn="{x:Null}" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle
Opacity="1"
RadiusX="2"
RadiusY="2"
Stroke="#ffffff"
StrokeThickness="1">
<Rectangle.Fill>
<LinearGradientBrush
StartPoint="0.6190476190476191,-0.5"
EndPoint="1.1128888811383928,1.426776123046875">
<LinearGradientBrush.GradientStops>
<GradientStopCollection>
<GradientStop
Color="#2E4C87"
Offset="0" />
<GradientStop
Color="#FFffffff"
Offset="1" />
</GradientStopCollection>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Path
Margin="5,5,5,5"
Stretch="Fill"
Opacity="1"
Data="M 808.8311767578125,278.7662353515625 C808.8311767578125,278.7662353515625 820,268 820,268 "
Stroke="#ffffff"
StrokeThickness="2" />
<Path
Margin="5,5,5,5"
Stretch="Fill"
Opacity="1"
Data="M 809.4155883789062,268.3636474609375 C809.4155883789062,268.3636474609375 820,279 820,279 "
Stroke="#ffffff"
StrokeThickness="2" />
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True"/>
<Trigger Property="IsDefaulted" Value="True"/>
<Trigger Property="IsMouseOver" Value="True"/>
<Trigger Property="IsPressed" Value="True"/>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type local:MasterWindow}">
<Setter Property="IsTabStop" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MasterWindow}">
<StackPanel>
<Border x:Name="border" Background="WhiteSmoke" BorderBrush="#2E4C87" BorderThickness="7" CornerRadius="8,8,8,8" >
<Border.BitmapEffect>
<DropShadowBitmapEffect Color="Black" Direction="320" Opacity="0.75" ShadowDepth="8"></DropShadowBitmapEffect>
</Border.BitmapEffect>
<Border.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="0.95" ScaleY="0.95"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="0"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</Border.RenderTransform>
<Border.Triggers>
<EventTrigger RoutedEvent="Border.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" From="0" To="0.96" Duration="0:0:0.6"/>
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" From="0" To="0.96" Duration="0:0:0.6"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Border.Triggers>
<Grid HorizontalAlignment="Stretch" >
<Grid.RowDefinitions>
<RowDefinition Height="32"></RowDefinition>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border BorderThickness="5,5,3,0" Background="#2E4C87" BorderBrush="#2E4C87" CornerRadius="5,4,0,0" VerticalAlignment="Top" Height="32" Margin="-6,-6,-4,0" >
<Grid Background="Transparent" HorizontalAlignment="Stretch" Height="32" VerticalAlignment="Center" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<ContentPresenter Content="{TemplateBinding WindowTitle}" Margin="0,4,0,0" HorizontalAlignment="Stretch" Style="{StaticResource WindowTitle}" />
<Button Name="btnClose" Style="{StaticResource closebutton}" Cursor="Hand" Command="{x:Static local:MasterWindow.CloseWindowCommand}" VerticalAlignment="Top" Height="18" HorizontalAlignment="Right" Width="18" Margin="0,5,8,0" Grid.Column="1" />
</Grid>
</Border>
<Border BorderBrush="Transparent" BorderThickness="7,0,7,7" VerticalAlignment="Top" HorizontalAlignment="Left" CornerRadius="0,0,10,10" Grid.Row="1"></Border>
<ContentPresenter Grid.Row="1" Content="{TemplateBinding Content}" VerticalAlignment="Top" Margin="0,-6,0,0"/>
</Grid>
</Border>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android, How can I extract mobile information? I want to collect some information of mobile phone such as phone number, which brand it is, model of the device and product name.
I know how to extract phone number but i don't know the rest. if it's possible guide me please.
[EDITED]
Thank you dear friends, I did what you suggested me and now every thing is ok in Emulator and I have result. But the problem is when I want to run it on My phones (Galaxy S and Galaxy S2) both of them crash. What is the problem?
Thanks
A: Refer andorid.os.Build class at http://developer.android.com/reference/android/os/Build.html
A: You can use
android.os.Build
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I add certain commands to .bash_history permanently? I use bash and I sometimes have to type some very long commands for certain tasks. These long commands are not regularly used and generally gets overwritten in .bash_history file by the time I use them again. How can I add certain commands to .bash_history permanently?
Thanks.
A: As others have mentioned, the usual way to do that would be to store your long commands as either aliases or bash functions. A nice way to organise them would the to put them all in a file (say $HOME/.custom_funcs) then source it from .bashrc.
If you really really want to be able to load commands into your bash history, you can use the -r option of the history command.
From the man page:
-r Read the current history file and append its contents to the history list.
Just store all your entries in a file, and whenever you need your custom history loaded simply run history -r <your_file>.
Here's a demo:
[me@home]$ history | tail # see current history
1006 history | tail
1007 rm x
1008 vi .custom_history
1009 ls
1010 history | tail
1011 cd /var/log
1012 tail -f messages
1013 cd
1014 ls -al
1015 history | tail # see current history
[me@home]$ cat $HOME/.custom_history # content of custom history file
echo "hello world"
ls -al /home/stack/overflow
(cd /var/log/messages; wc -l *; cd -)
[me@home]$ history -r $HOME/.custom_history # load custom history
[me@home]$ history | tail # see updated history
1012 tail -f messages
1013 cd
1014 ls -al
1015 history | tail # see current history
1016 cat .custom_history
1017 history -r $HOME/.custom_history
1018 echo "hello world"
1019 ls -al /home/stack/overflow
1020 (cd /var/log/messages; wc -l *; cd -)
1021 history | tail # see updated history
Note how entries 1018-1020 weren't actually run but instead were loaded from the file.
At this point you can access them as you would normally using the history or ! commands, or the Ctrl+r shortcuts and the likes.
A: How about just extending the size of your bash history file with the shell variable
HISTFILESIZE
Instead of the default 500 make it something like 2000
A: The canonical answer is to create scripts containing these commands.
Edit Supposing you have the following history entries;
find /var/www -name '*.html' -exec fgrep '<title>' {} /dev/null \;
find ~/public_html -name '*.php' -exec fgrep include {} /dev/null \;
... you can try to isolate the parameters into a function something like this;
r () {
find "$1" -name "*.$2" -exec fgrep "$3" {} /dev/null \;
}
... which you could use like this, to repeat the history entries from above:
r /var/www html '<title>'
r ~/public_html php include
Obviously, the step is then not very long to create a proper script with defaults, parameter validation, etc. (Hint: you could usefully default to the current directory for the path, and no extension for the file name, and add options like --path and --ext to override the defaults when you want to; then there will be only one mandatory argument to the script.)
Typically, you would store the script in $HOME/bin and make sure this directory is added to your PATH from your .profile or similar. For functions, these are usually defined in .profile, or a separate file which is sourced from this file.
Having it in a central place also helps develop it further; for example, for precision and perhaps some minor added efficiency, you might want to add -type f to the find command; now there is only one place to remember to edit, and you will have it fixed for good.
A: You can create an alias for your command.
alias myalas='...a very long command here...'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why does my large 5D array cause a stack overflow exception only as a member variable? I'm currently writing a program where I need to run many simulations and speed is the name of the game. I'm currently using one long linear array allocated on heap and working out the dimensions myself and pulling straight from the index I work out. A co-worker has written a similar program and has got a good speed boost from using a 5D array. I know it would be very easy to allocate this as a vector, but as far as I'm aware there is a speed cost to using the vector as a result of bounds checking.
My question is why does this occur?
This compiles and runs fine:
int Array[20][20][20][20][20];
int main()
{
return 0;
}
This compiles but throws a stack overflow exception when wrapped in a class:
class Foo
{
int Array[20][20][20][20][20];
};
int main()
{
Foo foo;
return 0;
}
I have tried modifying my stack size in the Visual Studio 2005 linker options as well as changing the Enable Larger Addresses option, but nothing seems to make any difference.
A: The static array will be directly mapped into memory, not on the stack. The member variable will be allocated on the stack, which is likely not large enough by default. Also, vector doesn't do any bounds checking in operator[].
A: Because when class instances are created as local objects inside functions (as opposed to global objects at the file scope (including static) or dynamically created in the heap), they typically use the stack as storage.
A: So how to fix it? Create your object as a pointer, or create the storage inside the object as a pointer.
std::auto_ptr<Foo> foo(new Foo);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Template pgettext-like tag In Django templates there is a {% trans %} tag for intenationalizing templates. It behaves like ugettext() function.
Is there also a tag behaving like pgettext() in django templates, where I can specify message context?
A: Yes, there is, but it'll be in the upcoming Django 1.4 or you can try it by using Django development version.
The tag works like this:
{% trans "Hello" context "greeting" %}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Runtime.exec doesn't compile java file I compile java file by Runtime.exec("javac MyFrog.java");
It says no errors, doesn't output anything, but doesn't create MyFrog.class file.
if i write Runtime.exec("javac") it outputs to output some help text.
So I understand that program is working, but don't create class file. Permissions are ok.
A: javac -verbose should give you lot more information, specifically the directory where the file is created. Since you are able to recognize output help text without any parameters, I assume you are capturing the process's stderr and assume you are doing the same for stdout as well (though javac does not seem to write anything to stdout).
Where are you checking for the existence of the .class file? It is created in the same directory as the .java file. If MyFrog.java has a package declaration it will not be created in the package sub-dir; for that you have to use -d argument.
A: make sure that MyFrog.java is present in working directory
A: Try javac -verbose and make sure your classpath is set correct.
A: You can use ProcessBuilder or Runtime.exec() method to create new process,
String []cmd={"javac","Foo.java"};
Process proc=Runtime.getRuntime().exec(cmd);
proc.waitFor();
Or use ProcessBuilder
ProcessBuilder pb = new ProcessBuilder("javac.exe","-verbose", "Foo.java");
pb.redirectErrorStream(true);
Process p = pb.start();
p.waitFor();
InputStream inp=p.getInputStream();
int no=inp.read();
while(no!=-1)
{
System.out.print((char)no);
no=inp.read();
}
A: I always find this resource answers all questions about Java exec.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery AJAX response with 200, but no response data, for some remote URL There are several questions on Stack Overflow saying cross domain AJAX request etc will not work because of security reasons. Some questions like this explain this. (Please let me know if I am wrong.)
This is working perfectly fine:
$(document).ready(function() {
$.getJSON("http://search.twitter.com/search.json?q=test&callback=?", function(data) {
alert("test alert outside loop");
$.each(data.results, function() {
alert("test alert inside loop");
});
});
});
But just replacing the URL with my application won't work. In that case response code is 200, but there's no response data. There is an hit on my application; I can see that in console.
$(document).ready(function() {
$.getJSON("http://192.168.1.2:3000/cities.json?callback=?", function(data) {
alert("test alert outside loop");
$.each(data.results, function() {
alert("test alert inside loop");
});
});
});
I am developing a very simple mobile app using PhoneGap so I need to make this call using JavaScript. But the main thing that's confusing me is why the Twitter call is working, but the call to my app isn't. I've also tried to remove the protect_from_forgery call in my application controller in my Rails app, but i don't think that matters.
EDIT
i have deployed the app on http://deals.textadda.com/cities.json now check it... Its not working..
U can try it. these two links http://jsfiddle.net/2arbY/
http://jsfiddle.net/fHxf9/
A: Probably data.results doesn't exist, even if data does. What do you get if you alert(data); (or console.log(data); ) outside the loop?
EDIT
Your app isn't generating a callback wrapper. For instance, http://deals.textadda.com/cities.json?callback=abc should generate a JSON object wrapped in a function call of abc, in the same way, for example, the twitter response does: http://search.twitter.com/search.json?q=test&callback=abc.
A: you are running into cross-domain issues due to same-origin-policy the ip you are trying to get the json from should reside on the same sever from which you are originating the request.
try using
$.getJSON("192.168.1.2/cities.json?callback=?", func
A: The problem is that this remote server returns JSON, not JSONP. It returns:
{"lines":[{"line":"COLOMBO - BADULLA"},{"line":"COLOMBO - MATALE"},{"line":"COLOMBO - PUTTLAM"},{"line":"COLOMBO - THANDIKULAM"},{"line":"COLOMBO - TALAIMANNAR"},{"line":"COLOMBO - BATTICALOA"},{"line":"COLOMBO - TRINCOMALEE"},{"line":"COLOMBO - MATARA"},{"line":"COLOMBO - AVISSAWELLA"},{"line":"COLOMBO - MIHINTALE"}]}
instead of:
someCallbackName({"lines":[{"line":"COLOMBO - BADULLA"},{"line":"COLOMBO - MATALE"},{"line":"COLOMBO - PUTTLAM"},{"line":"COLOMBO - THANDIKULAM"},{"line":"COLOMBO - TALAIMANNAR"},{"line":"COLOMBO - BATTICALOA"},{"line":"COLOMBO - TRINCOMALEE"},{"line":"COLOMBO - MATARA"},{"line":"COLOMBO - AVISSAWELLA"},{"line":"COLOMBO - MIHINTALE"}]})
Thats why I was not be able to consume a remote domain using AJAX unless this remote resource supports JSONP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHPUnit cannot read Session ( CodeIgniter and CIUnit ) I am using CodeIgniter 1.7.2 and CIUnit v.0.17
I am fairly new to PHPunit so please bear with me on this one. I have set-up phpUnit project extended with CIUnit to test an app built in the codeigniter framework. My problem is that when I run a test I have written the method being called from the test checks a session variable ‘LOGGED_IN’ which checks to see if a user has logged into the system. When I run my test this is obviously falling over at this point as the session variable has not been set as it is being called via the command line and not via a http request which would have initialised the session.
In my opinion, PHPunit cannot read Sessions when I run test through commandline...
How would I solve this?
A: In the code block that sets the session var / checks credentials include this code:
if(php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
//code to say logged in probably return true;
return true;
} else {
//normal login checking of credentials
}
This will ensure it is being run from command line and is safe-ish to route around credential checking (probably.)
Also note that, even in that oldish version of CI you should really be using the $this->db->session->userdata() function to check session vars, not accessing the $_SESSION variable directly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Compiler error message with cout I mistyped the error message before. It is fixed now.
I'm currently getting the following compiler error message
error: no match for 'operator<<' in 'std::cout << Collection::operator[](int)(j)'
The code that the compiler is complaining about is
cout << testingSet[j];
Where testingSet is an object of type Collection that has operator[] overloaded to return an object of type Example. Example has a friend function that overloads operator<< for ostream and Example.
note: this actually compiles just fine within Visual Studio; however does not compile using g++.
Here is the implementation of operator<<:
ostream& operator<<(ostream &strm, Example &ex)
{
strm << endl << endl;
strm << "{ ";
map<string, string>::iterator attrib;
for(attrib = ex.attributes.begin(); attrib != ex.attributes.end(); ++attrib)
{
strm << "(" << attrib->first << " = " << attrib->second << "), ";
}
return strm << "} classification = " << (ex.classification ? "true" : "false") << endl;
}
And the operator[]
Example Collection::operator[](int i)
{
return examples[i];
}
A: Probably your operator should be declared as:
ostream& operator<<(ostream &strm, const Example &ex)
Note the const-reference to Example.
Visual Studio has an extension that allows to bind a reference to a non-const r-value. My guess is that your operator[] returns an r-value.
Anyway, an operator<< should be const as it is not expected to modify the written object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to create dynamic embed function? Is it possible to create dynamic embed function in ActionScript3
for example like this
public function embedImage(path:String):Bitmap{
[Embed(source = path, mimeType = "image/png")]
var NewBitmapClass:Class;
var image:Bitmap=new NewBitmapClass();
return image;
}// tried it, it doesnt work
or maybe in some other way, or even if it is at all possible?
A: The closest you can get with the "dynamic" part, is to create a wrapper class, where you define your images, and you can get them as Bitmap later on by an id.
Unfortunately the properties are public, otherwise the hasOwnProperty function doesn't return true. (If someone finds a better way, please let me know)
See below:
package {
import flash.display.Bitmap;
public class DynamicEmbed {
[Embed(source = "../images/cat.jpg")]
public var cat : Class;
[Embed(source = "../images/parrot.jpg")]
public var parrot : Class;
[Embed(source = "../images/pig.jpg")]
public var pig : Class;
[Embed(source = "../images/quail.jpg")]
public var quail : Class;
public function DynamicEmbed() {
}
public function getBitmap(id : String) : Bitmap {
if(hasOwnProperty(id)) {
var bitmap : Bitmap = new this[id]();
return bitmap;
}
return null;
}
}
}
A: Embedded elements are embedded at compile time. You can't dynamically embed something at compile time... If you want to load resources dynamically, use the Loader.
A: No, embed source is embedded at compile time. You can not embed anything at run time. That's what embed means, embedding during building the swf.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to stop current process of C# application and start another function I am explaining my scenario, i have a function which print 1 to 10000 while printing i have to stop the process and let user know the current i value and if user presses enter it should continue again.
i am using
if ((Console.KeyAvailable) && (Console.ReadKey(true).Key == ConsoleKey.Escape))
but it doesn,t work, to complicate my task i am using threads, even if i manage to break this thread, child thread starts executing, i just want to stop the entire execution process for a moment and execute another function.
A: Check out the BackgroundWorker class, specifically, how to implement cancellation.
You'll basically need to check inside the loop if a cancellation is pending. If it is, then exit the loop.
A: If your using Threads. You can use this kind of code..
// Start
thread = new Thread(new ThreadStart(YourCommand));
thread.Start();
// Pause
if (thread != null)
{
thread.Suspend();
}
//Continue
if (thread != null)
{
thread.Resume();
}
//Alive
if (thread != null)
{
if (thread.IsAlive)
{
thread.Abort();
}
}
Or you can use timer....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Load png files in XNA I am trying to load all png files from smoe directory( named "bee") but getting an exception that dir. does not exist.
Also, i am sharing the code.
Plese help where i am doing mistake
private List<string> LoadFiles(string contentFolder)
{
DirectoryInfo dir = new DirectoryInfo(this.Content.RootDirectory + "\\" + contentFolder);
if (!dir.Exists)
throw new DirectoryNotFoundException();
List<string> result = new List<string>();
//Load all files that matches the file filter
FileInfo[] files = dir.GetFiles("*.png");
foreach (FileInfo file in files)
{
result.Add(file.Name);
}
return result;
}
A: Backslashes need to be escaped. e.g. "C:\\path\\to\\some\\directroy\\"
A: *
*Use Path.Combine to build paths
*if you have not selected "Copy to output" in your assets, you won't find that ".png" in that folder.
if your game path is "c:\game\source" and your content project path is "c:\game\content", the content folder you are trying to open, will be "c:\game\source\bin\x86\Debug" and there should be only .xnb files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create space between buttons? I am already creating multiple buttons but I don't know how to align the buttons.
My code is here:
- (void)viewDidLoad
{
//self.title=@"Asset Management";
[super viewDidLoad];
listOfItems = [[NSMutableArray alloc] init];
[listOfItems addObject:@"User Information"];
[listOfItems addObject:@"Regional Settings"];
[listOfItems addObject:@"Configuration"];
toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 20, 320, 44)];
//UIToolbar* toolbar = [[UIToolbar alloc] initWithFrame:CGs
toolbar.tintColor = [UIColor clearColor];
[toolbar setTranslucent:YES];
// create the array to hold the buttons, which then gets added to the toolbar
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];
// Create button1
UIBarButtonItem *propertiesButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(button1Pressed)];
[buttons addObject:propertiesButton];
[propertiesButton release];
// Create button2
UIBarButtonItem *commentaryButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(button2Pressed)];
[buttons addObject:commentaryButton];
[commentaryButton release];
// Create button3
UIBarButtonItem *versionsButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(button3Pressed)];
[buttons addObject:versionsButton];
[versionsButton release];
// stick the buttons in the toolbar
[toolbar setItems:buttons animated:NO];
//self.toolbarItems = buttons;
[buttons release];
// and put the toolbar in the nav bar
[[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithCustomView:toolbar] autorelease]];
[toolbar release];
}
How do I create space b/w the buttons. Pls help me.
Thanks in advance!
A: You can add spaces between tool bar items using either of the two built-in space button types
UIBarButtonSystemItemFixedSpace and UIBarButtonSystemItemFlexibleSpace.
Fixed Space button
UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
target:nil
action:nil];
[fixedSpace setWidth:20];
Flexible Space button
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
Add the space bar buttons in between the other tool bar items.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: File not found error with FMOD FMOD_OUTPUTTYPE_WAVWRITER_NRT i'm trying to run FMOD in WAVWRITER_NRT mode. I was modifying the example bundled with FMOD, but I always get an error on FMOD_System_Init. It says that the file cannot be found.
I thought it would create a file to write output to. I have also tried placing a wav file with that name into that location. Still, I always have this error.
Here is the code:
result = FMOD_System_Create(&gSystem);
CHECK_RESULT(result);
result = FMOD_System_SetOutput(gSystem, FMOD_OUTPUTTYPE_WAVWRITER_NRT);
CHECK_RESULT(result);
result = FMOD_System_Init(gSystem, 4, FMOD_INIT_NORMAL, "/sdcard/fmod/out.wav");
CHECK_RESULT(result);
result = FMOD_System_CreateSound(gSystem, "/sdcard/fmod/test1.mp3", FMOD_CREATESTREAM, 0, &gSound);
CHECK_RESULT(result);
Please help!
A: Add WRITE_EXTERNAL_STORAGE permission to the manifest.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Manually packaging data for CakePHP's save() I'm trying to package up some data for the save() function in cakephp. I'm new to PHP, so I'm confused about how to actually write the below in code:
Array
(
[ModelName] => Array
(
[fieldname1] => 'value'
[fieldname2] => 'value'
)
)
Thank you!
A: To answer your question, you can create the array structure you need, and save it, by doing this:
<?php
$data = array(
'ModelName' => array(
'fieldname1' => 'value',
'fieldname2' => 'value'
)
);
$this->ModelName->save($data);
?>
Please note:
Based on what you've written above in your comments it looks like you're not keeping to the CakePHP conventions. It's possible to do things this way but you'll save yourself a lot of time and trouble if you decided to stick with the CakePHP defaults as much as possible, and only do it your own way when you have a good reason to.
A couple things to remember are:
*
*Model names should be singular. This means that your model should be called Follower instead of Followers.
*The model's primary key in the database should be named just id, not followers_id, and should be set as PRIMARY KEY and AUTO_INCREMENT in your database.
If you decide not to follow the conventions you'll probably find yourself scratching your head, wondering why things aren't working, every step of the way. Try having a look at the CakePHP documentation for more details.
A: I think you need to do like below:
$this->Followers->create();
$this->data['Followers']['user_id'] = $user_id;
$this->data['Followers']['follower_id'] = $follower_id; // If it is primary and auto increment than you don't need this line.
$this->Followers->save($this->data)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Search for multiple words in very large text files (10 GB) using C++ the fastest way I have this program where I have to search for specific values and its line number in very large text file and there might be multiple occurences for the same value.
I've tried a simple C++ programs which reads the text files line by line and searches for a the value using strstr but it's taking a very longgggggggggggggg time
I also tried to use a system command using grep but still it's taking a lot of time, not as long as before but it's still too much time.
I was searching for a library I can use to fasten the search.
Any help and suggestions? Thank you :)
A: There are two issues concerning the spead: the time it takes to actually
read the data, and the time it takes to search.
Generally speaking, the fastest way to read a file is to mmap it (or
the equivalent under Windows). This can get complicated if the entire
file won't fit into the address space, but you mention 10GB in the
header; if searching is all you do in the program, this shouldn't create
any problems.
More generally, if speed is a problem, avoid using getline on a
string. Reading large blocks, and picking the lines up (as char[])
out of them, without copying, is significantly faster. (As a simple
compromize, you may want to copy when a line crosses a block boundary.
If you're dealing with blocks of a MB or more, this shouldn't be too
often; I've used this technique on older, 16 bit machines, with blocks
of 32KB, and still gotten a significant performance improvement.)
With regards to searching, if you're searching for a single, fixed
string (not a regular expression or other pattern matching), you might
want to try a BM search. If the string you're searching for is
reasonably long, this can make a significant difference over other
search algorithms. (I think that some implementations of grep will
use this if the search pattern is in fact a fixed string, and is
sufficiently long for it to make a difference.)
A: Use multiple threads. Each thread can be responsible for searching through a portion of the file. For example on a 4 core machine spawn 12 threads. The first thread looks through the first 8%evening of the file, the second thread the second 8% of the file, etc. You will want to tune the number of threads per core to keep the cpu max utilized. Since this is an I/O bound operation you may never reach 100% cpu utilization.
Feeding data to the threads will be a bottleneck using this design. Memory mapping the file might help somewhat but at the end of the day the disk can only read one sector at a time. This will be a bottleneck that you will be hard pressed to resolve. You might consider starting one thread that does nothing but read all the data in to memory and kick off search threads as the data loads up.
A: Since files are sequential beasts searching from start to end is something that you may not get around however there are a couple of things you could do.
if the data is static you could generate a smaller lookup file (alt. with offsets into the main file), this works good if the same string is repeated multiple times making the index file much smaller. if the file is dynamic you maybe need to regenerate the index file occassionally (offline)
instead of reading line by line, read larger chunks from the file like several MB to speed up I/O.
A: If you'd like to do use a library you could use xapian.
You may also want to try tokenizing your text before doing the search and I'd also suggest you to try regex too but it will take a lot if you don't have an index on that text so I'd definitely suggest you to try xapian or some search engine.
A: If your big text file does not change often then create a database (for example SQLite) with a table:
create table word_line_numbers
(word varchar(100), line_number integer);
Read your file and insert a record in database for every word with something like this:
insert into word_line_numbers(word, line_number) values ('foo', 13452);
insert into word_line_numbers(word, line_number) values ('foo', 13421);
insert into word_line_numbers(word, line_number) values ('bar', 1421);
Create an index of words:
create index wird_line_numbers_idx on word_line_numbers(word);
And then you can find line numbers for words fast using this index:
select line_number from word_line_numbers where word='foo';
For added speed (because of smaller database size) and complexity you can use 2 tables: words(word_id integer primary key, word not null) and word_lines(word_id integer not null references words, line_number integer not null).
A: I'd try first loading as much of the file into the RAM as possible (memory mapping of the file is a good option) and then search concurrently in parts of it on multiple processors. You'll need to take special care near the buffer boundaries to make sure you aren't missing any words. Also, you may want to try something more efficient than the typical strstr(), see these:
Boyer–Moore string search algorithm
Knuth–Morris–Pratt algorithm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What does cassandra do during compaction? I know that cassandra merges sstables, row-keys, remove tombstone and all.
*
*But i am really interested to know how it performs compaction ?
*As sstables are immutable does it copy all the relevant data to new file? and while writing to this new file it discard the tombstone marked data.
i know what compaction does but want to know how it make this happen(T)
A: I hope this thread helps, provided if you follow all the posts and comments in it
http://comments.gmane.org/gmane.comp.db.cassandra.user/10577
AFAIK
Whenever memtable is flushed from memory to disk they are just appended[Not updated] to new SSTable created, sorted via rowkey.
SSTable merge[updation] will take place only during compaction.
Till then read path will read from all the SSTable having that key you look up and the result from them is merged to reply back,
Two types : Minor and Major
Minor compaction is triggered automatically whenever a new sstable is being created.
May remove all tombstones
Compacts sstables of equal size in to one [initially memtable flush size] when minor compaction threshold is reached [4 by default].
Major Compaction is manually triggered using nodetool
Can be applied over a column family over a time
Compacts all the sstables of a CF in to 1
Compacts the SSTables and marks delete over unneeded SSTables. GC takes care of freeing up that space
Regards,
Tamil
A: Are two ways to run compaction :
A- Minor compaction. Run automatically.
B- Major compaction. Run mannualy.
In both cases takes x files (per CF) and process them. In this process mark the rows with expired ttl as tombstones, and delete the existing tombstones. With this generates a new file. The tombostones generated in this compaction, will be delete in the next compaction (if spend the grace period, gc_grace).
The difference between A and B are the quantity of files taken and the final file.
A takes a few similar files (similar size) and generate a new file.
B takes ALL the files and genrate only one big file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Why is there a SELECT 1 from table? I came across a fictitious SQL, i am not sure what is the original intend, it looks like:
SELECT COUNT (*)
INTO miss
FROM billing b
WHERE b.network= network1
and NOT EXISTS (SELECT 1 from vas NV WHERE NV.network =
b.network);
Why is there a select 1, and not exists?
A: There is a great AskTom Q&A on the use of EXISTS vs IN (or NOT EXISTS vs NOT IN):
http://asktom.oracle.com/pls/asktom/f?p=100:11:1371782877074057::::P11_QUESTION_ID:953229842074
Basically using EXISTS only checks for the existence of the row in the subselect and does not check every matching row (which IN would). Therefore when using EXISTS or NOT EXISTS you do not need to actually select a particular value so selecting a placeholder (in this case "1") is enough.
In your particular SQL statement, the NOT EXISTS clause ensures that the main SELECT will only return rows where there isn't a corresponding row in the VAS table.
A: When using the EXISTS keyword you need to have a sub-select statement, and only the existence of a row is checked, the contents of the row do not matter. SELECT is a keyword that controls what is inside the columns that are returned. SELECTing 1 or NV.network will return the same number of rows.
Therefore you can SELECT whatever you want, and canonical ways to do that include SELECT NULL or SELECT 1.
Note that an alternative to your query is:
SELECT count(*) INTO miss
FROM billing b
LEFT JOIN vas NV ON NV.network = b.network
WHERE b.network = network1
AND NV.network IS NULL
(left join fills right-hand columns with NULL values when the ON condition cannot be matched.
A: This code of yours is for mainly written from a performance stand point
I am mentioning only about the inner query. Since it needed explanation for user. What ever sql I have used should be inserted to the actual query user has used above
and NOT EXISTS (SELECT 1 from vas NV WHERE NV.network =
b.network);
Explaining the inner query only
Usually people use to put select NV.netword but this return a data that is just used to identify if there doesn't exist a data. So, ideally what ever is returned in inner query is not even checked in the parent query. So to reduce Bytes in explain plan, we use select 1 which will have minimum byte cost and which in-turn will reduce the cost of the query.
To view the difference i suggest downloading oracle sql developer and running both the query in explain plan window and watch out the bytes column for each query
SELECT nv.network from vas NV WHERE NV.network = b.network
// cost will be depended on the value nv.network contain and that is selected in the where condition
while
SELECT 1 from vas NV WHERE NV.network = b.network
// cost will be independent of the column and cost lesser bytes selected and lesser cost.
Not exist you will be able to check with other answers.
A: SELECT 1 from vas NV WHERE NV.network = b.network
If this query returns a row, it means that there is a record in the NV table that matches one in the billing table.
NOT EXISTS negates it, satisfying there WHERE clause if there is NOT a record in the NV table that matches one in the billing table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: button control php page include because of considering embed google ads into include page. I am giving up jquery.loading
(google not allow jquery ajax and jquery loading for ads, now even iframe page)
so is it possible use other javascript method for control php page include?
more explain, if my page need to including 10 pages, and I do not want they all loading in same time(such slowly for loading at same time). So I put 10 buttons for switching include page.
only click each button, loading the chosen include page to main. and click another one, loading the new one and hidden the first one.
A: As long as they are links google should crawl them fine, you just need to stop the link from being clicked on in javascript...
<a href="test.html" class="test">Test Page</a>
Then your jquery...
$(document).ready(function(){
$('a.test').click(function(e){
// Load the AJAX here
// Stop the click from actually going to the page
e.preventDefault();
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove UIImage Background color and make it transparent? I wanted to remove UIImage background color and make it transparent...
I tried this but the following code just changing White background color into Black Color.
UIImage* createColorMaskedImage(UIImage* originalImage){
float maskingColors[6] = {0xEE, 0xFF, 0xEE, 0xFF, 0xEE, 0xFF};
CGImageRef maskedImageRef = CGImageCreateWithMaskingColors(originalImage.CGImage, maskingColors);
UIImage* maskedImage = [UIImage imageWithCGImage:maskedImageRef];
CGImageRelease(maskedImageRef);
return maskedImage;
}
UIImage *watchImage = [UIImage imageNamed:@"watch2.jpg"];
// Mask image
colorMaskImage_ = createColorMaskedImage(watchImage);
//create image view and set its poistion.
UIImageView* maskImageView = [[UIImageView alloc] initWithImage:colorMaskImage_];
CGRect frame = maskImageView.frame;
frame.origin = CGPointMake(80,60);
maskImageView.frame = frame;
maskImageView.backgroundColor = [UIColor clearColor];
[self.view addSubview:maskImageView];
[maskImageView release];
A: Swift version
func makeTransparent(image: UIImage) -> UIImage? {
guard let rawImage = image.cgImage else { return nil}
let colorMasking: [CGFloat] = [255, 255, 255, 255, 255, 255]
UIGraphicsBeginImageContext(image.size)
if let maskedImage = rawImage.copy(maskingColorComponents: colorMasking),
let context = UIGraphicsGetCurrentContext() {
context.translateBy(x: 0.0, y: image.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.draw(maskedImage, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return finalImage
}
return nil
}
A: Your watch2.jpg probably doesn't have alpha values, which would let it have transparent areas.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mapping thread id from top to gdb I am using top to see the thread wise cpu usage using
top -H -p `pgrep app.out`
It is showing some pid for each thread like
4015
4016
I had attached gdb to the application using gdb attach command.
Now I want to switch to thread 4015 which is showing inside top o/p.
How can I do that ?
If I fire thread 4015 it is showing no thread . as I need to give thread id in gdb.
So how can I map top thread id to gdb thread id ?
A: You should be able to match the LWP displayed in GDB with the top information:
according to my quick tests with Firefox, you can see that in your top -H -p:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
6492 kevin 20 0 1242m 386m 31m S 0.3 4.9 0:09.00 firefox
6470 kevin 20 0 1242m 386m 31m S 5.7 4.9 5:04.89 firefox
and that in GDB info threads:
22 Thread 0x7fe3d2393700 (LWP 6492) "firefox" pthread_cond_timedwait...
...
* 1 Thread 0x7fe3dd868740 (LWP 6470) "firefox" __GI___poll ()...
EDIT: just for you in exclusivity, here is a brand new commands for gdb: lwp_to_id <lwp>:
import gdb
class lwp_to_id (gdb.Command):
def __init__(self):
gdb.Command.__init__(self, "lwp_to_id", gdb.COMMAND_OBSCURE)
def invoke(self, args, from_tty):
lwp = int(args)
for thr in gdb.selected_inferior().threads():
if thr.ptid[1] == lwp:
print "LWP %s maps to thread #%d" % (lwp, thr.num)
return
else:
print "LWP %s doesn't match any threads in the current inferior." % lwp
lwp_to_id()
(working at least on the trunk version of GDB, not sure about the official releases !
A: Do a
ps xjf
This will give you a tree of all processes with their pid and parent pid.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Insert missing comma (perl) Line:
výkonná produkce: Martin Scorsese, Timothy Van Patten střih: Kate Sanford, Tim Streeto herec(s): Hong Eun Hee (Mi Geum (soţia lui Sang Ok)) Han Hee (Jang Mi Ryung) Kim Yoo Mi (Yoon Chae Yeon) Jae-ho Song (Im Bong Hoek (tatăl lui Sang Ok))
I want insert, with perl, missing comma like this:
výkonná produkce: Martin Scorsese, Timothy Van Patten střih: Kate Sanford, Tim Streeto herec(s): Hong Eun Hee (Mi Geum (soţia lui Sang Ok)), Han Hee (Jang Mi Ryung), Kim Yoo Mi (Yoon Chae Yeon), Jae-ho Song (Im Bong Hoek (tatăl lui Sang Ok))
Thanks.
A: Without any details on constraints, we have to guess what you need. I'm guessing this:
s/\) /), /g
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to attach a number to a movie clip This is what I am trying to achieve but I do not remember the syntax in AS2 if someone could please help.
public function highlightCan() {
var glowId = String(this);
var newId = glowId.substring(47);
trace ("newId : " + newId);
new Tween(_parent._glow["newId"], "_alpha",
mx.transitions.easing.None.easeNone, _parent._glow0._alpha, 100, 2, false);
}
The newId, is what I am trying to attach to _glow.
If I hard code this value i.e. _glow0 or _glow1, this works but this value needs to be dynamic, in order to get the rollover state working. per highlightCan();
Thanks
A: public function highlightCan(id:Number) {
var glowId = String(this);
var newId = glowId.substring(47);
trace ("newId : " + newId);
new Tween(_parent._glow["newId"], "_alpha",
mx.transitions.easing.None.easeNone,
eval("_parent._glow"+id)._alpha, 100, 2, false);
}
when you call the highlightCan() you must send the ID number e.g.: highlightCan(2) will make transition on _parent._glow2._alpha
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to create a .app file of my java project to run on mac os I am new to mac. I have a java project. I created a exe of that project using launch4j for window. Now I need to create a application for mac. I java project contains 5 java classes, also referred to some external jars. I found this site http://www.centerkey.com/mac/java/. But I struck when I tried to create the executable jar file. While working on window I used the following commands to create the class files and jar file.
To create class files..
javac one.java two.java -cp mail.jar;sqlite.jar Mainclass.java
To create the jar files for the classes created from the above command
jar cvf one.jar one.class
I used the same command in mac terminal. But the first command to create the class files doesn't work. Any suggestion....
A: AFAIK Eclipse can create Mac app bundles for Java projects, though i'm not used it and can't say how it works.
Try Export -> Other -> Mac OS X Application bundle
A: First thing first, DO NOT USE javapackager
javapackager is the packaging and signing tool released with JDK 8; When JDK 11 deleted javaFX, javapackager is also deleted as a part of it.
That's why you may encounter below issue when you try to use javapackager:
The operation couldn’t be completed. Unable to locate a Java Runtime that supports javapackager.
I specifically mention it here because there are so many outdated info throughout the internet, cost me so much time going round in circles.
How I managed to package self-contained Java Application
*
*Use Eclipse to generate runnable JAR file
a. Right click your project -> Export.
b. Select Java -> Runnable JAR file.
c. Next.
d. Specify Export destination, e.g. ~/Downloads/jar/HelloSwing.jar .
e. "Library handling" select "Extract required libraries into generated JAR".
f. Finish.
*Use jpackage to package
Input below command in the termnial:
jpackage --type pkg \
--temp ~/Downloads/temp \
--name HelloSwing \
--input ~/Downloads/jar \
--main-jar HelloSwing.jar \
--main-class com.cheng.rostergenerator.ui.Main
*Get generated files
In the current terminal path ~/ , HelloSwing-1.0.dmg (51MB) is generated, that is the install file.
Under ~/Downloads/temp, HelloSwing.app is generated (125MB), double click to launch the App.
This is just a Hello World project of Java Swing, however, the application image size is a bit daunting.
Anyway, happy coding!
Reference: jpackage command doc
A: Update on the above: The "Export -> Other -> Mac OS X Application bundle" does not work for me on current Eclipse and Java stuff. Trying to get around this stumbling block I found the following:
https://centerkey.com/mac/java/
I tried their sample for the tutorial, and it worked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MySQL Encrypt returns true on wrong field with numbers as salt I'm not totally sure how to describe this so the easiest way is with a test case. The running the following sql will return three rows on the select. My understanding of encrypt tells me that this shouldn't return any rows.
It only happens when the salt begins with two numbers.
Please also ignore the fact that encrypt is called how it is. Its a legacy app and I need to understand what is happening before making the change.
CREATE TABLE IF NOT EXISTS `test` (
`user` varchar(10) NOT NULL,
`pass` varchar(10) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `test` (`user`, `pass`) VALUES
('user', '11');
INSERT INTO `test` (`user`, `pass`) VALUES
('user', '22');
INSERT INTO `test` (`user`, `pass`) VALUES
('user', '33');
INSERT INTO `test` (`user`, `pass`) VALUES
('user', 'aa');
SELECT *
FROM `test`
WHERE encrypt( 'user', test.pass )
A: Here is clearly mentioned
If crypt() is not available on your system (as is the case with
Windows), ENCRYPT() always returns NULL.
so first check that crypt() is available or not
A: Check the output without WHERE clause -
SELECT *, ENCRYPT('user', pass) FROM test;
+------+------+-----------------------+
| user | pass | ENCRYPT('user', pass) |
+------+------+-----------------------+
| user | 11 | 11VKs9AZ4WOfc |
| user | 22 | 22QsW1gRCcd2I |
| user | 33 | 33PLcxSqvhZnc |
| user | aa | aaBrLCcg4bKmQ |
+------+------+-----------------------+
When you use WHERE clause, this values are converted to boolean; in your case value '11VKs9AZ4WOfc' is TRUE, but 'aaBrLCcg4bKmQ' is FALSE.
Here it is a small example that may explain this behavior -
SELECT 'A' = TRUE, '1' = TRUE;
+------------+------------+
| 'A' = TRUE | '1' = TRUE |
+------------+------------+
| 0 | 1 |
+------------+------------+
I think some of your values are cast as TRUE, and some as FALSE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7633103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits