text stringlengths 8 267k | meta dict |
|---|---|
Q: JScrollpane crashes in IE when content is created using JavaScript I'm using JScrollpane on a number of portlets, each pulling content from different sources.
One of the sources contains a JavaScript file, this then builds the html using a series of document.write() calls. There is nothing too difficult in the html that is created, just a few list objects, hyperlinks, and a couple of images, and there are no Flash elements.
When I try to put a JSCrollpane on this content, I get "Internet Explorer has encountered a problem and needs to close." This only happens in IE 8, in Chrome and Firefox there are no issues.
I have no control over the content and cannot change it.
I am using JQuery v1.6.1 and jScrollpane v2.0beta10.
A: is your code within a $(document).ready() block?
Another common cause of that error is having a background image on the body tag while using jquery 1.6.2, however you are using 1.6.1 so that shouldn't be an issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python array of datetime objects from numpy ndarray I have numpy ndarray which contains two columns: one is date, e.g. 2011-08-04, another one is time, e.g. 19:00:00:081.
How can I combine them into one array of datetime objects? Currently, they're strings in numpy array.
A: If the date and time string in the example.txt data file were given as one column with no separating whitespace, then genfromtxt could convert it into a datetime object like this:
import numpy as np
import datetime as dt
def mkdate(text):
return dt.datetime.strptime(text, '%Y-%m-%dT%H:%M:%S:%f')
data = np.genfromtxt(
'example.txt',
names=('data','num','date')+tuple('col{i}'.format(i=i) for i in range(19)),
converters={'date':mkdate},
dtype=None)
Given example.txt as it is, you could form the desired numpy array with
import numpy as np
import datetime as dt
import csv
def mkdate(text):
return dt.datetime.strptime(text, '%Y-%m-%d%H:%M:%S:%f')
def using_csv(fname):
desc=([('data', '|S4'), ('num', '<i4'), ('date', '|O4')]+
[('col{i}'.format(i=i), '<f8') for i in range(19)])
with open(fname,'r') as f:
reader=csv.reader(f,delimiter='\t')
data=np.array([tuple(row[:2]+[mkdate(''.join(row[2:4]))]+row[4:])
for row in reader],
dtype=desc)
# print(mc.report_memory())
return data
Merging two columns in a numpy array can be a slow operation especially if the array is large. That's because merging, like resizing, requires allocating memory for a new array, and copying data from the original array to the new one. So I think it is worth trying to form the correct numpy array directly, instead of in stages (by forming a partially correct array and merging two columns).
By the way, I tested the above csv code versus merging two columns (below). Forming a single array from csv (above) was faster (and the memory usage was about the same):
import matplotlib.cbook as mc
import numpy as np
import datetime as dt
def using_genfromtxt(fname):
data = np.genfromtxt(fname, dtype=None)
orig_desc=data.dtype.descr
view_desc=orig_desc[:2]+[('date','|S22')]+orig_desc[4:]
new_desc=orig_desc[:2]+[('date','|O4')]+orig_desc[4:]
newdata = np.empty(data.shape, dtype=new_desc)
fields=data.dtype.names
fields=fields[:2]+fields[4:]
for field in fields:
newdata[field] = data[field]
newdata['date']=np.vectorize(mkdate)(data.view(view_desc)['date'])
# print(mc.report_memory())
return newdata
# using_csv('example4096.txt')
# using_genfromtxt('example4096.txt')
example4096.txt is the same as example.txt, duplicated 4096 times. It's about 12K lines long.
% python -mtimeit -s'import test' 'test.using_genfromtxt("example4096.txt")'
10 loops, best of 3: 1.92 sec per loop
% python -mtimeit -s'import test' 'test.using_csv("example4096.txt")'
10 loops, best of 3: 982 msec per loop
A: To answer the question as it is, given a two-column NumPy array a, you could do
b = numpy.array([datetime.datetime.strptime(s + t, "%Y-%m-%d%H:%M:%S:%f")
for s, t in a])
Since the comments indicate that the original array a is constructed using genfromtxt(), you are probably better off joining the columns in the text file and defining a suitable converter (see the converters argument to genfromtxt()).
Edit: If the columns are of types S10 and S12 respectively as indicated in the comments, you can do a minor optimisation of this code since you don't need to explicitly join the columns:
a = numpy.array([("2011-08-04", "19:00:00:081"),
("2011-08-04", "19:00:00:181")],
dtype=[("", "S10"), ("", "S12")])
b = numpy.array([datetime.datetime.strptime(s, "%Y-%m-%d%H:%M:%S:%f")
for s in a.view("S22")])
The operation a.view("S22") is cheap as it does not copy the data. If your array is really big, this optimisation might be welcome, though it does not make a huge difference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Application is not working in Device but working in simulator in Blackberry I have one application by using which i will block the foreground application. It means when i am clicking any icon in the home screen it should not start. And my application is running in the background and will start when phone will start booting up. So i checked the Auto-run on start up. This is working fine in the simulator but not working in the device after running the cod file. I am running in Blackberry Storm. Here i am putting my code:
public class BlockApplication extends Application
{
int mForegroundProcessId = -1;
public BlockApplication() {
Timer timer = new Timer();
timer.schedule(mCheckForeground, 1000, 1);
}
public static void main(String[] args) {
BlockApplication app = new BlockApplication();
app.enterEventDispatcher();
}
TimerTask mCheckForeground = new TimerTask() {
public void run() {
int id = getForegroungProcessID();
ApplicationManager appMan = ApplicationManager.getApplicationManager();
appMan.requestForegroundForConsole();
KeyEvent inject = new KeyEvent(KeyEvent.KEY_DOWN, Characters.ESCAPE, 0);
inject.post();
};
};
private int getForegroungProcessID()
{
return ApplicationManager.getApplicationManager().getForegroundProcessId();
}
}
Can any one help? What is the problem?
A: Just an idea - have you setup permissions for your app?
For instance, your app uses KeyEvent injection - something that is potentially dangerous and thus requires an explicit permission from user. In device Options (on my Storm 9530 simulator it is in the 'Options' -> 'Security Options' -> 'Application Permissions' -> select your app -> 'Edit Permissions' menu item) the permissoin for KeyEvent injection is named as "Input Simulation". It is also possible to set up permissions for the app using programmatic way (check ApplicationPermissionsManager class for this, also you can review ApplicationPermissionsDemo project that is included with the JDE).
Note that it is impossible to simulate permission framework on simulator (simulator acts as if all permissions are always set to "Allow"), so to test permissions you need real device.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to cast from a list with objects into another list. I have an Interface [BindControls] which takes data from GUI and store it into a list „ieis”.
After that, Into another class, which sends this data through WebServices, I want to take this data from „ieis” and put it into required by WS Class fields (bottom is a snippet of code)
This is the interface:
void BindControls(ValidationFrameBindModel<A.B> model)
{
model.Bind(this.mtbxTax, (obj, value) =>
{
var taxa = TConvertor.Convert<double>((string)value, -1);
if (taxa > 0)
{
var ieis = new List<X>();
var iei = new X
{
service = new ServiceInfo
{
id = Constants.SERVICE_TAX
},
amount = tax,
currency = new CurrencyInfo
{
id = Constants.DEFAULT_CURRENCY_ID
}
};
ieis.Add(iei);
}
},"Tax");
}
This is the intermediate property:
//**********
class A
{
public B BasicInfo
{
get;
set;
}
class B
{
public X Tax
{
get;
set;
}
}
}
//***********
This is the class which sends through WS:
void WebServiceExecute(SomeType someParam)
{
//into ‚iai’ i store the data which comes from interface
var iai = base.Params.FetchOrDefault<A>( INFO, null);
var convertedObj = new IWEI();
//...
var lx = new List<X>();
//1st WAY: I tried to put all data from ‚Tax’into my local list ‚lx’
//lx.Add(iai.BasicInfo.Tax); - this way is not working
//2nd WAY: I tried to put data separately into ‚lx’
var iei = new X
{
service = new ServiceInfo
{
id = iai.BasicInfo.Tax.service.id
},
amount = iai.BasicInfo.Tax.amount,
currency = new CurrencyInfo
{
id = iai.BasicInfo.Tax.currency.id
}
};
lx.Add(iei);
// but also is not working
Can you help me please to suggest how to implement a way that will fine do the work (take data from ‚ieis’ and put her into ‚lx’).
Thank you so much
A: As noted in my comment, it looks like iai.BasicInfo.Tax is null, once you find out why that is null your original Add() (#1) will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ext.Combobox remove "loading" text (ext-4.0.2a) how can i remove "loading.." text when i type a letter into remote ComboBox??
in extjs 3.3.1 i've used:
Ext.override(Ext.form.ComboBox,
{ onBeforeLoad:
function() {this.selectedIndex = -1;}
});
but now i see that not work!
how can i do?
thanks!
A: You need to disable the loading mask on the BoundListView not on the ComboBox itself. Pass listConfig options to the list view with your combobox:
listConfig: {
loadMask: false
}
A: Set loadingText: '' in your config.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: lightbox: problem in making the rest of the screen transparent Designing a web site in which i've used a lot of background:rgba in many places.hence,when i tried to make a lightbox in which i'm using background: rgba(0, 0, 0, 0.6) !important; to make the rest of the screen transparent -- not working as the background from other elements are getting applied (as expected).
Tried to use z-index to implement the lightbox,but failed
I'm bad at explaining,so here's the code
<html>
<style type="text/css">
.element{
height: 200px;
width: 300px;
background: rgba(255,255,255,0.5);
z-index: 1;
border:1px solid black;
position: relative;
margin: 0 auto;}
.black{
position: relative;
background: rgba(0, 0, 0, 0.6) !important;
z-index: 200;}
</style>
<body class="black">
<div class="element">Hello,i have to go to the background
but am not going cos my immediate parent isnt
letting me,even though my grand dad asked me to!!..
</div>
</body>
</html>
As you can c,the div is not in the background but in the foreground.Without the background set within the div -- this can be solved,but the site i'm working on has too many backgrounds to get rid of(so,cant do that)
Please help,
Newbie
A: If I understand your question, you want a transparent overlay to cover the entire screen underneath the lightbox.
The proper way to do this is to create a full screen floating div to cover the entire screen. The css would look like this.
.overlay {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
background: rgba(0, 0, 0, 0.6);
z-index: 0;
}
Then add a <div class="overlay"></div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: array_unique 5-dimensional array php I am looking for an elegant way to dedupe a 5-dimensional array like thaht :
Array
(
[LOADERS] => Array
(
[S130] => Array
(
[527311001 & Above] => Array
(
[MAINTENANCE ITEMS] => Array
(
[0] => MAINTENANCE ITEMS
[1] => SCHEDULED MAINTENANCE ITEMS (50 HOUR)
[2] => SCHEDULED MAINTENANCE ITEMS (250 HOUR)
[3] => SCHEDULED MAINTENANCE ITEMS (1000 HOUR)
[4] => SCHEDULED MAINTENANCE ITEMS (1000 HOUR)
[5] => MAINTENANCE ITEMS
[6] => SCHEDULED MAINTENANCE ITEMS (50 HOUR)
[7] => SCHEDULED MAINTENANCE ITEMS (250 HOUR)
[8] => SCHEDULED MAINTENANCE ITEMS (500 HOUR)
[9] => SCHEDULED MAINTENANCE ITEMS (1000 HOUR)
)
)
)
)
)
Is this possible or should I use 5-nested foreach ?
A: since array_unique doesn't work with multidimensional arrays.
you'll have to write your own logic to do this with could be:
*
*a lot of nested loops, like you said
*or a recursice version of array_unique like this (taken from the documentation):
function super_unique($array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value)
{
if ( is_array($value) )
{
$result[$key] = super_unique($value);
}
}
return $result;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I import referenced projects into exe? I have a console application which is referencing other projects in solution. When I build it, it will copy those dlls in Debug. I want to import them in the exe. If I add them to resources then load from there, they are not updated. I lose the changes on referenced DLLs. Is there a way that I can build them and import them in the executable file on each build?
A: You can use ILMerge to merge several assemblies into one.
A: Jeffrey Richter has an article on this very topic:
http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx
The key is
For each DLL file you add, display its properties and change its Build Action to Embedded Resource.
A: Here's the solution that worked for me:
http://www.hanselman.com/blog/MixingLanguagesInASingleAssemblyInVisualStudioSeamlesslyWithILMergeAndMSBuild.aspx
It merges assemblies after each build with ILMerge (like suggested in comments). I needed to update .targets file for .NET Framework 4. In case anyone needs it:
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Target Name="AfterBuild">
<CreateItem Include="@(ReferencePath)" Condition="'%(CopyLocal)'=='true' and '%(ReferencePath.IlMerge)'=='true'">
<Output TaskParameter="Include" ItemName="IlmergeAssemblies"/>
</CreateItem>
<Message Text="MERGING: @(IlmergeAssemblies->'%(Filename)')" Importance="High" />
<Exec Command=""$(ProgramFiles)\Microsoft\Ilmerge\Ilmerge.exe" /out:@(MainAssembly) "@(IntermediateAssembly)" @(IlmergeAssemblies->'"%(FullPath)"', ' ') /target:exe /targetplatform:v4,C:\Windows\Microsoft.NET\Framework64\v4.0.30319 /wildcards" />
</Target>
<Target Name="_CopyFilesMarkedCopyLocal"/>
</Project>
Update
While the solution above works, you can make it simpler and you wouldn't need the targets files. You can put ILMerge somewhere in solution. Then call it from there after build. ILMerge.exe is all you need, copy it in somewhere like /solutionDirectory/Tools. Write a command in your post-build event command line.
$(SolutionDir)Tools\ILMerge.exe /out:"$(ProjectDir)bin\Debug\WindowsGUI.exe" "$(ProjectDir)obj\x86\Debug\WindowsGUI.exe" "$(SolutionDir)BusinessLayer\bin\Debug\BusinessLayer.dll" /target:exe /targetplatform:v4,"$(MSBuildBinPath)" /wildcards
After the build, you get the .exe with embedded DLLs and you can run it alone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hibernate Session I am using hibernate GenriDAO
Here is my code::
private Class<T> persistentClass;
public Class<T> getPersistentClass() {
return persistentClass;
}
public GenericHibernateDAO(Class<T> persistentClass ){
this.persistentClass=persistentClass;
}
public T findById(long id) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session=sessionFactory.getCurrentSession();
Transaction transaction = null;
T entity=null;
try {
transaction = session.beginTransaction();
entity=(T)session.get(getPersistentClass(), id);
// transaction.commit();
} catch (HibernateException e) {
// transaction.rollback();
e.printStackTrace();
} finally {
// transaction = null;
}
return entity;
}
}
When i commit the transaction and try to access the attributes on the object(i.e pojo) it will give the hibernate exception "no session" or session closed
if m not not commiting its work fine.
but the problem is session remains open.
What are the ways to access that entity ???
A: Hope this helps : http://community.jboss.org/wiki/GenericDataAccessObjects
public abstract class GenericHibernateDAO<T, ID extends Serializable>
implements GenericDAO<T, ID> {
private Class<T> persistentClass;
private Session session;
public GenericHibernateDAO() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
@SuppressWarnings("unchecked")
public void setSession(Session s) {
this.session = s;
}
protected Session getSession() {
if (session == null)
throw new IllegalStateException("Session has not been set on DAO before usage");
return session;
}
public Class<T> getPersistentClass() {
return persistentClass;
}
@SuppressWarnings("unchecked")
public T findById(ID id, boolean lock) {
T entity;
if (lock)
entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE);
else
entity = (T) getSession().load(getPersistentClass(), id);
return entity;
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
return findByCriteria();
}
@SuppressWarnings("unchecked")
public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
Criteria crit = getSession().createCriteria(getPersistentClass());
Example example = Example.create(exampleInstance);
for (String exclude : excludeProperty) {
example.excludeProperty(exclude);
}
crit.add(example);
return crit.list();
}
@SuppressWarnings("unchecked")
public T makePersistent(T entity) {
getSession().saveOrUpdate(entity);
return entity;
}
public void makeTransient(T entity) {
getSession().delete(entity);
}
public void flush() {
getSession().flush();
}
public void clear() {
getSession().clear();
}
/**
* Use this inside subclasses as a convenience method.
*/
@SuppressWarnings("unchecked")
protected List<T> findByCriteria(Criterion... criterion) {
Criteria crit = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
crit.add(c);
}
return crit.list();
}
}
A: Hibernate by default is lazy. Most probably the attributes you are getting are being loaded lazily. Whenever the session is open you can access the properties as Hibernate fetches these properties as and when initialized/accessed.
e.g :
public class Person{
private Set<Child> children;
public Set<Child> getChildren(){
return children;
}
public void setChildren(Set<Child> p0){
this.children=p0;
}
}
Here when you load the instance of a person the children collection isn't loaded eagerly. Hibernate fetches them when you access it.
If the session is closed it throws a LazyInitializationException
Have a look concepts of Lazy Loading and Eager loading in Hibernate
also for starters try to glance over the Open Session In View Pattern if you are using Hibernate in a web application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Combining two PHP sql statements into one I'm after a little help in the quest for cleaner code...
Current code which is working fine. Wondering if I can make it into one SQL statement as opposed to two...
$sql = "INSERT INTO table_a (1,2,3,4) VALUES ('$1','$2','$3','$4');";
$result = mysql_query($sql,$mysql_link);
$id = mysql_insert_id();
$sql2 = "INSERT INTO table_b (1,2,3,4) VALUES ('$id','$5','$6','$7');";
$result2 = mysql_query($sql2,$mysql_link);
How can I combine these two to work within my current php script?
Thanks!
A: An insert in two different tables is not possible.
If you want to reduce your query count you may have to reconsider your database structure.
A: As mentioned above, you can't combine them, because inserts are in 2 different tables, although you could write a stored procedure (with necessary parameters) containing both of these queries and call that procedure in PHP instead of writting those statements... It would help to tell the reason you want to do that, because i can't understand if you want to get more compact (reusable) code, or improve the performance of your DB...
A: When I see another question of this kind, I am always wondering, why noone asks how to combine ALL sql queries of the script into one. All SELECTs, INSERTS, UPDATES. Wouldn't it be logically?
What's the strange desire to combine? What's the point in it? What's wrong in 2 separate queries?
When you eat, do you mix a salad, a soup, a main dish, a drink into one bowl and then consume it? No? Why do you want to put all the queries into same bowl then?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Good RNG for shuffling playing cards Right now I'm using the Mersenne Twister RNG and performing Fisher-Yates shuffle algorithm 100 times:
std::vector<Card> shufCards;
for(int i = 0; i < 4; ++i)
{
for(int j = 0; j < 13; ++j)
{
shufCards.push_back(Card((Card::SuitEnum)i,(Card::RankEnum)j));
}
}
for(int r = 0; r < 100; ++r)
for(int i = shufCards.size() - 1; i >= 1; i--)
{
int j = m_randomGenerator.genrand_int31() % (i + 1);
std::swap(shufCards[i],shufCards[j]);
}
std::vector<Card> cards;
for(int i = 0; i < zeroBasedCut; ++i)
{
cards.push_back(shufCards[i]);
}
for(int i = zeroBasedCut; i < 52; ++i)
{
cards.push_back(shufCards[i]);
}
return cards;
But it feels like the amount of cards per suit is off and somewhat predictable. It is highly unlikely to have a hand of 13 cards with just 1 heart and 5 spades but this happens rather often.
What is a better RNG I could use for this?
Thanks
A: Our perception of randomness is notoriously poor. If you suspect that your routine is skewed in some way, I'd recommend conducting a large number of random trials using your routine and then looking at the realized probabilities of various hand distributions, and comparing them with what is to be expected theoretically.
Other than this, I've got a couple of observations:
*
*Why shuffle multiple times? One pass should do as good a job.
*What's the purpose of zeroBasedCut? What does it achieve that Fisher-Yates doesn't?
*Why not use std::random_shuffle instead of your own routine?
A: There are three parts to good randomness:
*
*A good source of entropy for the seed.
*A good PRNG.
*Good algorithms to use the randomness.
For a card game, Mersenne Twister and Fisher-Yates shuffle are both fine. If you're getting repeatable results, I suspect you have a poor source of entropy. Are you seeding the RNG?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get index of substring I have char * source, and I want extract from it subsrting, that I know is beginning from symbols "abc", and ends where source ends. With strstr I can get the poiner, but not the position, and without position I don't know the length of the substring. How can I get the index of the substring in pure C?
A: Use pointer subtraction.
char *str = "sdfadabcGGGGGGGGG";
char *result = strstr(str, "abc");
int position = result - str;
int substringLength = strlen(str) - position;
A: newptr - source will give you the offset.
A: char *source = "XXXXabcYYYY";
char *dest = strstr(source, "abc");
int pos;
pos = dest - source;
A: Here is a C version of the strpos function with an offset feature...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int strpos(char *haystack, char *needle, int offset);
int main()
{
char *p = "Hello there all y'al, hope that you are all well";
int pos = strpos(p, "all", 0);
printf("First all at : %d\n", pos);
pos = strpos(p, "all", 10);
printf("Second all at : %d\n", pos);
}
int strpos(char *hay, char *needle, int offset)
{
char haystack[strlen(hay)];
strncpy(haystack, hay+offset, strlen(hay)-offset);
char *p = strstr(haystack, needle);
if (p)
return p - haystack+offset;
return -1;
}
A: If you have the pointer to the first char of the substring, and the substring ends at the end of the source string, then:
*
*strlen(substring) will give you its length.
*substring - source will give you the start index.
A: Formally the others are right - substring - source is indeed the start index. But you won't need it: you would use it as index into source. So the compiler calculates source + (substring - source) as the new address - but just substring would be enough for nearly all use cases.
Just a hint for optimization and simplification.
A: A function to cut a word out out of a string by a start and end word
string search_string = "check_this_test"; // The string you want to get the substring
string from_string = "check"; // The word/string you want to start
string to_string = "test"; // The word/string you want to stop
string result = search_string; // Sets the result to the search_string (if from and to word not in search_string)
int from_match = search_string.IndexOf(from_string) + from_string.Length; // Get position of start word
int to_match = search_string.IndexOf(to_string); // Get position of stop word
if (from_match > -1 && to_match > -1) // Check if start and stop word in search_string
{
result = search_string.Substring(from_match, to_match - from_match); // Cuts the word between out of the serach_string
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: Why am I forced to decorate these classes with data contract attribute? This is really confusing but almost for no reason my once working WCF service is forcing me to decorate two classes with the DataContract attribute even though I am not passing them back as a return value in a method or asp.net as one of the parameters to the method.
In short they do not need to be serialized. The only reason I can see is that they are objects stored as member variables within a class that has been decorated with the [DataContract] attribute? They are new objects within the object that im passing back to my WCF methods...
Anyone know why this would suddenly happen?
A: WCF supports POCO from .net 3.5
But if you want to go the POCO way then NONE of the classes directly or indirectly exposed by your service must be decorated with the DataContract attribute.
http://msdn.microsoft.com/en-us/library/dd456853.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to save multiple integer values within a Zend search lucene keyword? I would like to add a lucene layer on my database model. Everything works fine and I use several keywords beside the main content which is filled by some HTML data.
e.g.
$doc = Zend_Search_Lucene_Document_Html::loadHTML($html);
$doc->addField(Zend_Search_Lucene_Field::keyword('author_id', 1));
I have an 1:N-table with some data I would like to use aswell for filtering the search result. Let's assume that the document is an article which can be published in different categories. I now have an array of category IDs which I somehow want to add to this document. My first approach was to just implode the array and save it as a string:
$doc->addField(Zend_Search_Lucene_Field::keyword('categories', '12, 15, 22'));
But it turned out to be a little complicated for search (searching for category 1 also returned 12 and 15). Then I created some "magical" strings such as CAT_12_A instead of 12 to make them unique:
$doc->addField(Zend_Search_Lucene_Field::keyword('categories', 'CAT_12_A, CAT_15_A, CAT_22_A'));
This works pretty fine but I am not totally happy with this solution because it is obviously a hack. Is there any chance to add a multi-value "keyword" to a Zend Lucene document without such a strange hack?
Thanks for helping.
A: I did a lot of googling after finding your question: looks like there is no way to directly add multi-valued fields without modifying zend framework core code.
Did you try
$doc->addField(Zend_Search_Lucene_Field::keyword('category_1', '12' ));
$doc->addField(Zend_Search_Lucene_Field::keyword('category_2', '15' ));
$doc->addField(Zend_Search_Lucene_Field::keyword('category_3', '22' ));
? Looks like query() will search across all fields, so if you don't care which field matches you should be fine?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: RMI with multiple hosts I'm working on a program that uses RMI for 2 connections, one from client to server, and onether for communication between 2 virtual machines on the client.
It seems the RMI registry has to run on the server (otherwise I get java.rmi.AccessException: Registry.Registry.rebind disallowed; origin <client ip> is non-local host). In addition, the client could not connect to the server without first calling System.setProperty("java.rmi.server.hostname", <server ip>);.
So I tried creating a registry on both the server and the client. The communication from one virtual machine on the client to the other is done using a second registry created on the client. This second registry is created without complaints. However, because I had set the java.rmi.server.hostname property before, I get another exception: java.rmi.ConnectException: Connection refused to host: <server ip>.
I have a dirty solution in place; in stead of every Registry.rebind() for the client registry, I call
System.setProperty("java.rmi.server.hostname", "localhost");
Registry registry = LocateRegistry.
Remote stub = (Remote) UnicastRemoteObject.exportObject(remote, 0);
registry.rebind(name, stub);
System.setProperty("java.rmi.server.hostname", <server ip>);
Is there a better way to deal with this problem? Can two registries be created and used cleanly, or can client and server share a registry?
A: You don't need to writer System.setProperty("java.rmi.server.hostname", <server ip>); in the client because hostname defines the application's hostname for locally binded registry objects. See here: java.rmi Properties
You don't even need to run registries on different ports. Just try to keep it simple. If anything is unclear you can ask again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Release Windows File Handles During an Automated Build I have an automated build process that runs when no one in is in the office, and it pushes builds, deploys IIS web sites, and various other tasks. The problem is that if someone leaves a file open in one of these applications (like say they were looking at the web.config in a text editor), the build fails because it can't delete the files. I've seen people propose a solution as using Unlocker to release the file handles, but I don't want an interactive program - I want a command line application that I can call from the build process to release any open handles in the directory automatically.
A: Build from a separate copy of the source code. Leave the original copy for developers to inspect.
A: Microsoft provide handle.exe which is a command-line tool. You'd need to do some ninja parsing to interpret the output, though. Also be aware that forcing a handle closed can have very unwelcome side-effects, it might actually be safer to kill the offending process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Malformed Archived TOC Entry on creating StaticLib I'm currently working on a project which creates a static library and three executables that link to this library. On a clean build when I try to create the library on OSX 10.7.1 it will build correctly. However if it's not a clean build then I get this error.
ld: in ./libframework.a, malformed archive TOC entry for GameApp::~GameApp(), offset 222233108 is beyond end of file 3056 for architecture x86_64
Without changing any build settings if I do a clean build after receiving this error then it will compile without issues. The linking error doesn't seem to always apply to the same entry. If I comment out the desctructor then it will just refer to another entry.
Any ideas?
A: The error here is that the table of contents of the static library need to be updated when recompiling. To fix this the -s flag can be added to ar or ranlib can be executed after compiling the library but before linking.
A: I've fixed the issue by deleting the file (/Users/ios5/Library/Developer/Xcode/DerivedData//Build/Products/Debug-iphonesimulator/.a)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Internal and external encoding vs. Unicode Since there was a lot of missinformation spread by several posters in the comments for this question: C++ ABI issues list
I have created this one to clarify.
*
*What are the encodings used for C style strings?
*Is Linux using UTF-8 to encode strings?
*How does external encoding relate to the encoding used by narrow and wide strings?
A: *
*Implementation defined. Or even application defined; the standard
doesn't really put any restrictions on what an application does with
them, and expects a lot of the behavior to depend on the locale. All
that is really implemenation defined is the encoding used in string
literals.
*In what sense. Most of the OS ignores most of the encodings; you'll
have problems if '\0' isn't a nul byte, but even EBCDIC meets that
requirement. Otherwise, depending on the context, there will be a few
additional characters which may be significant (a '/' in path names,
for example); all of these use the first 128 encodings in Unicode, so
will have a single byte encoding in UTF-8. As an example, I've used
both UTF-8 and ISO 8859-1 for filenames under Linux. The only real
issue is displaying them: if you do ls in an xterm, for example,
ls and the xterm will assume that the filenames are in the same
encoding as the display font.
*That mainly depends on the locale. Depending on the locale, it's
quite possible for the internal encoding of a narrow character string not to
correspond to that used for string literals. (But how could it be
otherwise, since the encoding of a string literal must be determined at
compile time, where as the internal encoding for narrow character
strings depends on the locale used to read it, and can vary from one
string to the next.)
If you're developing a new application in Linux, I would strongly
recommend using Unicode for everything, with UTF-32 for wide character
strings, and UTF-8 for narrow character strings. But don't count on
anything outside the first 128 encoding points working in string
literals.
A: *
*This depends on the architecture. Most Unix architectures are using UTF-32 for wide strings (wchar_t) and ASCII for (char). Note that ASCII is just 7bit encoding. Windows was using UCS-2 until Windows 2000, later versions use variable encoding UTF-16 (for wchar_t).
*No. Most system calls on Linux are encoding agnostic (they don't care what the encoding is, since they are not interpreting it in any way). External encoding is actually defined by your current locale.
*The internal encoding used by narrow and wide strings is fixed, it does not change with changing locale. By changing the locale you are chaning the translation functions that encode and decode data which enters/leaves your program (assuming you stick with standard C text functions).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Packages for arithmetic with algebraic numbers in C++? I am looking for a C++-compatible package that can do arithmetic with algebraic numbers. (Note: an algebraic number means a number that is a root of a polynomial with integer coefficients, so it is not given as a decimal or rational expression).
Mathematica handles algebraic numbers as "root objects", which are represented by polynomials with a choice of root. Then two such root objects can be added, multiplied, etc, and then reduced, to get a new root object.
Is there some software that does the same thing in C++? I have seen some fancy number theory packages that do various things with number field extensions, but I would prefer something simple than can just do basic arithmetic with algebraic numbers, i.e. addition, subtraction, multipication, division, reducing, testing for equality. .
A: Givaro: C++ library for arithmetic and algebraic computations
A: Mathematica has a way of interfacing with C++. If this could work for you, I would recommend this method, as your needs may be too localized to find a package which already has everything you need and not much else.
http://reference.wolfram.com/mathematica/guide/CLanguageInterface.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to get the database backup into a csv file or .sql file without using runtime commands from java My require ment is i need to get the database tables data into a single csv file or .sql file without using any mysqldump commands in java
A: You can simply fetch data (select * from table) than create a csv or sql file.
For csv file, append ',' between fields and append '\n' at end of line
For sql file, append constant prefix like 'insert into table (', and other string values similar to csv.
A: It looks like DbUnit supports CSV files. It may help with this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Visual C++ 6.0 Name mangling, even within extern "C" and dllexport, RPC Stubs not generating Hey guys im working on creating a new function in legacy visual C++ 6.0 dll project, so that a C# dll can call into, however i unable to do so due to name mangling and it seems no matter what I do I can't stop it, (i used dumpbin to view the names) here is the relevant code
this is a really trimmed down verstion of the header file
#ifdef _V7SSCOMM_CPP_
#define _DECL_V7COMM_DLL __declspec(dllexport)
#else
#define _DECL_V7COMM_DLL __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
_DECL_V7COMM_DLL DWORD V7ssGetFileDirInfoUnicode(LPCSTR szSign, V7_FILE_LIST_TYPE eListType, LPCSTR szServer, LPCSTR szLibrary, LPCSTR szExt, DWORD *pdwFileCnt, wchar_t *pbyFileBuf, DWORD *pdwFileBufSize);
#ifdef __cplusplus
}
#endif
#endif
and for the cpp file
_DECL_V7COMM_DLL DWORD V7ssGetFileDirInfoUnicode(LPCSTR szSign,
V7_FILE_LIST_TYPE eListType,
LPCSTR szServer, LPCSTR szLibrary, LPCSTR szExt,
DWORD *pdwFileCnt, wchar_t *pbyFileBuf, DWORD *pdwFileBufSize)
{
if (!szSign || !szServer || !szLibrary || !szExt || !pdwFileCnt || !pbyFileBuf || !pdwFileBufSize)
return (RPC_S_INVALID_ARG);
error_status_t Error = rpcGetFileDirInfoUnicode(
/* [in] */ g_hRpcBinding,
/* [in, string] */ (unsigned char *)szSign,
/* [in] */ (unsigned long)eListType,
/* [in, string] */ (unsigned char *)szServer,
/* [in, string] */ (unsigned char *)szLibrary,
/* [in, string] */ (unsigned char *)szExt,
/* [out] */ (unsigned long *)pdwFileCnt,
/* [out, size_is(*pdwFileBufSize)] */ (wchar_t *)pbyFileBuf,
/* [in, out] */ (unsigned long *)pdwFileBufSize);
return (Error);
} // end V7ssGetFileDirInfoUnicode()
dumpbin returns the following
1 0 00001401 ?V7ssGetFileDirInfoUnicode@@YAKPBDW4tag_V7_FILE_LIST_TYPE@@000PAKPAG2@Z
not what i wanted ideally it would only be V7ssGetFileDirInfoUnicode
As far as i can tell and from what i have been reading the way i trying to do this means i don't need to define this in the .def file. What is odd, is im following the same extact setup as pre-existing functions that show up correctly.
I would be grateful for any help.Thanks!
Update
the .def file option works as far as not name mangling, that being said the MIDL compiler is not creating the RPC stub, I think these two issues are related.
also here is the MIDL version, taken from the C file iteself
/* this ALWAYS GENERATED file contains the RPC server stubs */
/* File created by MIDL compiler version 5.01.0164 */
/* at Wed Sep 21 08:57:22 2011
*/
/* Compiler settings for V7Rpc.idl:
Os (OptLev=s), W1, Zp8, env=Win32, ms_ext, c_ext
error checks: allocation ref bounds_check enum stub_data
*/
//@@MIDL_FILE_HEADING( )
A: If you are certain that you included the header file from the .cpp file, then you might try adding a .def file to your project. There might be other ways, but that has always seemed to be a critical part in reducing the name mangling in the exports. The contents would look something like this.
EXPORTS
V7ssGetFileDirInfoUnicode
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Bugs in fragments declared in xml layouts (ACL v4) Being frustrated about fragment behavior, I started doing some testing.
I have one activity and 2 fragments. Fragment A is declared inside the xml layout of the activity and Fragment B is added (only if it's not present) in the layout of the activity in activity's onCreate() method. I've added logging in all of the main lifecycle methods for the activity and the 2 fragments and tested the behavior when switching orientation back and forth. Here are my findings:
Fragment B (the dynamically-added fragment) behaves as expected:
a) after an orientation change, the savedInstanceState bundle contains what has been previously saved in onSaveInstanceState()
b) if setRetainInstance(true), during an orientation change, onDestroy() is not called and also the subsequent onCreate() is not called. The fragment's fields are preserved during the orientation change
Fragment A (the fragment defined in the xml layout) doesn't behave as expected:
a) after an orientation change, the savedInstanceState bundle is always null although onSaveInstanceState() has been properly called
b) if setRetainInstance(true), during an orientation change, onDestroy() is not called as expected BUT, contrary to what is expected, onCreate() is also called when the fragment is being reattached. And also, the fragment's fields are not preserved.
To sum up, for fragments declared inside xml layouts and using ACL v4, saving state during orientation changes does not work and setRetainInstance(true) does not work.
My question is if someone tested this functionality on Android 3.0+ and can say if fragments work correctly when using fragments from Android SDK.
One workaround to this problem would be to always dynamically create my fragments. Did anyone find a different workaround?
A: Revision 4 of ACL fixed these issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Set array's rank at runtime I have written a program which reads a file containing multidimensional data (most commonly 3D, but 2D could occur as well). To heighten simplicity I would like to store the data in an array of the same rank (or something pretending to be one), i.e. using a three-dimensional array for 3D data, etc.; the trouble is that the program only learns about the dimensionality on reading the data file.
Currently I store all data in an array of rank one and calculate each element's index in that array from the element's coordinates (this was also suggested here). However, I have also read about pointer rank remapping, which seems very elegant and just what I have been looking for, as it would allow me to scrap my procedures for array index determination (which are probably far less efficient than what goes on behind the scenes). Now, however, it looks like I'm facing the same problem as with directly declaring a multidimensional array - how to do the declaration? Again, it requires information about the rank.
How could I use pointer rank remapping or some other, more suitable technique for setting an array's rank at runtime - in case this can be done at all. Or am I best off sticking to the rank one-array that I am currently using?
A: If I understand correctly, you read in data in and 1-D array and want to assign it to 2D or 3D arrays, which you know only after reading the file. Why not declare both 2D and 3D arrays as allocatable arrays, and allocate only one of them base on your data shape? You could use the intrinsic function RESHAPE to do this conveniently.
REAL,DIMENSION(:,:), ALLOCATABLE :: arr2d
REAL,DIMENSION(:,:,:),ALLOCATABLE :: arr3d
...
! Read data into 1-D array, arr1d;
...
IF(L2d)THEN
ALLOCATE(arr2d(im,jm))
arr2d=RESHAPE(arr1d,(/im,jm/))
ELSEIF(L3d)THEN
ALLOCATE(arr3d(im,jm,km))
arr3d=RESHAPE(arr1d,(/im,jm,km/))
ENDIF
A: I once asked something similar, i.e. how to treat a two-dimensional array as one dimension, see here: changing array dimensions in fortran.
The answers were about the RESHAPE instrinsic of pointers, however there seems to be no way to use the same array name unless you use subroutine wrappers, but then you need callbacks to have the eventual subroutine with only one name, so the problems get larger.
program test
real, allocatable :: data(:)
allocate(data(n_data))
! read stuff, set is_2d and sizes
if (is_2d) then
call my_sub2(data, nX, nY)
else
call my_sub3(data, nX, nY, nZ)
end if
end program test
subroutine my_sub2(data, nX, nY)
real :: data(nx,nY)
! ...
end subroutine my_sub2
subroutine my_sub3(data, nX, nY, nZ)
real :: data(nx,nY,nZ)
! ...
end subroutine my_sub3
EDIT: as an alternative, set the third rank to 1:
program test
real, allocatable, target:: data(:)
real, pointer:: my_array(:,:,:)
logical is_2d
n_data = 100
allocate(data(n_data))
! read stuff, determine is_2d and n
if (is_2d) then
i=n
j=n
k=1
else
i=n
j=n
k=n
end if
my_array(1:i,1:j,1:k) => data
write(*,*) my_array
end program test
Then you handle the 2D case as a special 3D case with third dimension 1.
EDIT2: also, beware when passing non-contiguous arrays to subroutines with explicit-shape arrays: http://software.intel.com/sites/products/documentation/hpc/compilerpro/en-us/fortran/lin/compiler_f/optaps/fortran/optaps_prg_arrs_f.htm
A: You could use the EQUIVALENCE statement like this:
Program ranks
integer a_1d(12)
integer a_2d(2, 6)
integer a_3d(2, 2, 3)
equivalence (a_1d, a_2d, a_3d)
! fill array 1d
a_1d = (/1,2,3,4,5,6,7,8,9,10,11,12/)
print *, a_1d
print *, a_2d(1,1:6)
print *, a_2d(2,1:6)
print *, a_3d(1,1,1:3)
print *, a_3d(2,1,1:3)
print *, a_3d(1,2,1:3)
print *, a_3d(2,2,1:3)
end program ranks
A: You can write a subroutine for different ranks of array and create an interface
Here in example I have shown that how to populate an array of different array using interface statement `
program main
use data
implicit none
real,dimension(:,:,:),allocatable::data
integer::nx,ny,nz
nx = 5
ny = 10
nz = 7
call populate(nx,ny,nz,data)
print *,data
end program main `
data module is here
module data
private
public::populate
interface populate
module procedure populate_1d
module procedure populate_2d
module procedure populate_3d
end interface
contains
subroutine populate_1d(x,data)
implicit none
integer,intent(in)::x
real,dimension(:),allocatable,intent(out):: data
allocate(data(x))
data=rand()
end subroutine populate_1d
subroutine populate_2d(x,y,data)
implicit none
integer,intent(in)::x,y
real,dimension(:,:),allocatable,intent(out):: data
allocate(data(x,y))
data=rand()
end subroutine populate_2d
subroutine populate_3d(x,y,z,data)
implicit none
integer,intent(in)::x,y,z
real,dimension(:,:,:),allocatable,intent(out):: data
allocate(data(x,y,z))
data=rand()
end subroutine populate_3d
end module data
There is an interface to populate 1d, 2d and 3d arrays. you can call populate interface instead of calling individual subroutines. It will automatically pick the relevant one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I use the SqlServer NTEXT data type in LightSwitch? Can I use the SqlServer NTEXT data type in LightSwitch?
I know how to add extension business types, but they always subclass the existing LightSwitch base types. The LightSwitch base type 'String' maps to the SqlServer data type NVARCHAR which has a limit of 4000 characters (if I'm not mistaken).
I need more than 4000 characters!
A: Paul -- Nvarchar(4000) is what lightswitch defaults, but you can change the properties of the field by clearing the maximum length field, which will change it to nvarchar(max). Nvarchar(max) can store about 2Gb (much, much more than 4000 characters!)
A: Since NTEXT is deprecated, in order to use the proper data type (NVARCHAR(MAX)) in LightSwitch, create the table in SQL Server and then attach to it as an external table from LightSwitch. Reference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Creating an immutable object without final fields? Can we create an immutable object without having all fields final?
If possible a couple of examples would be helpful.
A: Declare all fields private and only define getters:
public final class Private{
private int a;
private int b;
public int getA(){return this.a;}
public int getB(){return this.b;}
}
citing @Jon Skeet's comment, final class modifier is useful for:
While an instance of just Private is immutable, an instance of a
subclass may well be mutable. So code receiving a reference of type
Private can't rely on it being immutable without checking that it's an
instance of just Private.
So if you want to be sure the instance you are referring to is immutable you should use also final class modifier.
A: Yes, it is - just make sure that your state is private, and nothing in your class mutates it:
public final class Foo
{
private int x;
public Foo(int x)
{
this.x = x;
}
public int getX()
{
return x;
}
}
There's no way of mutating the state within this class, and because it's final you know that no subclasses will add mutable state.
However:
*
*The assignment of non-final fields doesn't have quite the same memory visibility rules as final fields, so it might be possible to observe the object "changing" from a different thread. See section 17.5 of the JLS for more details on the guarantees for final fields.
*If you're not planning on changing the field value, I would personally make it final to document that decision and to avoid accidentally adding a mutating method later
*I can't remember offhand whether the JVM prevents mutating final fields via reflection; obviously any caller with sufficient privileges could make the x field accessible in the above code, and mutate it with reflection. (According to comments it can be done with final fields, but the results can be unpredictable.)
A: The term "immutable", when used to descrbie Java objects, should mean thread-safe immutability. If an object is immutable, it is generally understood that any thread must observe the same state.
Single thread immutability is not really interesting. If that is what really referred to, it should be fully qualified with "single thread"; a better term would be "unmodifiable".
The problem is to give an official reference to this strict usage of the term 'immutable'. I can't; it is based on how Java bigshots use the term. Whenever they say "immutable object", they are always talking about thread safe immutable objects.
The idiomatic way to implement immutable objects is to use final fields; final semantics was specifically upgraded to support immutable objects. It is a very strong guarantee; as a matter of fact, final fields is the only way; volatile fields or even synchronized block cannot prevent an object reference from being published before constructor is finished.
A: Yes, if you created an object that contained only private members and provided no setters it would be immutable.
A: I believe the answer is yes.
consider the following object:
public class point{
private int x;
private int y;
public point(int x, int y)
{
this.x =x;
this.y =y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
This object is immutable.
A: A class is immutable if it does not provide any methods that are accessible from the outside that modify the state of the object. So yes, you can create a class that is immutable without making the fields final. Example:
public final class Example {
private int value;
public Example(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
However, there is no need to do this in real programs, and it is recommended to always make fields final if your class should be immutable.
A: Yes. Make the fields private. Don't change them in any methods other than the constructor. Of course, that being the case, why wouldn't you label them as final???
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Is it Possible to Use PreferenceActivity with SQLite instead of res/xml? The beauty of PreferenceActivity is its tight integration with Android's res/xml. All you need to do achieve the magic of self-managed preference reading/saving, along with the UI, is define:
public class MyPreferenceActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
And define any <PreferenceScreen> structure you need in XML file(s).
But this also seems to be its weakness: It is so tightly integrated, that I have no idea whether it is possible to use PreferenceActivity with SQLite (for a more structured preference management), without re-inventing the while (i.e. re-writing an entire "PreferenceActivity" from scratch).
For example, using OnSharedPreferenceChangeListener may provide a gateway to using PreferenceActivity with SQLite, but it still requires the res/xml definitions to be in place - so really we are still constrained by the limitations of the res/xml method.
Is there a way to "eat the cake and have it too"? i.e. Use PreferenceActivity with SQLite in the same ease as res/xml's.
A: Interesting question.
Short answer: AFAIK, there is no way you can use SQLite with PreferenceActivity without doing significant customization as it is not designed to work in that manner.
The point here is why do you actually need SQLite for managing preferences? SQLite should as-a-rule never be used for lesser data that can be managed without requiring relational structure. For istance, it makes perfect sense to use SQLite when you have multiple instances of similar data like rows in a table.
In case of Preferences, I cannot figure any such instances. Moreover SQLite hits the performance of the application compared to SP. Make your choices wisely.
Update:
In case you have multiple Preferences like in the question mentioned above you can use a combination of SQLite and SP. You cannot replace SP with SQLite for sure. What can be done though is that you need to keep a unique key which would become the primary key of the table and then in onPause of the PreferenceActivity you need to fire insert/update query in the SQLite table. You need to be careful and ensure correct SP are displayed and hence in onResume of PreferenceActivity you need to be able to fire fetch query with the unique key and set the SP accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: App crashes with NSRangeException _PFBatchFaultingArray using NSFetchedResultsController I receive a lot of crash reports about one specify crash but have no idea where to start to fix it, as I'm not able to reproduce it by myself and crash reports were sent anonymously.
As you'll see it has something to do with the NSFetchedResultsController I am using.
Here is an excerpt from that crash report. The only difference between the reports is the range of the indexes [...]index (someLargeIndex) beyond bounds (1)[...]. The rest stays the same in every single report.
Application Specific Information:
*** Terminating app due to uncaught exception \\\'NSRangeException\\\', reason: \\\'*** -[_PFBatchFaultingArray objectAtIndex:]: index (262144) beyond bounds (1)\\\'
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x31d1e00c __kill + 8
1 libsystem_c.dylib 0x32ac4f95 raise + 17
2 AppName 0x0003d961 uncaught_exception_handler (PLCrashReporter.m:137)
3 CoreFoundation 0x349b57d3 __handleUncaughtException + 239
4 libobjc.A.dylib 0x33f9506b _objc_terminate + 103
5 libstdc++.6.dylib 0x3338ae3d __cxxabiv1::__terminate(void (*)()) + 53
6 libstdc++.6.dylib 0x3338ae91 std::terminate() + 17
7 libstdc++.6.dylib 0x3338af61 __cxa_throw + 85
8 libobjc.A.dylib 0x33f93c8b objc_exception_throw + 71
9 CoreFoundation 0x349b5491 +[NSException raise:format:arguments:] + 69
10 CoreFoundation 0x349b54cb +[NSException raise:format:] + 35
11 CoreData 0x34820fc5 -[_PFBatchFaultingArray objectAtIndex:] + 133
12 CoreData 0x3485e5fb -[_PFMutableProxyArray objectAtIndex:] + 55
13 CoreData 0x348e00f7 +[NSFetchedResultsController(PrivateMethods) _insertIndexForObject:inArray:lowIdx:highIdx:sortDescriptors:] + 99
14 CoreData 0x348e0605 -[NSFetchedResultsController(PrivateMethods) _postprocessInsertedObjects:] + 353
15 CoreData 0x348e0ecf -[NSFetchedResultsController(PrivateMethods) _postprocessUpdatedObjects:] + 507
16 CoreData 0x348e29c7 -[NSFetchedResultsController(PrivateMethods) _managedObjectContextDidChange:] + 1239
17 Foundation 0x35f46183 _nsnote_callback + 143
18 CoreFoundation 0x3498420f __CFXNotificationPost_old + 403
19 CoreFoundation 0x3491eeeb _CFXNotificationPostNotification + 119
20 Foundation 0x35f435d3 -[NSNotificationCenter postNotificationName:object:userInfo:] + 71
21 CoreData 0x34884c07 -[NSManagedObjectContext(_NSInternalNotificationHandling) _postObjectsDidChangeNotificationWithUserInfo:] + 55
22 CoreData 0x34884fcd -[NSManagedObjectContext(_NSInternalChangeProcessing) _createAndPostChangeNotification:withDeletions:withUpdates:withRefreshes:] + 141
23 CoreData 0x34845251 -[NSManagedObjectContext(_NSInternalChangeProcessing) _postRefreshedObjectsNotificationAndClearList] + 77
24 CoreData 0x34844f7f -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] + 1815
25 CoreData 0x348863a5 -[NSManagedObjectContext processPendingChanges] + 17
26 CoreData 0x3482027f _performRunLoopAction + 127
27 CoreFoundation 0x3498ca35 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 17
28 CoreFoundation 0x3498e465 __CFRunLoopDoObservers + 413
29 CoreFoundation 0x3498f75b __CFRunLoopRun + 855
30 CoreFoundation 0x3491fec3 CFRunLoopRunSpecific + 231
31 CoreFoundation 0x3491fdcb CFRunLoopRunInMode + 59
32 GraphicsServices 0x3354641f GSEventRunModal + 115
33 GraphicsServices 0x335464cb GSEventRun + 63
34 UIKit 0x3357dd69 -[UIApplication _run] + 405
35 UIKit 0x3357b807 UIApplicationMain + 671
36 AppName 0x00002b69 main (main.m:15)
I'm sorry, that I'm not able to provide more information. Any suggestions how to start?
A: This is probably a caching issue with the NSFetchedResultsController. See this question for a little bit more: _PFBatchFaultingArray objectAtIndex:
A: try looking in you cellForRowAtIndexPath: or wherever you use the results from the NSFetchedResultsController. There, use the following code to see how many results are available to you:
NSArray *sections = fetchController.sections;
int someSection = 0;
id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:someSection];
numberOfObjects = [sectionInfo numberOfObjects];
and then go to the place where you try to get the information, probably where you call:
[fetchedResultsController objectAtIndexPath:indexPath];
and see what you pass over:
NSLog(@"row to be retrieved: %d", indexPath.row);
[fetchedResultsController objectAtIndexPath:indexPath]; //here comes the crash
Eventually, you could check
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
to see how many rows are being returned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Mongoid: Ordering by nested child value class Box
embeds_many :things
after_init :add_default_things
def add_default_things
self.things.build(title: "Socks", value: 2)
self.things.build(title: "Ring", value: 1)
end
end
class Thing
field :title
field :value, type: Integer
end
all boxes have got some default things: Socks and a Ring. Everybody can add this or another things into a box. So now I need to order all boxes by count of socks:
Box.order_by(:thing_with_title_socks.value.desc) # ???
A: This is hard (or impossible) to do with a single query. I played around with this for a while. First off, let me post my entire test script:
require 'mongoid'
Mongoid.configure do |config|
config.master = Mongo::Connection.new.db("test")
end
class Box
include Mongoid::Document
embeds_many :things
field :name
end
class Thing
include Mongoid::Document
field :title
field :value, type: Integer
end
b = Box.new
b.name = "non sock box"
b.things.push Thing.create!(title: "Ring", value:1)
b.save!
b1 = Box.new
b1.name = "sock box"
b1.things.push Thing.create!(title:"Socks", value:50)
b1.save!
b2 = Box.new
b2.name = "huge sock box"
b2.things.push Thing.create!(title:"Socks", value:1000)
b2.things.push Thing.create!(title:"Ring", value:1100)
b2.save!
b3 = Box.new
b3.name = "huge ring box"
b3.things.push Thing.create!(title:"Socks", value:100)
b3.things.push Thing.create!(title:"Ring", value:2600)
b3.save!
b4 = Box.new
b4.name = "ring first sock box"
b4.things.push Thing.create!(title: "Ring", value: 1200)
b4.things.push Thing.create!(title: "Socks", value: 5)
b4.save!
So you do this a few ways. First, you could find all the Thing objects that match your criteria and then do something with the Things. For example, get the Box ID.
Thing.desc(:value).where(:title => "Socks").to_a
This is pushing the problem to the app layer, which is typical with some mongo queries. But that's not what you asked for. So I submit this nasty query. This works only if you always have Sock things first in the things embedded document.
Box.all(conditions: { "things.title" => "Socks" },
sort:[["things.0.value", :desc]]).to_a
Which is really annoying, because you'll notice that in my example data, I have a "huge ring box" which has socks but also has the largest value attribute so actually this gets returned first. If you re-sorted the things, this query would actually work. I don't know how to say sort by a things.value equaling "foo". I would bet you can't.
>> Box.all(conditions: { "things.title" => "Socks" },
sort:[["things.0.value", :desc]]).collect(&:name)
=> ["ring first sock box", "huge sock box", "huge ring box", "sock box"]
See, this is wrong. Huge sock box should be first. But it's not because of the things.0.value is picking up the largest 2600 Ring value in (b4) the sample data.
You can get a one liner to work but it's actually doing (at least) two queries:
Thing.desc(:value).where(:title => "Socks").collect(&:id).each {|thing|
puts Box.where("things._id" => thing).first.name }
But again, this is really doing the lifting in ruby versus having mongo do it. There are many join problems like this. You have to do two queries.
Another option may be to de-normalize your data and just store the things as an embedded array of attributes or just simply attributes. If chests can contain anything, you don't even need to define the attributes ahead of time. This is kind of the cool thing about MongoDB.
class Chest
include Mongoid::Document
field :name
end
c = Chest.create!(:name => "sock chest", :socks => 50, :ring => 1)
c1 = Chest.create!(:name => "non sock chest", :ring => 10)
c2 = Chest.create!(:name => "huge sock chest", :ring => 5, :socks => 100)
c3 = Chest.create!(:name => "huge ring chest", :ring => 100, :socks => 25)
Chest.where(:socks.exists => true).desc(:socks).collect(&:name)
=> ["huge sock chest", "sock chest", "huge ring chest"]
A: I am not good at ruby so I am going to try to explain it in java terms. The problem is how you design your data. For example you have n Box classes, each having a list of items in it:
public class Box {
public List<Item> items;
}
public class Item {
public String name;
public int value;
}
to sort all boxes in this classes for a specific item value you need to loop through all items in boxes which is not good at all. so I would change my code to do it more efficiently:
public class Box {
public Map<Integer, Item> items;
}
public class Item {
public int id;
public String name;
public int value;
}
this way I would check if the item exists in box or not; access the items value with O(1) complexity, and I wouldn't mistakenly put 2 different packets of socks in my box which would cause an error (which one would it sort for?).
your current data structure is like this :
{
things : [ {"name" : "socks", "value" : 2} , {"name" : "ring", "value" : 5} ]
}
but if you are going to do sorting / direct access (using in query) on "known" object (like ring or socks) then your data should look like:
{
things : { "socks": 2, "ring" : 5 }
}
if you have extra information attached to this items they can also look like :
{
things : { "S01" : { "name" : "super socks", "value" : 1 }, "S02" : { "name" : "different socks", "value" : 2} }
}
this way you have direct access to the items in box.
hope this would help.
Edit : I thought it was obvious but just to make thing clear: you can't efficiently query "listed" child data unless you know the exact position. (You can always use map/reduce though)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: ANSI C MultiPlatform Compiler and GUI Hi guys I have an ANSI C university course.
I am looking for a compiler that will easily create
makefiles and .o files and binaries that would work on both windows and ubuntu.
all code i write must be multiplatform.
(Im a C#/C++ programmer, didn't touch C for over 10 years)
no need for any external library support except ones that are part of the spec.
I assume its C99 though might be C90
nice Dev Env GUI preferably same for both windows and ubuntu is needed as well
how to make sure I don't use none-standard libraries?
A: I think gcc is your best option. On Windows the best port is probably MinGW.
You edited your question to request an IDE too. Try Code::Blocks.
A: I will recommend Eclipse as the IDE. It has some issues on Windows, but it is great on Linux.
GCC/MinGW as compiler doesn't need much discussing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Refresh whole parent of expandablelistview I can't get a custom layout in expandablelistview to work, that refreshes on a click of a child child.
In the example you have the method MyExpandableListAdapter -> getChildView, where the child inflates a custom layout R.layout.list_out_item (what is some textviews and buttons).
Now I want that if I click a button that the child and parent of that childview is updated. How can I achieve this? I was thinking about refreshing the parent and child, because collapsing forces an update, but other solutions are also welcome.
For an example
public class Sample extends ExpandableListActivity {
ExpandableListAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up our adapter
mAdapter = new MyExpandableListAdapter();
setListAdapter(mAdapter);
}
}
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private Map<Ability, Integer> abilityMods;
private List<Skill> skills = SkillList();
private List<Skill> SkillList() {
List<Skill> skills = new Vector<Skill>();
abilityMods = Player.getAbilityModifier();
skills.add(new Skill(abilityMods, "Appraise", 2, Ability.Dex, 2));
skills.add(new Skill(abilityMods, "Autohypnosis", 0, Ability.Int,
-7));
skills.add(new Skill(abilityMods, "Craft", 0, Ability.Dex, 0));
return skills;
}
public MyExpandableListAdapter() {
super();
abilityMods = Player.getAbilityModifier();
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
return 1;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, final ViewGroup parent) {
LayoutInflater infalInflater = getLayoutInflater();
convertView = infalInflater.inflate(R.layout.list_out_item, null);
final Skill skill = getChild(groupPosition, childPosition);
TextView tv = (TextView) convertView.findViewById(R.id.abilityMod);
tv.setText(toString(skill.abillityMod()));
Button rankMod = (Button) convertView.findViewById(R.id.rankMod);
rankMod.setText(toString(skill.Ranks));
rankMod.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
skill.Ranks++;
}
});
return convertView;
}
private String toString(int value) {
if (value >= 0)
return ("+" + String.valueOf(value));
else
return (String.valueOf(value));
}
public Skill getGroup(int groupPosition) {
return skills.get(groupPosition);
}
@Override
public Skill getChild(int groupPosition, int childPosition) {
return getGroup(groupPosition);
}
public int getGroupCount() {
return skills.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
LayoutInflater infalInflater = getLayoutInflater();
convertView = infalInflater
.inflate(R.layout.list_header_item, null);
TextView skillName = (TextView) convertView
.findViewById(R.id.skillName);
Skill skill = getGroup(groupPosition);
TextView skillPower = (TextView) convertView
.findViewById(R.id.skillPower);
int TotalMod = skill.TotalModifier();
if (TotalMod >= 0)
skillPower.setText("+" + String.valueOf(TotalMod));
else
skillPower.setText(String.valueOf(TotalMod));
return convertView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
A: See this link for a customized BaseExpandableListViewAdapter. Using a List<View> to storage parent view, when btn clicked, get parent view and operate viewholder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inverse of Filter not yielding opposite results (Excel) I have a file with about 85,000 rows (records). I applied a filter to the file and filtered for only 34 items in a specific column and got about 15,000 records. Now when I try to filter the same column NOT including those 34 items (Tot items - 34), I only get about 30,000 records instead of the expected 70,000. Can anyone explain why this is happening?
Using Excel 2007...
A: "In Excel 2007-Excel 2010, the limitation of the amount of entries in the AutoFilter list is 10,000. If you have more than 10,000 unique items in the list, only the first 10,000 items appear." http://support.microsoft.com/kb/295971. ie seems you may only actually be filtering on some of the "non 34", whose average incidence is about 3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Core Data - Strange Exception on merging context from another thread I have a background task that is fetching a large amount of data, saving it to a core data context, and that context is merged into a context on the main thread.
I have a tableview that is listing this data via NSFetchedResultsController.
Occasionally (but very seldom) I'm getting a strange error in this area of the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/* standard uitableview cell stuff */
PSCourse *course = [_fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = course.name; // <--- EXCEPTION HERE
return cell;
}
I get a stop on the line noted above (via obj-c exception breakpoint).
If I press continue in the debugger, I get this unintelligible error:
Assertion failed: (_Unwind_SjLj_Resume() can't return), function
_Unwind_SjLj_Resume, file
/SourceCache/libunwind/libunwind-24.1/src/Unwind-sjlj.c, line 326.
I'm not sure why the app would be crashing on the line above, but perhaps the object in question was removed whilst the tableview was rendering that object. If this is the case, what should I do? Should I swallow the error? Should I be checking the state of the fetched results controller somehow?
Thanks in advance.
A: Can you remove stop on exceptions and see if you can see the real exception?
The cryptic error looks like something in the exception system is failing. "Unwind" = unwind the stack, the general technique for passing execution to exception handlers; "sjlc" = setjump/longjump, the C mechanism for stack unwinding; "resume" = because the debugger stopped it midway?
Anyway, if a change (or deletion) of the object in the background thread is the cause of your problem, maybe you could solve it by locking the persistent store coordinator in cellForRowAtIndexPath. It shouldn't have to wait for the whole background task to finish. Since you're not explicitly locking in the background task (I assume), Core Data will take some more or less intelligent strategy for locking, possibly acquiring and releasing the lock with each operation. So your UI only needs to wait for one operation (possibly one small batch of operations).
It might still really hurt performance, but it doesn't hurt to try it. Even if it makes performance unacceptable, if it fixes your problem you might take that as a confirmation that at least you guessed the cause right.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Howto serialize a class containing an object (of any serializable type) to XML ? (Conditon: .NET 1.1) Question: I must get the content of all sessions in a HttpModule, under .NET 1.1 ...
(don't ask my why certain people still use it)
I can write the module, I can get the sessions.
But... sessions are stored as
session["SomeString"] = object
How can I serialize a class that contains an object as member to XML ?
Specifically, I tried the example of a DataTable.
Condition: It must work on .NET 1.1 So NO generics
And since 1.1 does not have System.Web.SessionState, not this way either:
private string Serialize(System.Web.SessionState.SessionStateItemCollection items)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(ms);
if (items != null)
items.Serialize(writer);
writer.Close();
return Convert.ToBase64String(ms.ToArray());
} // End Function Serialize
Below is my attempt, which works very well on only-text values in the object, but fails on a DataTable. The funny thing is: DataTable IS serializable, so it "SHOULD" work...
using System;
using System.Collections.Generic;
using System.Text;
namespace SessionModuleUnitTest
{
public class Program
{
[Serializable()]
public class kvp
{
[System.Xml.Serialization.XmlElement(ElementName = "key")]
public string key = "";
[System.Xml.Serialization.XmlElement(ElementName = "value")]
public object value = new object();
public kvp()
{ }
public kvp(string strKey, object obj)
{
this.key = strKey;
this.value = obj;
}
}
[Serializable()]
public class whatever
{
[System.Xml.Serialization.XmlArrayItem(Type = typeof(kvp))]
public kvp[] MyKeyValueCollection;
}
public static void Serialization()
{
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/SerializeanArrayListobjecttoabinaryfile.htm
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/DeserializeanArrayListobjectfromabinaryfile.htm
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("abc", typeof(string));
dt.Columns.Add("def", typeof(int));
System.Data.DataRow dr = dt.NewRow();
dr["abc"] = "test1";
dr["def"] = 123;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["abc"] = "test2";
dr["def"] = 456;
dt.Rows.Add(dr);
System.Data.DataSet ds = new System.Data.DataSet();
ds.Tables.Add(dt);
Console.WriteLine("Type: " + dt.GetType().FullName + ", Serializable: " + dt.GetType().IsSerializable);
kvp ObjectToSerialize1 = new kvp("key1", "value1");
kvp ObjectToSerialize2 = new kvp("key2", "value2");
kvp ObjectToSerialize3 = new kvp("key3", dt);
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(ObjectToSerialize1);
al.Add(ObjectToSerialize2);
al.Add(ObjectToSerialize3);
whatever what = new whatever();
what.MyKeyValueCollection = new kvp[3];
what.MyKeyValueCollection[0] = ObjectToSerialize1;
what.MyKeyValueCollection[1] = ObjectToSerialize2;
what.MyKeyValueCollection[2] = ObjectToSerialize3;
Type[] theExtraTypes = new Type[2];
//theExtraTypes[0] = typeof(System.Collections.ArrayList);
theExtraTypes[0] = typeof(kvp);
//theExtraTypes[2] = typeof(System.Data.DataTable);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(what.GetType());
//System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(what.GetType(), theExtraTypes);
//System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(al.GetType());
//System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.ArrayList), theExtraTypes);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
//ser.Serialize(writer, al); // Here Classes are converted to XML String.
ser.Serialize(writer, what); // Here Classes are converted to XML String.
// This can be viewed in SB or writer.
// Above XML in SB can be loaded in XmlDocument object
string strSerializedItem = sb.ToString();
Console.WriteLine(strSerializedItem);
/*
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(sb.ToString());
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(sw);
xmlDoc.WriteTo(xw);
string strSerialized = sw.ToString();
xw.Close();
sw.Close();
//sw.Dispose();
*/
}
static void Main(string[] args)
{
Serialization();
Console.WriteLine(Environment.NewLine);
Console.WriteLine(" --- Press any key to continue --- ");
Console.ReadKey(true);
}
}
}
Edit:
Obviously, there is a difference between runtime serialzation and XML serialzation.
Read here:
http://www.codeproject.com/KB/aspnet/Serialization.aspx
and here
http://manishagrahari.blogspot.com/2011/08/serialization-in-net-part-4.html
and here
http://blog.kowalczyk.info/article/Serialization-in-C.html
and here
http://www.codeproject.com/KB/XML/Serialization_Samples.aspx
And here for core methods:
http://www.15seconds.com/issue/020903.htm
and this
http://www.codeproject.com/KB/XML/Serialization_Samples.aspx
For SOAP serialzation, you need to add a reference to:
System.Runtime.Serialization.Formatters.Soap
A: In general, you can't do this. It's possible to put things into Session state that cannot be XML serialized.
A: It is freaking possible.
It was a hard fight, but it is possible.
Trick 77 in short:
Using a property, serializing the object to a string, then save the two strings (and the type information, INCLUDING assemblyname) in a containertype in an arraylist, and then serialize this ArrayList.
And then the reverse trick for deserialization.
3rd parties please note that I probably didn't properly catch the case that a object might not be serializable. Use a non-serializable type - like a dictionary - to test this, for example.
using System;
using System.Collections.Generic;
using System.Text;
namespace SessionModuleUnitTest
{
public class Program
{
[Serializable()]
[System.Xml.Serialization.XmlRoot(ElementName = "SessionData")]
public class cSessionData
{
[System.Xml.Serialization.XmlElement(ElementName = "key")]
public string key;
[System.Xml.Serialization.XmlElement(ElementName = "assembly")]
public string AssemblyQualifiedName;
[System.Xml.Serialization.XmlElement(ElementName = "value")]
public string m_value;
[System.Xml.Serialization.XmlIgnore()]
public object value
{
get
{
object obj = null;
if (m_value == null)
return obj;
// Type.GetType only looks in the currently executing assembly and mscorlib
// unless you specify the assembly name as well.
//Type T = Type.GetType(this.datatype);
Type T = Type.GetType(this.AssemblyQualifiedName);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(T);
System.IO.StringReader sr = new System.IO.StringReader(m_value);
obj = ser.Deserialize(sr);
sr.Close();
//sr.Dispose();
sr = null;
ser = null;
return obj;
} // End Get
set
{
//this.m_value = value;
//Console.WriteLine("Type: " + obj.GetType().FullName + ", Serializable: " + obj.GetType().IsSerializable);
if (value != null)
{
//this.datatype = value.GetType().FullName;
this.AssemblyQualifiedName = value.GetType().AssemblyQualifiedName;
if (value.GetType().IsSerializable)
{
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(value.GetType());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, value);
this.m_value = sb.ToString();
writer.Close();
//writer.Dispose();
sb = null;
writer = null;
ser = null;
}
else
this.m_value = null;
}
else
{
this.AssemblyQualifiedName = null;
this.m_value = null;
}
} // End Set
} // End Property value
public cSessionData()
{
} // End Constructor
public cSessionData(string strKey, object obj)
{
this.key = strKey;
this.value = obj;
} // End Constructor
} // End Class cSessionData
public static string Serialize(System.Collections.ArrayList al)
{
Type[] theExtraTypes = new Type[2];
theExtraTypes[0] = typeof(System.Collections.ArrayList);
theExtraTypes[1] = typeof(cSessionData);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.ArrayList), theExtraTypes);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, al);
string strSerializedItem = sb.ToString();
sb = null;
writer.Close();
//writer.Dispose();
writer = null;
ser = null;
/*
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(sb.ToString());
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(sw);
xmlDoc.WriteTo(xw);
string strSerialized = sw.ToString();
xw.Close();
sw.Close();
//sw.Dispose();
*/
return strSerializedItem;
}
public static void Serialization()
{
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/SerializeanArrayListobjecttoabinaryfile.htm
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/DeserializeanArrayListobjectfromabinaryfile.htm
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("abc", typeof(string));
dt.Columns.Add("def", typeof(int));
System.Data.DataRow dr = dt.NewRow();
dr["abc"] = "test1";
dr["def"] = 123;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["abc"] = "test2";
dr["def"] = 456;
dt.Rows.Add(dr);
System.Data.DataSet ds = new System.Data.DataSet();
ds.Tables.Add(dt);
Console.WriteLine("tname: " + dt.GetType().FullName);
cSessionData ObjectToSerialize1 = new cSessionData("key1", "value1");
cSessionData ObjectToSerialize2 = new cSessionData("key2", "value2");
cSessionData ObjectToSerialize3 = new cSessionData("key3", dt);
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(ObjectToSerialize1);
al.Add(ObjectToSerialize2);
al.Add(ObjectToSerialize3);
string strSerializedItem = Serialize(al);
Console.WriteLine(strSerializedItem);
Deserialize(strSerializedItem);
}
static void Deserialize(string strXML)
{
Type[] theExtraTypes = new Type[2];
theExtraTypes[0] = typeof(System.Collections.ArrayList);
theExtraTypes[1] = typeof(cSessionData);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.ArrayList), theExtraTypes);
System.IO.StringReader sr = new System.IO.StringReader(strXML);
System.Collections.ArrayList myal = (System.Collections.ArrayList ) ser.Deserialize(sr);
foreach (cSessionData SessionData in myal)
{
Console.WriteLine(SessionData.key + "=" + SessionData.value);
}
cSessionData MySessionData = (cSessionData) myal[2];
Console.WriteLine(MySessionData.key + "=" + MySessionData.value);
System.Data.DataTable d = (System.Data.DataTable)MySessionData.value;
Console.WriteLine(d.Rows[0]["def"]);
} // End Sub Deserialize
static void Main(string[] args)
{
Serialization();
Console.WriteLine(Environment.NewLine);
Console.WriteLine(" --- Press any key to continue --- ");
Console.ReadKey(true);
} // End Sub Main
} // End Class Program
} // Namespace SessionModuleUnitTest
Edit:
Rev 1:
using System;
using System.Collections.Generic;
using System.Text;
namespace SessionModuleUnitTest
{
public class Program
{
[Serializable()]
[System.Xml.Serialization.XmlRoot(ElementName = "SessionData")]
public class cSessionData
{
[System.Xml.Serialization.XmlElement(ElementName = "key")]
public string key;
[System.Xml.Serialization.XmlElement(ElementName = "assembly")]
public string AssemblyQualifiedName;
[System.Xml.Serialization.XmlElement(ElementName = "value")]
public string m_value;
[System.Xml.Serialization.XmlIgnore()]
public object value
{
get
{
object obj = null;
if (m_value == null)
return obj;
// Type.GetType only looks in the currently executing assembly and mscorlib
// unless you specify the assembly name as well.
//Type T = Type.GetType(this.datatype);
Type T = Type.GetType(this.AssemblyQualifiedName);
obj = DeSerializeSOAP(m_value);
return obj;
} // End Get
set
{
//this.m_value = value;
//Console.WriteLine("Type: " + obj.GetType().FullName + ", Serializable: " + obj.GetType().IsSerializable);
if (value != null)
{
//this.datatype = value.GetType().FullName;
this.AssemblyQualifiedName = value.GetType().AssemblyQualifiedName;
if (value.GetType().IsSerializable)
{
this.m_value = SerializeSOAP(value);
}
else
this.m_value = null;
}
else
{
this.AssemblyQualifiedName = null;
this.m_value = null;
}
} // End Set
} // End Property value
public cSessionData()
{
} // End Constructor
public cSessionData(string strKey, object obj)
{
this.key = strKey;
this.value = obj;
} // End Constructor
} // End Class cSessionData
//public static void InsertSessionData(cSessionData SessionData)
public static void InsertSessionData(string strSessionUID, string strSessionID, string strKey, string strValue, string strDataType)
{
strSessionUID = strSessionUID.Replace("'", "''");
strSessionID = strSessionID.Replace("'", "''");
strKey = strKey.Replace("'", "''");
strValue = strValue.Replace("'", "''");
strDataType = strDataType.Replace("'", "''");
string strSQL = @"
INSERT INTO dbo.T_SessionValues
(
Session_UID
,Session_ID
,Session_Key
,Session_Value
,Session_DataType
)
VALUES
(
'" + strSessionUID + @"' --<Session_UID, uniqueidentifier, newid()>
,N'" + strSessionID + @"' --<Session_ID, nvarchar(84), NULL>
,N'" + strKey + @"' --<Session_Key, nvarchar(100), NULL>
,N'" + strValue + @"' --<Session_Value, nvarchar(max),NULL>
,N'" + strDataType + @"' --<Session_DataType, nvarchar(4000),NULL>
)
";
//System.Runtime.Serialization.Formatters.Binary.
COR.SQL.MS_SQL.Execute(strSQL);
}
// Add reference to System.Runtime.Serialization.Formatters.Soap
public static string SerializeSOAP(object obj)
{
string strSOAP = null;
System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
using (System.IO.MemoryStream memStream = new System.IO.MemoryStream())
{
serializer.Serialize(memStream, obj);
long pos = memStream.Position;
memStream.Position = 0;
using (System.IO.StreamReader reader = new System.IO.StreamReader(memStream))
{
strSOAP = reader.ReadToEnd();
memStream.Position = pos;
reader.Close();
}
}
return strSOAP;
}
public static object DeSerializeSOAP(string SOAP)
{
if (string.IsNullOrEmpty(SOAP))
{
throw new ArgumentException("SOAP can not be null/empty");
}
using (System.IO.MemoryStream Stream = new System.IO.MemoryStream(UTF8Encoding.UTF8.GetBytes(SOAP)))
{
System.Runtime.Serialization.Formatters.Soap.SoapFormatter Formatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
return Formatter.Deserialize(Stream);
}
}
public static System.Collections.ArrayList GetData()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("abc", typeof(string));
dt.Columns.Add("def", typeof(int));
System.Data.DataRow dr = dt.NewRow();
dr["abc"] = "test1";
dr["def"] = 123;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["abc"] = "test2";
dr["def"] = 456;
dt.Rows.Add(dr);
System.Data.DataSet ds = new System.Data.DataSet();
ds.Tables.Add(dt);
cSessionData ObjectToSerialize1 = new cSessionData("key1", "value1");
cSessionData ObjectToSerialize2 = new cSessionData("key2", "value2");
cSessionData ObjectToSerialize3 = new cSessionData("key3", dt);
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(ObjectToSerialize1);
al.Add(ObjectToSerialize2);
al.Add(ObjectToSerialize3);
return al;
}
public static void Deserialize(string strSOAP)
{
System.Collections.ArrayList myal = (System.Collections.ArrayList)DeSerializeSOAP(strSOAP);
foreach (cSessionData SessionData in myal)
{
Console.WriteLine(SessionData.key + "=" + SessionData.value);
}
cSessionData MySessionData = (cSessionData)myal[2];
Console.WriteLine(MySessionData.key + "=" + MySessionData.value);
System.Data.DataTable d = (System.Data.DataTable)MySessionData.value;
Console.WriteLine(d.Rows[0]["def"]);
}
public static string Serialize(System.Collections.ArrayList al)
{
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/SerializeanArrayListobjecttoabinaryfile.htm
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/DeserializeanArrayListobjectfromabinaryfile.htm
string strSerializedItem = SerializeSOAP(al);
Console.WriteLine(strSerializedItem);
return strSerializedItem;
}
static void Main(string[] args)
{
//InsertSessionData(System.Guid.NewGuid().ToString(), "fdslfkjsdalfj", "Key1", "Value1", typeof(System.Data.DataTable).AssemblyQualifiedName);
string strSOAP = Serialize(GetData());
Deserialize(strSOAP);
Console.WriteLine(Environment.NewLine);
Console.WriteLine(" --- Press any key to continue --- ");
Console.ReadKey(true);
} // End Sub Main
} // End Class Program
} // Namespace SessionModuleUnitTest
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Design Patterns Examples
Possible Duplicate:
Examples of GoF Design Patterns
for some university work I'm working on a new way (using AO) to implement design patterns.
So now basically need to find some "real-life" examples of usage of design patterns (namely adapter, proxy, singleton, factory and observer) inside Java applications so to isolate the very part of the code in which the certain DP is being used so to try and implement that part differently.
Any (not-so-big) java application, piece of java framework/library , github/googlecode project whatsoever will be much appreciated.
A: Take a look at the Spring Framework. It uses a number of different design patterns.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Call an EventHandler from another Method How can I call the following method from another method on same code behind page?
protected void CustomValidatorDelLN_ServerValidate(object sender, ServerValidateEventArgs args)
{
bool is_valid = txtDeliveryLastName.Text != "";
txtDeliveryLastName.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
args.IsValid = is_valid;
}
I don't know how to handle the (object sender, ServerValidateEventArgs args) bit. I call CustomValidatorDelLN_ServerValidate(); What do I put inside the brackets?
A: Since you're not directly referencing the sender, and you're not properly using the ServerValidateEventArgs, you can shortcut things a bit:
var args = new ServerValidateEventArgs(String.Empty, false);
CustomValidatorDelLN_ServerValidate(null, args);
I wouldn't do that though. I would suggest a refactor. Calling an Event Handler from other code really doesn't make sense. You could easily pull out the validation logic and put it in a separate method. You could then use that new method from both spots in your code:
// You can call this method from both places
protected bool ValidateLastName()
{
bool isValid = !String.IsNullOrWhiteSpace(txtDeliveryLastName.Text);
txtDeliveryLastName.BackColor = isValid ? Color.White : Color.LightPink;
return isValid;
}
// This would be the modified Event Handler
protected void CustomValidatorDelLN_ServerValidate(object sender,
ServerValidateEventArgs args)
{
args.IsValid = ValidateLastName();
}
A: Extract that validation logic to another method
public bool CheckValidity()
{
bool is_valid = txtDeliveryLastName.Text != "";
txtDeliveryLastName.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
return is_valid;
}
And use it
protected void CustomValidatorDelLN_ServerValidate(object sender, ServerValidateEventArgs args)
{
args.IsValid = CheckValidity();
}
Now call CheckValidity() from anywhere
A: Something Like this can work...
protected void CustomValidatorDelLN_ServerValidate(object sender, ServerValidateEventArgs args)
{
args.IsValid = isValid();
}
protected bool isValid()
{
bool is_valid = txtDeliveryLastName.Text != "";
txtDeliveryLastName.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
return is_valid;
}
A: Try breaking out another method:
private bool ValidateDeliveryLastName()
{
bool is_valid = txtDeliveryLastName.Text != "";
txtDeliveryLastName.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
return is_valid;
}
then use the call
protected void CustomValidatorDelLN_ServerValidate(object sender, ServerValidateEventArgs args)
{
args.IsValid = ValidateDeliveryLastName();
}
and likewise in your other method, whatever that might be.
A: for the (object sender, ServerValidateEventArgs args) bit put this: (this, new EventArgs())
A: Since your code doesn't actually use the sender parameter you can simply pass in a null. As for the ServerValidateEventArgs you can just new it up, there's no magic.
CustomValidatorDelLN_ServerValidate(null, new ServerValidateEventArgs(String.Empty, false));
A: The method you're referring to is an event and it needs to be wired up to your validator either through the html or in a page event. Example:
<asp:CustomValidator OnServerValidate="CustomValidatorDelLN_ServerValidate" />
or
protected void Page_Load(object sender, EventArgs e)
{
CustomValidatorDelLN.ServerValidate += CustomValidatorDelLN_ServerValidate;
}
Reference: http://msdn.microsoft.com/en-us/library/system.web.ui.mobilecontrols.customvalidator.servervalidate.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: character pointers(allotted by new) and their initialistaion i have some doubts regarding character pointers:
1.when we write the declaration:
char *t;
do we need to do
t=new char[6];
strcpy(t,"terry");
or directly
t="terry";
will do..
2.Also if we follow do
char *t;
t=new char[6];
t="terry";
will t now point to the allocated memory from heap or the first letter of terry(if we look from the point of view of manipulation of pointers).
3.if i write:
char *t;
and then i have to initialise 't' to '\0'(but t should point to an allocated memory space)..how do i do this because my mvc 2010 compiler doesnt allow...
t=new char[5](0);//0 is the ascii value of '\0'
A: You're tagged C++. Use string:
std::string t("terry"); and let the language take care of the details for you.
*
*Either way will do, depending on your needs. If you need to change the string later you have to allocate the memory, and when you allocate always remember to delete it later.
*The first letter of the literal.
*t=new char[5]; t[0] = 0;
A: *
*You can do the latter option, but the pointer will most likely point to a read-only memory region, so you should only do that with a const char *.
*In this case, t will ultimately point to a read-only memory region, leaking those 6 bytes.
*You can use the memset() function to set a whole array to 0.
But yes, use std::string instead and stop thinking about this.
A: *
*You shoudn't do the second, because t is char*, and so t="terry" is deprecated (and your compiler might give this warning indicating the assignment statement.)
*The allocated memory is leaked, since you didn't use it, and t points to terry. Again, this is deprecated (and your compiler might give this warning indicating the assignment statement).
*Just do : t = new char[5](); It's default initialized now.
As the best practice, in general is, std::string. So use it:
std::string t = "terry";
No memory leak, no deprecated feature, no warning. No tension.
A: 1. If the string (e.g. "terry") is not going to get changed anywhere in you program, you can surely do
char* t = "terry";
and forget about the memory allocated for the string as it will be freed on its own. However, a better programming practice for constant strings would be declaring t as const char* like this:
const char* t = "terry";
But if it is going to get changed, then it's either
char* t = new char[6];
strcpy(t, "terry");
or
char t[6];
strcpy(t, "terry");
In the first case, where new operator is used, you will have to free the memory allocated with new after you no longer need the string:
delete[] t;
In the second case, the memory underlying the sting will be freed automatically when t leaves the C++ scope (curly braces) it was declared in (but if t is a member of an object, the memory will be freed only when the object is destructed).
2. After
char* t;
t = new char[6];
t = "terry";
t would really point at "terry", but the pointer/address you would need to free the memory allocated with new is lost for good.
3. String null terminators ('\0') are just like other characters: they need reside somewhere in the memory. You were wise enough to allocate 6 bytes for "terry", which is 5 characters in length: after
char* t = new char[6];
strcpy(t, "terry");
the 6th byte of the memory block pointed by t holds the null terminator. But
char* t;
does not allocate any memory apart from the t pointer. So, if you want a string to contain only a null terminator (be zero-length), you could do it in this way:
char* t = new char[1];
t[0] = '\0';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Symfony 2 - htmlentities and data-prototype attribute I'm making a form in Symfony 2. In my buildForm function I have the prototype option equal true to generate the html code for making dynamic collections. The code looks like this:
$builder
->add('items', 'collection' ,array(
'type' => $this->itemType,
'allow_add' => true,
'prototype' => true,
)
);
Before I update the vendors this array key made the html snippet code with htmlentities, and now the code comes with "", so that becomes an error.
Before
data-prototype="<div><label class=" required">$$name$$</label><div...
Now
data-prototype="<div><label class=" required">$$name$$</label><div id="apoyoCollection_items_$$name$$"><div><label...
Does anyone has any idea how to solve that issue?
A: I've solved the problem.
Someone, in the project, changed the Twig configuration to iso8559-1 in config.yml, like this:
twig:
charset: ISO-8859-15
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: In an array with integers one value is in the array twice. How do you determine which one? Assume that the array has integers between 1 and 1,000,000.
I know some popular ways of solving this problem:
*
*If all numbers between 1 and 1,000,000 are included, find the sum of the array elements and subtract it from the total sum (n*n+1/2)
*Use a hash map (needs extra memory)
*Use a bit map (less memory overhead)
I recently came across another solution and I need some help in understanding the logic behind it:
Keep a single radix accumulator. You exclusive-or the accumulator with
both the index and the value at that index.
The fact that x ^ C ^ x == C is useful here, since each number will be
xor'd twice, except the one that's in there twice, which will appear 3
times. (x ^ x ^ x == x) And the final index, which will appear once.
So if we seed the accumulator with the final index, the accumulator's
final value will be the number that is in the list twice.
I will appreciate it if some one can help me understand the logic behind this approach (with a small example!).
A: Assume you have an accumulator
int accumulator = 0;
At each step of your loop, you XOR the accumulator with i and v, where i is the index of the loop iteration and v is the value in the ith position of the array.
accumulator ^= (i ^ v)
Normally, i and v will be the same number so you will end up doing
accumulator ^= (i ^ i)
But i ^ i == 0, so this will end up being a no-op and the value of the accumulator will be left untouched. At this point I should say that the order of the numbers in the array does not matter because XOR is commutative, so even if the array is shuffled to begin with the result at the end should still be 0 (the initial value of the accumulator).
Now what if a number occurs twice in the array? Obviously, this number will appear three times in the XORing (one for the index equal to the number, one for the normal appearance of the number, and one for the extra appearance). Furthermore, one of the other numbers will only appear once (only for its index).
This solution now proceeds to assume that the number that only appears once is equal to the last index of the array, or in other words: that the range of numbers in the array is contiguous and starting from the first index to be processed (edit: thanks to caf for this heads-up comment, this is what I had in mind really but I totally messed it up when writing). With this (N appears only once) as a given, consider that starting with
int accumulator = N;
effectively makes N again appear twice in the XORing. At this point, we are left with numbers that only appear exactly twice, and just the one number that appears three times. Since the twice-appearing numbers will XOR out to 0, the final value of the accumulator will be equal to the number that appears three times (i.e. one extra).
A: Each number between 1 and 10,001 inclusive appears as an array index. (Aren't C arrays 0-indexed? Well, it doesn't make a difference provided we're consistent about whether the array values and indices both start at 0 or both start at 1. I'll go with the array starting at 1, since that's what the question seems to say.)
Anyway, yes, each number between 1 and 10,001 inclusive appears, precisely once, as an array index. Each number between 1 and 10,000 inclusive also appears as an array value precisely once, with the exception of the duplicated value which occurs twice. So mathematically, the calculation we're doing overall is the following:
1 xor 1 xor 2 xor 2 xor 3 xor 3 xor ... xor 10,000 xor 10,000 xor 10,001 xor D
where D is the duplicated value. Of course, the terms in the calculation probably don't appear in that order, but xor is commutative, so we can rearrange the terms however we like. And n xor n is 0 for each n. So the above simplifies to
10,001 xor D
xor this with 10,001 and you get D, the duplicated value.
A: The logic is that you only have to store the accumulator value, and only need to go through the array once. That's pretty clever.
Of course, whether this is the best method in practice depends on how much work it is to calculate the exclusive or, and how large your array is. If the values in the array are randomly distributed, it may be quicker to use a different method, even if it uses more memory, as the duplicate value is likely to be found possibly long before you check the entire array.
Of course if the array is sorted to begin with, things are considerably easier. So it depends very much on how the values are distributed throughout the array.
A: The question is: are you interested in knowing how to do clever but purely academic xor tricks with little relevance to the real world, or do you want to know this because in the real world you may write programs that use arrays? This answer addresses the latter case.
The no-nonsense solution is to go through the whole array and sort it as you do. While you sort, make sure there are no duplicate values, ie implement the abstract data type "set". This will probably require a second array to be allocated and the sorting will be time consuming. Whether it is more or less time consuming than clever xor tricks, I don't know.
However, what good is an array of n unsorted values to you in the real world? If they are unsorted we have to assume that their order is important somehow, so the original array might have to be preserved. If you want to search through the original array or analyse it for duplicates, median value etc etc you really want a sorted version of it. Once you have it sorted you can binary search it with "O log n".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Why is command dying in the script but not when I execute it outside the script? I'm using ActivePerl 5.12.4 on Windows 7. I have this in my script …
my $cmd = "ant -Dbuildtarget=$env -Dmodule=\"$module\" -Dproject=$project -Dnolabel=true checkout-selenium-tests";
print "cmd: $cmd\n";
open(F, $cmd) or die "Failed to execute: $!";
while (<F>) {
print;
}
Sadly, my script dies at the "open" command with the failure:
Failed to execute: Invalid argument at run_single_folder.pl line 17.
I don't know what's wrong. When I print out the command that's executed, I can execute that command normally in the command window and it runs fine. How can I figure out why executing the command in the Perl script is dying when it is succeeding on the command prompt?
A: You need to tell Perl it's a pipe using "|".
open(my $PIPE, "foo |") # Get output from foo
open(my $PIPE, "| foo") # Send input to foo
Since you don't need the shell, let's avoid it but using the multi-arg version. For one thing, it saves you from converting $env, $module and $project to shell literals (like you tried to do with $module).
my @cmd = (
ant => (
"-Dbuildtarget=$env",
"-Dmodule=$module",
"-Dproject=$project",
"-Dnolabel=true",
"checkout-selenium-tests",
)
);
open(my $PIPE, '-|', @cmd) or die "Failed to execute: $!";
while (<$PIPE>) {
print;
}
A: If you want to start a subprocess with a call to open() and capture its output you need to use a | after the command, or perl will think you want to open a file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: endless zoom CATiledlayer iOS Is there a way to reset your zoomlevel each time you're on a deeper zoomlevel so you can have an endless zoom?
I'm trying to create a CATiledLayer where each tile has a different color and when you zoom into a tile you just get new colors, and so on.
A: I'm not sure about how to do this with CATiledLayer, but the book Programming IOS 4, by Matt Neuburg, includes a section "Zooming with Detail" which describes how to do something similar using UIScrollView.
UIScrollView offers support for pinch-out zooming into its contents, but it just magnifies the unzoomed rendering of its contents with a scale transform rather than re-rendering its contents at the higher zoomScale. Therefore, in order to provide zooming that actually shows increased detail, you need to add some logic.
Basically, the book suggests you implement scrollViewDidEndZooming:withView:atScale: so that it (1) resets UIScrollView's zoomScale to its default value of 1.0, and (2) removes the contents view and provides a new view with contents at the desired true zoom scale. You need to introduce your own ivar to track this true scale manually. The result is that, as you zoom further in and the true scale keeps increasing monotonically, the UIScrollView houses a succession of different views and keeps cycling its own zoomScale within its bounds, from 1.0 to max, then reset to 1.0, then 1.0 to max, etc.. The book gives a skeletal example (p 506 in the 1st edition, second printing of the book).
How would you use this for endless zooming? If you don't need truly endless zooming, you can just do the above with a very large range for the true scale.
If you want truly endless zooming, you can't track your zoom level with a finitely-bounded variable for the true scale. Instead, you'd modify scrollViewDidEndZooming:withView:atScale: so that it (1) resets UIScrollView's zoomScale to its default value of 1.0, (1) removes the contents view and provides a new view, where the new view at the new zoomScale of 1.0 is visually identical to the removed view at the old zoomLevel. In this way, as the user kept zooming in with pinch-out gestures, UIScrollView would repeatedly cycle from 1.0 to max, invisibly replacing the underlying view at each cycle, in between the user's gestures.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Get File Name from Upload Form Using jQuery? I want to get the file name of the uploaded file using jQuery. But the problem, I got the fake path and file name, instead of the file name only. This is my form.
<form action="" method="post">
<input type="file" name="uploadFile" id="uploadFile" />
<input type="submit" name="submit" value="Upload" id="inputSubmit" />
</form>
And the jQuery is like this
$(document).ready(function(){
$('#inputSubmit').click(function(){
alert($('#uploadFile').val());
});
});
I use Chrome and got this in the alert box. Let's say I choose file named filename.jpg.
C:\fakepath\filename.jpg
How can I get only the file name? Thank you for your help.
A: Split the filepath string with "\" and use the last item in the resulting array.
see: Getting the last element of a split string array
A: You can also do:
$('#uploadFile').prop("files")['name'];
If it's a multiple file input, do:
$.each($('#uploadFile').prop("files"), function(k,v){
var filename = v['name'];
// filename = "blahblah.jpg", without path
});
A: get file name when uploading using jquery
var filename = $('input[type=file]').val().split('\').pop();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Core Plot CPTGraphHostingView corner radius is it possible to set corner radius for CPTGraphHostingView?
A: No, but why would you need to? All Core Plot drawing is done by Core Animation layers (CPTGraph and all of it's various pieces). You can set the corner radius on the graph and on many other layers. Any graph part that is a subclass of CPTBorderedLayer can take a corner radius.
A: Make the HostView background clear color and set the background property and corner radius of the graph. This worked for me:
hostView.backgroundColor=[UIColor clearColor];
graph.backgroundColor=[UIColor brownColor];
graph.cornerRadius=10.0f;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7500997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Insert Editable Text Field in Cognos Report (v.8) Objective: Genrate a report in PDF or HTML with an Editable text field (for Comment)
Purpose: The PDF or HTML report is delivered to customer (a statement of work). They should be able to type in their comments in the comment field, save the report in their disk.
Note: I am not looking for Write-back to server. This is for offline editing and entering comment.
My handicap: I do not have development access in cognos system. But my developer claims, it can not be done. I can not imagine that is
Research done till now:
Example - Add a Multimedia File to a Report
-- In the Insertable Objects pane, on the toolbox tab, drag the HTML Item object to the report. In the HTML dialog box, type the following: PARAM NAME="URL" VALUE="/c8/webcontent/samples/images/GO.wmv"
In similar way, can we use PARAM Name="textarea" ?
A: I haven't done that but I have a clue. Insert an HTML part in your report where you would like to add the comments. Put some javascript in such HTML code to read / write using a JSON Web service.
You would need to pass some user's data like his/her username and domain, so they can only modify their own comments.
I think I saw an example in Cognos KB some years ago.
A: Why not save the report as an XLS file? Then the user can add comments to the XLS file as much as they want.
A: You can actually add Text Area into your cognos report.
drag html item into the report
and in HTML Property add the following code.
Comments:
This will add the TextArea where user can write their comments.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to click on an
* element with javascript? Assuming that we have html like the one below, I want to be able to click on the element using javascript just as if I it was a link.
<li class="myClass" data-type="onClick" data-target="something://url">
<img src="img.png" alt="image"/>
<h2> Text</h2>
</li>
Thanks
A: <li class="myClass" onclick="doSomething()">
<img src="img.png" alt="image"/>
<h2> Text</h2>
</li>
In your javascript create the function doSomething()
And maybe use CSS on the li element:
li.myClass {
cursor:pointer;
}
A: You could also use jQuery. It's more easy to work with jQuery. There you would give the li element an id or a class and then you could use this code:
$(".myClass").click( function() {
// .. do the code
});
or with id:
$("#myID").click( function() {
// .. do the code
});
I would also advise to put a pointer on the element by adding " cursor: pointer; " to the css.
So everyone knows it's possible to click on it :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible in C++ to declare an attibute in the body? Is it possible in C++ to declare an attibute in the body, that is, the .cpp file ?
A: If by attribute, you mean member variable of a class, then the answer is: "member variables must be defined in the class definition." They cannot be defined anywhere else, neither in the constructor, or in any member function.
Whether the class definition sits in the header file or in the source (.cpp) file is not relevant.
A: You can't add an attribute to a class outside the original definition of the class (which is usually in a header), for example in the .cpp file.
A: Yes:
test.cpp:
class Test
{
int x; //declare attribute in class body and in cpp file
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to test how many options are in a select box? I am using the jQuery 1.6.2.
I am dynamically populating a select box using ColdFusion and jQuery.
When the options are returned and stuffed inside the select box, I'd jQuery to figure out how many options there are and adjust the size attr as needed.
// load the options into the select box
$("#Select").load("GlobalAdmin/ArtistUnassociatedAlbums.cfm?" + QString);
// test the number of options
var NumOfOptions = $();
var BoxSize = 0;
// do a calculation
if (NumOfOptions > 10) {
BoxSize = 10;
} else {
BoxSize = NumOfOptions ;
}
// adjust the select box size
$("#AlbumsSelect").attr("size", BoxSize );
How do I efficiently get at the number of options returned?
A: Yea just use the length property...
var numOfOptions = $('#Select option').length;
A: Just select the options and test the length property of the resulting jQuery object:
console.log($("#Select option").length);
A: Try to use javascript's property .length
var length = $("option").length;
A: You can use this:
var NumOfOptions = $("#AlbumsSelect option").length;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In .Net 2.0 :How Can I form a predicate delegate to Find() something in my List? After looking on MSDN, it's still unclear to me how I should form a proper predicate to use the Find() method in List using a member variable of T (where T is a class)
For example:
public class Name
{
public string FirstName;
public string LastName;
public String Address;
public string Designation;
}
String[] input = new string[] { "VinishGeorge", "PonKumar", "MuthuKumar" };
//ConCatenation of FirstName and Lastname
List<Name> lstName = new List<Name>();
Name objName = new Name();
// Find the first of each Name whose FirstName and LastName will be equal to input(String array declard above).
for(int i =0;i<lstName.Count;i++)
{
objName = lstName .Find(byComparison(x));
Console.Writeline(objName .Address + objName.Designation);
}
What should my byComparison predicate look like?
A: It's not clear why you're looping and calling Find. Normally you'd call Find not in a loop - it will loop for you. Anonymous methods are your friends here though:
Name found = lstName.Find(delegate(Name name) {
return name.FirstName + name.LastName == x;
});
If you're using C# 3 (even targeting .NET 2) you can use a lambda expression instead:
Name found = lstName.Find(name => name.FirstName + name.LastName == x);
EDIT: To find all names in input you can use:
List<Name> matches = lstName.FindAll(delegate(Name name) {
string combined = name.FirstName + name.LastName;
return input.Contains(combined);
});
Note that this won't be terribly efficient as it will look through the whole of input for a match on every Name. However, the more efficient alternatives are more complicated - I think it's important for you to understand how this code works to start with.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Affine transform in PIL Python I have problems with the im.transform method in PIL python library. I thought I figured out the logic of parameters, A to F, however, the resulting image gets rotated in the wrong direction and cut off although all four corners calculated by the bellow function have correct positive values.
Could anybody give me formulas to calculate affine parameters (A to F) from three identical points in both coordinate systems?
def tran (x_pic, y_pic, A, B, C, D, E, F):
X = A * x_pic + B * y_pic + C
Y = D * x_pic + E * y_pic + F
return X, Y
A: transform works fine for me. As an example we'll rotate an image around a center different from (0,0) with optional scaling and translation to a new center. Here is how to do it with transform:
def ScaleRotateTranslate(image, angle, center = None, new_center = None, scale = None,expand=False):
if center is None:
return image.rotate(angle)
angle = -angle/180.0*math.pi
nx,ny = x,y = center
sx=sy=1.0
if new_center:
(nx,ny) = new_center
if scale:
(sx,sy) = scale
cosine = math.cos(angle)
sine = math.sin(angle)
a = cosine/sx
b = sine/sx
c = x-nx*a-ny*b
d = -sine/sy
e = cosine/sy
f = y-nx*d-ny*e
return image.transform(image.size, Image.AFFINE, (a,b,c,d,e,f), resample=Image.BICUBIC)
A: I think my version of is much more explicit and easy to understand.
def scale_rotate_translate(image, angle, sr_center=None, displacement=None, scale=None):
if sr_center is None:
sr_center = 0, 0
if displacement is None:
displacement = 0, 0
if scale is None:
scale = 1, 1
angle = -angle / 180.0 * np.pi
C = np.array([[1, 0, -sr_center[0]],
[0, 1, -sr_center[1]],
[0, 0, 1]])
C_1 = np.linalg.inv(C)
S = np.array([[scale[0], 0, 0],
[0, scale[1], 0],
[0, 0, 1]])
R = np.array([[np.cos(angle), np.sin(angle), 0],
[-np.sin(angle), np.cos(angle), 0],
[0, 0, 1]])
D = np.array([[1, 0, displacement[0]],
[0, 1, displacement[1]],
[0, 0, 1]])
Mt = np.dot(D, np.dot(C_1, np.dot(R, np.dot(S, C))))
a, b, c = Mt[0]
d, e, f = Mt[1]
return image.transform(image.size, Image.AFFINE, (a, b, c, d, e, f), resample=Image.BICUBIC)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What should be the automated build steps for a database? Every-time I check in, I want to trigger Nant build script to run some tasks for the database in the project in Dev/Uat/Live server to clean db, reload contents of db etc.
What should be the steps as I have never done it before? Is there an article that talks about automated database built steps which you can recommend?
Thanks.
A: I just found this one and it is not bad: bottleit.com.au/Blog/post/Continuous-database-integration.aspx. He created an osql target and sets a script file. The osql target will run the script file based on properties in the nant script (database, user name, password). You will, of course, need osql on the build machine for this to work. Everything in sql server 2008 is scriptable, from creating to restoring databases. So my suggestion is to do what ever you need to do manually, save it as a script file and use that script file in your build script.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Zend Framework: Inserting calls to View Helpers into Javascript code I'm developing a web application, where I use jQuery to make Ajax calls to the server.
I'm using the url view helper to insert the URL to be called. The code inside my view scripts looks like the following:
$.ajax({
type: "POST",
url: "<?php echo $this->url(array('action' => 'myaction', 'controller' => 'mycontroller'), null, true); ?>",
dataType: "html",
data: { id: myId, format: 'xml' },
beforeSend: function() {
// Show pseudoprogress
},
success: function(html) {
// Process response
},
error: function() {
// Show an error message
}
});
The system is working fine, but because of this approach I can't extract the Javascript code to separate files, because I always need to run it through the PHP interpreter first.
I wonder if there is a better way to do it, so that I can keep the Javascript code as "PHP-clean" as possible (and eventually, in separate files).
Thanks in advance.
A: Provide the url in a hidden input field or any other hidden markup element you like and get it from there with jQuery.
Example:
In the view:
<input type="hidden" id="myActionUrl" value="<?php echo $this->url(array('action' => 'myaction', 'controller' => 'mycontroller'), null, true); ?>" />
In the javascript:
url : $('#myActionUrl').val(),
A: I would do this:
<script type="text/javascript">
var url = "<?php echo $this->url(array('action' => 'myaction', 'controller' => 'mycontroller'), null, true); ?>";
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unbind special keypress event I've got a question regarding jQuery keypress events. I've got the following (working) code:
$(document).bind('keypress', function(event) {
if ($('#myDiv').is(':visible')) {
if (event.which == 102) {
// ...do something...
}
}
else {
if (event.which == 102) {
return;
}
}
});
I always "unbind" the event with binding another "over" it. I know that I can unbind it with .unbind('keypress') but I got more keypress events and when i unbind this with $(document).unbind('keypress') all my events get lost.
Can I do something like "keypress.102" to only unbind this particular "key" or how can this be done?!
A: You were on the right track. That's called namespaced events, i.e. labelling specific bindings using <event_name>.<namespace> (in your case, "keypress.102").
For example:
$(document).bind("keypress.key102", function(event) {
if ($('#myDiv').is(':visible')) {
if (event.which == 102) {
// ...do something...
}
}
else {
if (event.which == 102) {
return;
}
}
});
you can later unbind that without affecting other bound keypress events:
$(document).unbind("keypress.key102");
A: Use a namespaced event.
http://docs.jquery.com/Namespaced_Events
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: iOS memory issue with init in viewDidLoad and release in viewDidUnload Are there any potential memory issues with the following code?:
- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
}
- (void)viewWillAppear:(BOOL)animated {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
- (void)viewDidUnload
{
[locationManager release];
locationManager=nil;
[super viewDidUnload];
}
I have checked it with Instrument and it says there is memory leaking with above code.
A: You should release the locationManager in the dealloc method.
- (void)dealloc
{
[locationManager release];
[super dealloc];
}
The reason for that is that viewDidUnload is not guaranteed to get called.
For details see these questions:
When is UIViewController viewDidUnload called?
viewdidunload is not getting called at all!
A: It looks quite well besides:
*
*At the beginning of viewDidLoad add [super viewDidLoad];.
*At the beginning of viewWillAppear: add [super viewWillAppear:animated];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to adjust UITextView's width to fit its content without wrapping? Resizing UITextView to fit height of its content can be achieved like this:
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;
Is there something similar to fit width, without wrapping the content text?
A: 1) You can use the NSString UIKit Additions to compute the size taken by the text (and adjust the size of your UITextView accordingly). You may seen an example here.
For example, if you need to know the CGSize that is taken by your NSString if rendered on a single line, use CGSize sz = [_textView.text sizeWithFont:_textView.font] then adjust your frame given this size value.
If you need to know the size taken by your text if rendered on multiple lines, wrapping it if the text reaches a given width, use sizeWithFont:constrainedToSize:lineBreakMode: instead, etc.
2) You may also be interested in the sizeThatFits: and sizeToFit methods of UIView.
The first one returns the CGSize (that fits in the given CGSize passed in parameter) so that your UITextView can display all your text. The second actually do the resizing, adjusting the frame for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Good H323 Proxy server Is there any open source good h323 proxy server to be used for video conferencing?
In C or C# ?
A: Take a look at the GNU Gatekeeper. Its writtten in C++ and can be configured to be a H.323 proxy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery/JS Error When on a page that doesn't have given ID I've got a situation, that I'm pretty sure is something basic, that I just don't know the proper syntax/sequence for:
I've got the following code in my site's $(document).ready(function():
$(document).ready(function() {
//Prevents default anchor tag behavior
$('#socialScroller a, #contributePod a, .prev, .next').click(function(e) {
e.preventDefault();
});
//Scrollable for Social Sidebar area
$(".socialScrollable").scrollable({ easing:"easeInOutCubic", vertical:true, next:".socialNext", prev:".socialPrev"});
var scrollable = jQuery(".socialScrollable").data("scrollable");
var size = 3;
scrollable.onSeek(function(event, index) {
if (this.getIndex() >= this.getSize() - size) {
jQuery("a.socialNext").addClass("disabled");
}
});
scrollable.onBeforeSeek(function(event, index) {
if (this.getIndex() >= this.getSize() - size) {
if (index > this.getIndex()) {
return false;
}
}
});
//Scrollable for History page
$(".historyScrollable").scrollable({ easing:"easeInOutCubic"}).navigator();
//Scrollables for Media page
$(".mediaScrollable").scrollable({ easing:"easeInOutCubic"}).navigator({navi:'#pressNavTabs'});
$("#mediaNavScrollable").scrollable({ easing:"easeInOutCubic", next:".nextMedia", prev:".prevMedia"});
var scrollable = jQuery("#mediaNavScrollable").data("scrollable");
var size = 4;
scrollable.onSeek(function(event, index) {
if (this.getIndex() >= this.getSize() - size) {
jQuery("a.nextMedia").addClass("disabled");
}
});
scrollable.onBeforeSeek(function(event, index) {
if (this.getIndex() >= this.getSize() - size) {
if (index > this.getIndex()) {
return false;
}
}
});
$("#mediaNavScrollable").scrollable({ easing:"easeInOutCubic"});
//History Scroller
$(function() {
$(".vertHistoryScroller").scrollable({ vertical:"true", easing:"easeInOutCubic", next:".nextVert", prev:".prevVert" }).navigator();
});
//Contribute Sidebar Actions
$(".contributeContainer").hide();
$("#contributePod a").click(function(){
var aData = $(this).attr("data-name");
$(".contributeContainer").fadeOut("fast");
$("#"+aData).fadeIn("slow");
});
$(".contributeContainer a").click(function(){
$(this).parent(".contributeContainer").fadeOut("fast");
});
});
On any page that does not have #mediaNavScrollable, I get this error in the JS console:
Uncaught TypeError: Cannot call method 'onSeek' of undefined.
If I comment everything from the "var scrollable" line down, everything works fine on pages without that #mediaNavScrollable ID. How do I wrap that JS so that it only fires if it has #mediaNavScrollable?
A: You need to check to see if scrollable is not null and has any elements in it. If it doesnt, exit the handler.
var scrollable = jQuery("#mediaNavScrollable").data("scrollable");
if(scrollable == null || scrollable.length==0) return;
This will exit the handler without running any other code. Alternately, you can use an if block:
var scrollable = jQuery("#mediaNavScrollable").data("scrollable");
if(scrollable == null || scrollable.length==0)
{
//element doesnt exist, perform alternate action
}
else
{
//element does exist, do normal stuff here
scrollable.onSeek(......);
}
A: if ($("#mediaNavScrollable").length){
// your code
}
A: You need to check for the existence of scrollable:
if(scrollable)
{
...
}
A: You can check to see if the element exists first, like this:
if ($("#mediaNavScrollable").length) {
//your code here
}
A: That's not being caused by a missing element. If the element were missing, you'd never make it into the code where the error happens. edit — oops I hadn't scrolled the OP's code far enough to the right; I thought the code below it that's confusingly indented was part of a handler function.
Instead, the problem is that this:
var scrollable = jQuery("#mediaNavScrollable").data("scrollable");
is returning nothing. There's no data element called "scrollable" stored on your "mediNavScrollable" element. That may mean that the element in your HTML is supposed to look like this:
<div id='mediaNavScrollable' data-scrollable='something'>
but I sort of doubt it, as that code seems to expect it to be a DOM element. (Sort of an unpleasant mix of jQuery and old-style DOM 0 handlers, too). That means that for the code to work, not only do you need that element to be on the page, but something will have had to stick a reference to a DOM node in the jQuery data store for the element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: k-means: Same clusters for every execution Is it possible to get same kmeans clusters for every execution for a particular data set. Just like for a random value we can use a fixed seed. Is it possible to stop randomness for clustering?
A: Yes, calling set.seed(foo) immediately prior to running kmeans(....) will give the same random start and hence the same clustering each time. foo is a seed, like 42 or some other numeric value.
A: Yes. Use set.seed to set a seed for the random value before doing the clustering.
Using the example in kmeans:
set.seed(1)
x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(x) <- c("x", "y")
set.seed(2)
XX <- kmeans(x, 2)
set.seed(2)
YY <- kmeans(x, 2)
Test for equality:
identical(XX, YY)
[1] TRUE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Unable to retrieve value from java web service response in Flex I am trying to read data from the java web service from flex mxml/action script, seems like the call i.e request/response is successfully but when unable to read the value from the response, please help the MXML code is as below:
Unable to print the value from :
var outA:OutputA_type = ccxc.OutputA;
trace(outA);
var aaa:String = outA.toString();
Alert.show(aaa)
it prints as [Object OutputA)_Type] but not the required value. however in the flex builder test connection also in the network monitoring I see the proper value/response.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:number1="services.number1.*"
xmlns:testws="services.testws.*"
minWidth="955" minHeight="850" creationComplete="initApp()">
<!-- Styles ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<fx:Style source="Styles.css"/>
<!-- Script ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import mx.controls.Alert;
import mx.events.CalendarLayoutChangeEvent;
import mx.rpc.AsyncToken;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ObjectUtil;
import services.testws.Testws;
import valueObjects.OutputA_type;
import valueObjects.Parameters_type;
import valueObjects.TestParameters;
import valueObjects.TestResult_type;
private function initApp():void {
var testWebS:Testws = new Testws();
var testParam:TestParameters = new TestParameters();
testParam.ParamA = 2;
testParam.ParamB = 3;
var token:AsyncToken = testWebS.test(testParam);
token.addResponder(new mx.rpc.Responder(result, fault));
}
private function result(event:ResultEvent) : void {
trace(event.result);
var strData:TestResult_type = event.result as TestResult_type;
var ccxc:Parameters_type = strData.Parameters;
var outA:OutputA_type = ccxc.OutputA;
trace(outA);
var aaa:String = outA.toString();
Alert.show(aaa.toString());
}
public function fault(event : FaultEvent) : void {
Alert.show("Failed Condition Fault Exception");
}
]]>
</fx:Script>
<!-- Declarations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<fx:Declarations>
</fx:Declarations>
<!-- UI components ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<s:Label x="10" y="34"
width="690" height="40"
text="Employee Portal: Vehicle Request Form"
styleName="titleHeader"/>
<s:Form x="10" y="70">
<s:FormItem label="Input a:">
<s:TextInput id="a"/>
</s:FormItem>
<s:FormItem label="Input b:">
<s:TextInput id="b"/>
</s:FormItem>
<s:FormItem>
<s:Button id="submitButton"
label="Submit Request" click="submitButton_clickHandler(event)"/>
</s:FormItem>
</s:Form>
</s:Application>
SOAP-UI Request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tes="http://tempuri.org/testws">
<soapenv:Header/>
<soapenv:Body>
<tes:test>
<tes:parameters>
<!--Optional:-->
<tes:ParamA>3</tes:ParamA>
<!--Optional:-->
<tes:ParamB>1</tes:ParamB>
</tes:parameters>
</tes:test>
</soapenv:Body>
</soapenv:Envelope>
SOAP-UI Response:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<m:testResponse xmlns:m="http://tempuri.org/testws">
<m:testResult>
<axis2ns794:Parameters xmlns:axis2ns794="http://tempuri.org/testws">
<axis2ns795:OutputA description="" xmlns:axis2ns795="http://tempuri.org/testws">1</axis2ns795:OutputA>
</axis2ns794:Parameters>
</m:testResult>
</m:testResponse>
</soapenv:Body>
</soapenv:Envelope>
A: private function result(event:ResultEvent) : void {
trace(event.result);
var strData:TestResult_type = event.result as TestResult_type;
var ccxc:Parameters_type = strData.Parameters;
var outA:OutputA_type = ccxc.OutputA;
trace(outA);
var aaa:String = outA.toString();
Alert.show(aaa.toString());
}
*
*What is the response you get while doing trace(event.result)
*Do a trace of this strData, post down what you get.
A: Instead of using
private function result(event:ResultEvent) : void {
trace(event.result);
var strData:TestResult_type = event.result as TestResult_type;
var ccxc:Parameters_type = strData.Parameters;
var outA:OutputA_type = ccxc.OutputA;
trace(outA);
var aaa:String = outA.toString();
Alert.show(aaa.toString());
}
try using Object instead of casting it directly.
var retObj:Object = event.result;
var strData:TestResult_type = new TestResult_type();
strData.firstProperty = retObj.firstProperty;
strData.secondProperty = retObj.secondProperty;
I think I had an issue with this before where you can't just assign the returned object to a flex object like you can on the java side. If this works then you have to go through each of the event.result objects and set all of the properties of your object through setters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make HaXml and DrIFT work with GHC 7.0.3? I'm looking for a solution to interchange data between Haskell and Java/Scala/C# code. Currently, I'm thinking about using XML. Ideally, I'd like the XML schema to be generated from my Haskell datatypes. My first try was HaXml 1.22.2, DrIFT 2.2.2. All on GHC 7.0.3. There is the following snippet:
import Data.List (isPrefixOf)
import Text.XML.HaXml.XmlContent
import Text.XML.HaXml.Types
import Text.XML.HaXml.Pretty (document)
data MyType = A | B String deriving (Eq, Show)
{-! derive : XmlContent !-} -- this line is for DrIFT
out of this file, DrIFT produces:
{- Generated by DrIFT (Automatic class derivations for Haskell) -}
{-# LINE 1 "ts.hs" #-}
import Data.List (isPrefixOf)
import Text.XML.HaXml.XmlContent
import Text.XML.HaXml.Types
import Text.XML.HaXml.Pretty (document)
data MyType = A | B String deriving (Eq, Show)
{-! derive : XmlContent !-} -- this line is for DrIFT
{-* Generated by DrIFT : Look, but Don't Touch. *-}
instance HTypeable MyType where
toHType v =
Defined "MyType" [] [Constr "A" [] [],Constr "B" [] [toHType aa]]
where
(B aa) = v
instance XmlContent MyType where
parseContents = do
{ e@(Elem t _ _) <- elementWith (flip isPrefixOf) ["B","A"]
; case t of
_ | "B" `isPrefixOf` t -> interior e $ fmap B parseContents
| "A" `isPrefixOf` t -> interior e $ return A
}
toContents v@A =
[mkElemC (showConstr 0 (toHType v)) []]
toContents v@(B aa) =
[mkElemC (showConstr 1 (toHType v)) (toContents aa)]
-- Imported from other files :-
Compiling this code with GHC produces an error message:
19:32:
Couldn't match expected type `[Char]' with actual type `QName'
In the second argument of `isPrefixOf', namely `t'
In the expression: "B" `isPrefixOf` t
In a stmt of a pattern guard for
a case alternative:
"B" `isPrefixOf` t
Is it a problem with tooling or I'm doing something wrong? How to resolve this problem?
A: Diggin around in the Hackage documentation for older versions of HaXml reveals that in version 1.20.2 and earlier, the Elem data constructor used to take a Name, which is just a type synonym for String. Sometime between that and version 1.22.3, however, it was changed to take a QName, which is a custom data type.
It therefore makes sense that using isPrefixOf on element names would be valid for older versions, but invalid for newer versions.
From the upload dates of these versions, this happened sometime during the last year, while DrIFT does not appear to have been updated since 2009.
You should probably notify the DrIFT maintainer of this. In the meanwhile, you can work around it by using an older version of HaXml, or by writing the instances yourself. You should be able to use the incorrect generated instances as a starting point.
A: I recently had success integrating Haskell and Python using the Apache Thrift project. The Thrift compiler works off a data and service definition file to generate the code in the necessary languagues to create client and servers that seamlesslessly pass messages to each other.
A: Untested fix:
1) Change the line that says import Data.List(isPrefixOf) to
import qualified Data.List(isPrefixOf) as List
2) Add this code:
isPrefixOf (N n) = List.isPrefixOf n
isPrefixOf (QN _ n) = List.isPrefixOf n
Im not sure if this gives the intended behaviour for qualified names though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Symfony2, Doctrine2 and PostgreSQL: error "Undefined variable: className" I try to configure entities for existing table in PostgreSQL database.
Sequences in this database have names other than default doctrine names, so i have to account that in entity.
Webclient\db\LoginBundle\Entity\WebclientUsers:
type: entity
table: webclient.t_webclientusers
fields:
id:
type: integer
generator:
strategy: AUTO
sequenceGenerator:
sequenceName: webclient.s_webclientusers_id
email:
type: text
lifecycleCallbacks: { }
I tried also other strategy configurations, but i still having error:
Notice: Undefined variable: className in ****\Symfony\vendor\doctrine\lib\Doctrine\ORM\Mapping\ClassMetadataFactory.php line 343
What can I do with that?
A: I found an aswer on another website:
This is a internal error of Doctrine2, this bug is now fixed but if not :
http://www.doctrine-project.org/jira/browse/DDC-1381
Just edit the file ClassMetadataFactory.php and replace $className by $class->name on line 343, it will fix the problem.
You will probably get another error but this time, this will come from ur app.
Regards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Calling java webservice from sharepoint 2010 event receiver We are using sharepoint event reciever as given below:
public override void ItemUpdated(SPItemEventProperties properties)
{
if (properties.ListItemId > 0 && properties.ListId != Guid.Empty)
{
string id, url, operation;
url = properties.AfterUrl;
operation = "Update";
id = properties.ListItemId.ToString();
//id=properties.ListId.ToString();
JavaSendAlert.AlertWebServiceService jsa = new JavaSendAlert.AlertWebServiceService();
jsa.sendAlert(id,url,operation);
}
JavaSendAlert is a WSDL consumed, made in java and published on a 32 bit systyem.
We get exception on this line:
JavaSendAlert.AlertWebServiceService jsa = new JavaSendAlert.AlertWebServiceService();
The Exception is:
Cannot execute a program. The command being executed was
"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe" /noconfig
/fullpaths
@"C:\Users\461167\AppData\Local\Temp\OICE_FEF98CDC-FC33-4071-B497-DC6B21E9E725.0\w1tuwwu5.cmdline"
What we can do with this exception.
Thanks for replying
the error on the page u shared is not sma eas mine.
my error path is C:\Users\myname\AppData\Local\Temp\OICE_FEF98CDC-FC33-4071-B497-DC6B21E9E725.0\w1tuwwu5.cmdline
and on the page u shared is @"D:\WINNT\TEMP\eyrpuhyg.cmdline and is quite common in internet.
I am still not able to solve the problem but, people faced the same problem while installing SQL server http://social.technet.microsoft.com/Forums/en/sqlsetupandupgrade/thread/480562d9-d5db-4ce6-848a-a334c40dc3b9
Thanks
Mohit Leekha
A: with this information i can only guess... i'd say it's a permission/authentication issue - check out this KB.
A: Finally it worked
i just changed the trust level to farm which was previously set to sandbox.
Thanks
Mohit Leekha
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pear in SilverStripe? Does anyone knows how to integrate Pear (http://pear.php.net) and install packages in SilverStripe? My hosting provider doesn't want to install it for me.
Thanks,
Mauro
A: So your hosting provider doesn't have pear and you want to work around that by integrating it in Silverstripe and use it from there but it doesn't really have anything to do with SilverStripe. You just want to be able to use pear. Well, first of all, if your hosting provider doesn't allow pear, it would probably be an illegal move. Second, pear is 'just' a package manager. You can always just copy the files of that Mail package to your server (including all dependences) and put them onto your include path. You don't need the package manager for that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I find a specific process with "top" in a Mac terminal I've tried top | grep skype for example but it doesn't work. I'm trying to find a specific process by name.
A: if you really love top, you could try:
top -b -n 1 | grep skype
e.g.
kent$ top -b -n 1 |grep dropbox
4039 kent 20 0 184m 14m 5464 S 0 0.4 0:58.30 dropbox
A: Use this instead: ps -ax | grep -i skype
A: use ps instead of top.
A: Use: top -l 0 | grep Skype
The 0 is for infinite samples. You can also limit the number of samples to a positive number.
A: On Linux, the top command supports the -p option to monitor specific PIDs. On MacOS, the -p option is called -pid instead.
# Get the PID of the process
pgrep Skype
# Then
top -pid <put PID here>
# Or more succinctly:
top -pid `pgrep Skype`
If you do this a lot, you could turn this into a function and add it to ~/.bash_profile:
# Add this to ~/.bash_profile
function topgrep() {
if [[ $# -ne 1 ]]; then
echo "Usage: topgrep <expression>"
else
top -pid `pgrep $1`
fi
}
Now you can simply use topgrep Skype instead, which will run like usual but it will only show the process(es) matching expression.
A: Now you can use pgrep skype to find the process.
A: I would recommend using ps -ax | less
From within less, you can type in /skypeEnter to search for processes with names containing "skype".
A: Tested on MacOSX Mojave. It works a bit different than linux.
top -pid doesn't expect a comma separated list of pids, it expects only one pid. So I had to changed it a little to work with several pids.
top -pid $(pgrep -d ' -pid ' -f Python)
filter all Python process on top. It essentially becomes something like this:
top -pid 123 -pid 836 -pid 654
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
} |
Q: Response.BinaryWrite() works for one page, not another I have a helper function in a class library that creates and serves a custom PDF:
byte[] file = GetPdfBytesFromHtmlString( htmlCodeToConvert );
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader( "Content-Type", "binary/octet-stream" );
response.AddHeader( "Content-Disposition", "attachment; filename=" + filename + "; size=" + file.Length.ToString() );
response.Flush();
response.BinaryWrite( downloadBytes );
response.Flush();
response.End();
When this code is executed on one page, everything works. Another page is mostly identical, the only difference being the output of the HTML to be written to the PDF, which I have verified is working correctly. However, nothing happens. I've stepped through the code, it just goes its merry way, but the browser doesn't prompt to download.
I know I'm leaving a lot of code out, but because it works in one instance and not another, I'm stumped and looking for ideas to pursue a solution.
A: I really hate answering my own question, because it means I didn't do enough research before asking it. However, I was reviewing it and realized I'd only tested in Firefox. Running it in IE exposed a script error that contained the text "Error parsing near '%PDF - 1.4%' which I'd seen while searching but didn't follow up on.
The problem is the page that's not working uses an AJAX Update Panel, which I hadn't realized when I stated the code was identical. The export button click code is, but the markup isn't.
The second reply in this post contains some additional info and a workaround.
A: Your byte array you create is called file in the code, but you binarywrite 'downloadbytes' - is this the problem?
A: If the problem is the update panel, then all you need to do is add a full post back trigger for the control that's calling the function.
A: I was able to resolve this by adding a trigger inside my update panel.
<Triggers>
<asp:PostBackTrigger ControlID="YourControlID" />
</Triggers>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c# call batch with error-redirect and exe over cmd via process I use the following lines to create a process:
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.WorkingDirectory = buildProject.DirectoryName;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
Then I start the process and pass some commands to it:
process.Start();
StreamWriter stream = process.StandardInput;
// call batch
stream.WriteLine(@"call ""test.bat""");
// call exe
stream.WriteLine("echo msbuild!");
// exit-command
stream.WriteLine("exit");
All works fine until the batchfile contains two nul-redirects:
@call :Jump_1
@call :Jump_2
@goto end
@REM -----------------------------------------------------------------------
:Jump_1
@echo Jump_1
@call :Jump_1_1 1>nul 2>&1 REM critical!!!
@exit /B 0
:Jump_1_1
@echo Jump_1_1
@exit /B 0
@REM -----------------------------------------------------------------------
:Jump_2
@echo Jump_2
@call :Jump_2_1 1>nul 2>&1 REM critical!!!
@exit /B 0
:Jump_2_1
@echo Jump_2_1
@exit /B 0
@REM -----------------------------------------------------------------------
@echo End
:end
In this case the process stops immediatly. StandardOut shows this:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Entwicklung\ProcessTest\ProcessTest\bin\Debug>call "test.bat"
Jump_1
Jump_2
It only crashs if there are two Redirects if I remove one all is fine.
Because the original script is delivered with VS2010 I cannot change the script.
Edit: I updated the question with more details.
A: Is it the redirection to nul that fails, or is it the redirection from stderror to stdout (2>&1)?
Your code doesn't set RedirectStandardError to true, you should set this to true and it should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Flex ArgumentError: Error #2015: Invalid BitmapData There is no problem when I complied a Flex project with Flex SDK 4.0 or 4.1. But when I switch to SDK 4.5 (Because our group begins to use flash builder 4.5), I got the error when open a window ( pop up a widget window). I searched online for several days, but still have no clue what caused the problem.
Please help.
Here is the error message:
ArgumentError: Error #2015: Invalid BitmapData.
at flash.display::BitmapData/ctor()
at flash.display::BitmapData()
at spark.effects.supportClasses::AnimateTransitionShaderInstance/play()
at spark.effects.supportClasses::AnimateInstance/startEffect()
at mx.effects::Effect/play()
at mx.core::UIComponent/commitCurrentState()
at mx.core::UIComponent/commitProperties()
at spark.components.supportClasses::GroupBase/commitProperties()
at spark.components::Group/commitProperties()
at mx.core::UIComponent/validateProperties()
at spark.components::Group/validateProperties()
at mx.managers::LayoutManager/validateProperties()
at mx.managers::LayoutManager/doPhasedInstantiation()
at mx.managers::LayoutManager/doPhasedInstantiationCallback()
Here is the mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<!-- host component -->
<fx:Metadata>
[HostComponent("widgets.BatchGeocoder.components.AddressMapper")]
</fx:Metadata>
<!-- SkinParts
name=ddlCityField, type=spark.components.DropDownList, required=true
name=ddlCountryField, type=spark.components.DropDownList, required=true
name=ddlAddressField, type=spark.components.DropDownList, required=true
name=ddlStateField, type=spark.components.DropDownList, required=true
name=ddlZipField, type=spark.components.DropDownList, required=true
name=btnSubmit, type=spark.components.Button, required=true
-->
<s:layout>
<s:VerticalLayout gap="5"
horizontalAlign="center" />
</s:layout>
<s:Group width="100%"
height="100%">
<s:Label x="5"
y="10"
text="Address: " />
<s:DropDownList x="100"
y="5"
id="ddlAddressField"/>
<s:Button x="250"
y="5"
label="x"
fontSize="4"
width="22"
height="22"
toolTip="Reset Address Field"
skinClass="widgets.BatchGeocoder.components.skins.RefreshButtonSkin"
click="ddlAddressField.selectedIndex = -1" />
<s:Label x="5"
y="40"
text="City: " />
<s:DropDownList x="100"
y="35"
id="ddlCityField"/>
<s:Button x="250"
y="35"
label="x"
fontSize="4"
width="22"
height="22"
toolTip="Reset City Field"
skinClass="widgets.BatchGeocoder.components.skins.RefreshButtonSkin"
click="ddlCityField.selectedIndex = -1"/>
<s:Label x="5"
y="70"
text="State: " />
<s:DropDownList x="100"
y="65"
id="ddlStateField"/>
<s:Button x="250"
y="65"
label="x"
fontSize="4"
width="22"
height="22"
toolTip="Reset State Field"
skinClass="widgets.BatchGeocoder.components.skins.RefreshButtonSkin"
click="ddlStateField.selectedIndex = -1" />
<s:Label x="5"
y="100"
text="Zip: " />
<s:DropDownList x="100"
y="95"
id="ddlZipField"/>
<s:Button x="250"
y="95"
label="x"
fontSize="4"
width="22"
height="22"
toolTip="Reset Zip Code Field"
skinClass="widgets.BatchGeocoder.components.skins.RefreshButtonSkin"
click="ddlZipField.selectedIndex = -1" />
<s:Label x="5"
y="130"
text="Country: " />
<s:DropDownList x="100"
y="125"
id="ddlCountryField"/>
<s:Button x="250"
y="125"
label="x"
fontSize="4"
width="22"
height="22"
toolTip="Reset Country Field"
skinClass="widgets.BatchGeocoder.components.skins.RefreshButtonSkin"
click="ddlCountryField.selectedIndex = -1" />
<s:Label x="5"
y="160"
text="Label: " />
<s:DropDownList x="100"
y="155"
id="ddlLabelField"/>
<s:Button x="250"
y="155"
label="x"
fontSize="4"
width="22"
height="22"
toolTip="Reset Label Field"
skinClass="widgets.BatchGeocoder.components.skins.RefreshButtonSkin"
click="ddlLabelField.selectedIndex = -1" />
</s:Group>
<s:Button id="btnSubmit"
label="Done" />
</s:Skin>
---------------------------------------------
Thanks. I do have the skin. the problem is why it works with SDK 4.1, not with SDK 4.5.
Here is the skin definition:
<?xml version="1.0" encoding="utf-8"?>
<s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<!-- host component -->
<fx:Metadata>
[HostComponent("spark.components.Button")]
</fx:Metadata>
<!-- states -->
<s:states>
<s:State name="disabled" />
<s:State name="down" />
<s:State name="over" />
<s:State name="up" />
</s:states>
<!-- SkinParts
name=labelDisplay, type=spark.components.supportClasses.TextBase, required=false
-->
<s:Group id="holder">
<s:BitmapImage source="@Embed('../../assets/images/GenericRefresh16.png')"
source.over="@Embed('../../assets/images/GenericRefresh16_active.png')" />
</s:Group>
<s:transitions>
<s:Transition>
<s:CrossFade target="{holder}" />
</s:Transition>
</s:transitions>
</s:Skin>
Thanks. Unfortunately, it does not work.
But you are right, the crossfade effect caused the problem.I removed the following piece code, and it works.
<s:transitions>
<s:Transition autoReverse="true">
<s:CrossFade target="{holder}"/>
</s:Transition>
</s:transitions>
Any idea. Please help.
A: Seeing from the stack trace, the crossfade effect seems to be the problem. Try this instead :
<s:Group id="holder">
<s:BitmapImage source="@Embed('../../assets/images/GenericRefresh16.png')"
visible.over="false" />
<s:BitmapImage source="@Embed('../../assets/images/GenericRefresh16_active.png')"
visible.over="true" />
</s:Group>
<s:transitions>
<s:Transition autoReverse="true">
<s:CrossFade target="{holder}"/>
</s:Transition>
</s:transitions>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# - Is it possible to make divide-by-zeros return a number, instead of throwing an exception? I have an expression that includes divisions, for which some of the denominators are sometimes zero. However, in those cases I would like that division to result in 1, instead of throwing an exception. Is there any straightforward way about doing this, or am I forced to do some if statements and changing the inputs to the expression to get this desired effect?
A: Although I must question the motives here, if you need to do it, make a function.
double SafeDiv(double num, double denom) {
if(denom == 0) {
return 1;
}
return num/denom;
}
A: You could write a function for dividing. Here's an extension sample idea:
public static float DivideBy(this float toBeDivided, float divideBy){
try
{
return toBeDivided / divideBy;
}
catch(DivideByZeroException)
{
return 1.0;
}
}
A: Since it is not possible to redefine the division operator for built in types, you need to implement your version of division in a function.
A: Something like this?
public T divide<T>(T dividend, T divisor) {
return ((divisor == 0) ? (1) : (dividend / divisor));
}
or perhaps...
public T divide<T>(T dividend, T divisor) {
try {
return dividend / divisor;
}
catch (DivideByZeroException) {
return 1;
}
}
Personally, if you know that the divisor may be 0 in some cases, I wouldn't consider that case "exceptional" and thus use the first approach (which can also, quite conveniently, be inlined manually if you are so inclined).
That said, I agree with what Chris Marasti-Georg wrote, and question the motives for doing this.
A: No. If I understand your question, you would like to change the behavior of the divide operation and have it return 1 instead of throw. There is no way to do that.
A: Check for the denominator first if not equal to zero perform the operation
public double ReturnValueFunction(int denominator, int numerator)
{
try
{
if(denominator!=0)
{
return numerator/ denominator;
/* or your code */
}
else
{
/*your code*/
return someDecimalnumber;
}
}
catch(Exception ex)
{
}
}
A: If either divider or divisor are double and divisor is 0 (or 0.0) result is positive or negative infinity. It will pass through all subsequent operations without throwing, and instead returning ±Infinity or NaN, depending on the other operand. Later you can check if final value is something meaningful.
If it is for some reason necessary to return 1 when dividing by zero, then you have several options:
*
*Custom generic function
*Custom type with overloaded operators
*Check if divisor is 0 before the division
This is not something that is usually done, as far as I know, so you might rethink why would you do that..
A: Maybe you could try this
double res = a / (b == 0 ? a : b);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Qt: Example of QAbstractItemModel implementation using QtSql (to use with QTreeView) I'm looking for an example implementation of QAbstractItemModel to use with QTreeView.
The model should load data from QSqlQuery and should do it in a "lazy" way. In other words I only want to load records for nodes/parents that are open. And I'd like to see how to properly add and remove records from this model.
I tried to implement such model on my own but got a lot of different bugs Especialy when I started adding and removing rows.
If you know where I could find such example I would be very grateful.
Thanks :)
A: To help developping your model, you may be interested in ModelTest (http://developer.qt.nokia.com/wiki/Model_Test)
If I understand correctly, you will only have on child in each first level element.
-Row1
|_ Row1 columns
+Row2
+Row3
-Row4
|_Row4 columns
If so, I'll explain main steps and basic structure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: WordPress admin panel global warning I try to find out how to register a global warning for WordPress administration panel.
I create a plugin that after activation must be enabled, in order to work.
The question not is, how can I create a warning message that will be displayed sidewide in the WordPress admin panel ?
In example.
The plugin X is no yet enabled. Please click here to enable it.
A: There's a WordPress hook for admin_notices.
Put something like the following in your plugin and it will call activation_notice() during the output of the page.
add_action( 'admin_notices', 'activation_notice');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Solr highlight : InvalidTokenOffsetsException I use solr 3.4. When I search a word, I have an InvalidTokenOffsetsException.
My field type look like :
<fieldType name="text" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="1"/>
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
<filter class="solr.ASCIIFoldingFilterFactory"/>
<filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="15" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="1"/>
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
<filter class="solr.ASCIIFoldingFilterFactory"/>
<filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="15" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
When I remove "ASCIIFoldingFilterFactory", it works. It's the same problem with "ISOLatin1AccentFilterFactory".
Anyone have a solution ?
thanks
A: I had the same problem, and reported a bug https://issues.apache.org/jira/browse/LUCENE-3642 – its fixed in trunk right now.
I applied the patch manually and compiled solr my self, worked for both Solr 3.4 and Solr 3.5 although the patch did not apply cleanly and I had to do some manual fixing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to handle server side errors in MVC3 with ajax.beginform I am using Ajax.BeginForm for my page. The client side validation does its work and displays any errors in the validation summary area. Now I want same behaivor when a server side error occurs in the controller.
In a standard form you would AddModelError to the ModelState and return to the form and the fields and validation summary are updated. But with Ajax I can't get this to work.
My controller returns a JsonResult (this may not be the correct way, but I can get my update information back to the form easily) and the first thing I do is check for the ModelState.IsValid. If this is false, how do you get those errors to display on the page in the validation summary?
I return a dictionary collection with the field name and error and call this routine, which is pretty much just taken from jQuery:
function ShowFormErrors(validator, errors)
{
if(errors) {
// add items to error list and map
$.extend( validator.errorMap, errors );
validator.errorList = [];
var curElement;
for ( var name in errors ) {
for( var elm=0; elm<validator.currentElements.length; elm++ )
{
if( validator.currentElements[elm].name == name )
{
curElement = validator.currentElements[elm];
break;
}
}
validator.errorList.push({
message: errors[name],
element: curElement //this.findByName(name)[0]
});
}
// remove items from success list
validator.successList = $.grep( validator.successList, function(element) {
return !(element.name in errors);
});
}
validator.settings.showErrors
? validator.settings.showErrors.call( validator, validator.errorMap, validator.errorList )
: validator.defaultShowErrors();
}
This code works but will never call validator.settings.showErrors because I don't think that showErrors is in validate.unobtrusive.js but is in validate.js.
I ended up setting and clearing the validation summary locally:
function ShowValiationSummaryErrors(validator)
{
var frm = validator.currentForm;
var container = $(frm).find("[data-valmsg-summary=true]"), list = container.find("ul");
if (list && validator.errorList.length) {
list.empty();
container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
$.each(validator.errorList, function () {
$(list).append( $("<li />").html(this.message));
});
}
}
function ClearValidationSummary()
{
var container = $('form').find('[data-valmsg-summary="true"]');
var list = container.find('ul');
if (list && list.length)
{
list.empty();
container.addClass('validation-summary-valid').removeClass('validation-summary-errors');
}
}
A: What would be simple is to have your controller action return a partial view containing the form and then update the DOM by injecting this new contents. This way errors will automatically be shown. If you return JSON you will have to include this information in the JSON string and then manually update the relevant portions to show the errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I map Alt key in Vim? I tried to map <Alt+D> to <Ctrl+D> by adding the below line to .vimrc, but it doesn't work. I checked the .vimrc is loaded by Vim.
map <Alt-D> <C-D>
Is there any error in this mapping?
A: Your terminal might not transmit "properly" the Alt-D. You can use C-V to actually get the actual escape sequence send to Vim and use it to create your mapping. Ie, edit your .vimrc
and replace the actual by typing the following sequence "C-V Alt-D" so you'll have the correct escape sequence in your vimrc. That won't work if your terminal doesn't send anything to vim.
A: :help key-notation describes what format needs to be used to map different keys. In the case of alt, you can use either <A- or <M-. So your mapping would be
map <M-d> <C-d>
I'd also recommend using the nore variant of :map (e.g., noremap) unless you explicitly want to allow the right-hand side to be re-evaluated for mappings.
A: I'm not sure is "possible" anymore. Please read the update below.
Yes, you can even in terminal vim, but there's no real catch all answer. You basically have to follow two steps:
*
*Make sure the <M-d> notation exists, and map exactly what your terminal inputs (^[ is the escape character):
$ cat
^[d
$
" in your .vimrc
execute "set <M-d>=\ed"
" you have to use double quotes!
*Map something to your newly "created" combination:
noremap <M-d> :echo "m-d works!"<cr>
Understanding how it works, you can expand this "trick" to other "strange" combinations, for instance, I'm using termite, and vim doesn't recognize <S-F1>, using cat I get ^[[1;2P. Then, in my vimrc I do: execute "set <S-F1>=\e[1;2P", and then I can map it to anything.
Note: I don't know why, but for some people using \<Esc> works instead of \e.
Update (february 2016)
Depending on the terminfo your terminal runs, maybe you could... in most terminals, "alt + h", for example, is mapped to ^[h, which is: "escape + h". So it could overwrite keys. I've just tried (again) and it seems to work, but I believe it's a very buggy and error prone implementation.
Nevertheless, for the brave enough, here's an experimental plugin:
*
*https://github.com/vim-utils/vim-alt-mappings
*https://github.com/drmikehenry/vim-fixkey
A: Find out key mapping by putting following command in your vim editor
:help key-notation
It will display all the key mapping.
In my ubuntu system for Alt it is <M-...>. It is possible for your version mapping might be different. If you too have same mapping then following should work.
map <M-D> <C-D>
A: Map Alt Key in Vim on Mac OSx:
Start by viewing the key code your terminal is sending to vim:
$ sed -n l
^[[1;9D
In the above example, I ran the command and pressed Alt + Left.
The ^[[1;9D is the escaped sequence being sent to vim, so we can user that for our mapping.
map <Esc>[1;9D
A: To Mac users out there: for mapping ALT+hjkl, use instead the real character generated (find out which character using the combination while in INSERT mode), for example with my keyboard I get:
<ALT+j> ==> ª
<ALT+k> ==> º
and so on.
Solution found here on StackOverflow.
I used this to move lines up and down with ALT+k\j, using this on my .vimrc:
nnoremap ª :m .+1<CR>==
nnoremap º :m .-2<CR>==
inoremap ª <Esc>:m .+1<CR>==gi
inoremap º <Esc>:m .-2<CR>==gi
vnoremap ª :m '>+1<CR>gv=gv
vnoremap º :m '<-2<CR>gv=gv
as explained here.
Hope it's useful, enjoy Vim :)
ADDENDUM BY Dylan_Larkin (2019): For this to work on a Mac, "Use Option as Meta Key" must be turned OFF in Terminal->Preferences->Keyboard
UPDATE 09/2021
I recently switched from a "British" keyboard to "ABC - Extended" and noticed this configuration doesn't work as expected.
As an alternative, I mapped the <up> and <down> keys to do the same operation (which, I guess, also solves most of the complexity explained in other answers of this very question):
nnoremap <down> :m .+1<CR>==
nnoremap <up> :m .-2<CR>==
inoremap <down> <Esc>:m .+1<CR>==gi
inoremap <up> <Esc>:m .-2<CR>==gi
vnoremap <down> :m '>+1<CR>gv=gv
vnoremap <up> :m '<-2<CR>gv=gv
This is also a great way for beginners to rewire the habit of using the arrows and instead learn the much more efficient Vim motion way to move around the code. ;)
You can complete your transition mapping <left> and <right> to quickly move between tabs with:
nnoremap <left> gT
nnoremap <right> gt
Or whatever you fancy (even a brutal <NOP>, like I did at the beginning of my journey).
A: Use:
map <A-D> <C-D>
See :help key-notation.
A: My Terminal would produce ^[x commands (e.g. for alt-x). What got it to work inside Vim was this small script from vim.wikia.com:
for i in range(97,122)
let c = nr2char(i)
exec "map \e".c." <M-".c.">"
exec "map! \e".c." <M-".c.">"
endfor
Add to .vimrc to fix all alt key mappings.
A: as a follow up to Bruno's answer for Mac users, try making sure your option key is mapped to Esc+.
This will give you the "normal" behavior of the option (A) key in Vim.
For example, in iterm2, this option can be found under Preferences > Profiles > Keys:
A: Hello after no good solution after years of testing all the above on mac, I kept searching.
Here is my solution:
To create a combination keystroke including Alt you have to declare the combination in the preference > keyboard and use that combination in the vim setup file (check use option as meta key).
The output must be an unusual character (no a for example) so that you're not overriding a regular character.
In the example below you should be able to quite vim with ALT-Up.
vim setting:
mac setting:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "108"
} |
Q: calling asmx from server side I wrote an asmx service on one server1 and and asp.net/c# on another server2.
I want to transfer a dictionary<string,string> from srv1 to srv2.
I read Dictionary is not serializable and should be sent as List<KeyValuePair<string,string>>.
on srv2 I try to read the result but it's of type:
KeyValuePairOfStringString[] result = response.GetTemplatesParamsPerCtidResult;
i try to retrieve the key,value but cannot unflat each element:
foreach (var pair in result)
{
// pair has just 4 generic methods: toString, GetHashCode,GetType,Equals
}
How do I do this? Is there anything I should change in my implementation?
TIA
A: How about using an array MyModel[] where MyModel looks like this:
public class MyModel
{
public string Key { get; set; }
public string Value { get; set; }
}
Generics should be avoiding when exposing SOAP web services.
A: XmlSerializer won't serialize objects that implement IDictionary by default.
One way around this is to write a new class that wraps an IDictionary object and copies the values into an array of serializable objects.
So you can write a class like that :
public class DictionarySerializer : IXmlSerializable
{
const string NS = "http://www.develop.com/xml/serialization";
public IDictionary dictionary;
public DictionarySerializer()
{
dictionary = new Hashtable();
}
public DictionarySerializer(IDictionary dictionary)
{
this.dictionary = dictionary;
}
public void WriteXml(XmlWriter w)
{
w.WriteStartElement("dictionary", NS);
foreach (object key in dictionary.Keys)
{
object value = dictionary[key];
w.WriteStartElement("item", NS);
w.WriteElementString("key", NS, key.ToString());
w.WriteElementString("value", NS, value.ToString());
w.WriteEndElement();
}
w.WriteEndElement();
}
public void ReadXml(XmlReader r)
{
r.Read(); // move past container
r.ReadStartElement("dictionary");
while (r.NodeType != XmlNodeType.EndElement)
{
r.ReadStartElement("item", NS);
string key = r.ReadElementString("key", NS);
string value = r.ReadElementString("value", NS);
r.ReadEndElement();
r.MoveToContent();
dictionary.Add(key, value);
}
}
public System.Xml.Schema.XmlSchema GetSchema()
{
return LoadSchema();
}
}
You then create your webservice method with this return type.
[WebMethod]
public DictionarySerializer GetHashTable()
{
Hashtable ht = new Hashtable();
ht.Add(1, "Aaron");
ht.Add(2, "Monica");
ht.Add(3, "Michelle");
return new DictionarySerializer (h1);
}
If you need more information, the paper contain some information about this technic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MongoDB not that faster than MySQL? I discovered mongodb some months ago,and after reading this post, I thought mongodb was really faster than mysql, so I decided to build my own bench, the problem is that I do not have the same result than the above post's author, especially for quering the database : mongodb seems to be slower than MyISAM tables. Could you have a look to my python code, may be there is something wrong in it :
from datetime import datetime
import random
import MySQLdb
import pymongo
mysql_db=MySQLdb.connect(user="me",passwd="mypasswd",db="test_kv")
c=mysql_db.cursor()
connection = pymongo.Connection()
mongo_db = connection.test
kvtab = mongo_db.kvtab
nb=1000000
thelist=[]
for i in xrange(nb):
thelist.append((str(random.random()),str(random.random())))
t1=datetime.now()
for k,v in thelist:
c.execute("INSERT INTO key_val_tab (k,v) VALUES ('" + k + "','" + v + "')")
dt=datetime.now() - t1
print 'MySQL insert elapse :',dt
t1=datetime.now()
for i in xrange(nb):
c.execute("select * FROM key_val_tab WHERE k='" + random.choice(thelist)[0] + "'")
result=c.fetchone()
dt=datetime.now() - t1
print 'MySQL select elapse :',dt
t1=datetime.now()
for k,v in thelist:
kvtab.insert({"key":k,"value":v})
dt=datetime.now() - t1
print 'Mongodb insert elapse :',dt
kvtab.ensure_index('key')
t1=datetime.now()
for i in xrange(nb):
result=kvtab.find_one({"key":random.choice(thelist)[0]})
dt=datetime.now() - t1
print 'Mongodb select elapse :',dt
Notes:
*
*both MySQL and mongodb are on locahost.
*both MySQL and mongodb has the 'key' column indexed
MySQL Table:
CREATE TABLE IF NOT EXISTS `key_val_tab` (
`k` varchar(24) NOT NULL,
`v` varchar(24) NOT NULL,
KEY `kindex` (`k`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Versions are:
*
*MySQL: 5.1.41
*mongodb : 1.8.3
*python : 2.6.5
*pymongo : 2.0.1
*Linux : Ubuntu 2.6.32 32Bits with PAE
*Hardware : Desktop core i7 2.93 Ghz
Results (for 1 million inserts/selects) :
MySQL insert elapse : 0:02:52.143803
MySQL select elapse : 0:04:43.675914
Mongodb insert elapse : 0:00:49.038416 -> mongodb much faster for insert
Mongodb select elapse : 0:05:10.409025 -> ...but slower for quering (thought was the opposite)
A: MySQL insert elapse : 0:02:52.143803
Mongodb insert elapse : 0:00:49.038416 -> mongodb much faster for insert
Mongodb inserts much faster because of mongodb insert all data into ram and then periodically flush data to the disc.
MySQL select elapse : 0:04:43.675914
Mongodb select elapse : 0:05:10.409025 -> ...but slower for quering (thought was
You can achieve best performance with mongodb when you will embedd/denormalize your data. In many situation mongodb allow us to avoid joins because of embedding/denormalization.
And when you just inserting data into one collection/table and reading back by index mongodb not supposed to be faster, read speed should be ~ same if compare with sql database.
BTW: In mongodb 2.0 indexes 25% faster, so i guess 2.0 will work faster then mysql.
A: Sigh. These kind of benchmarks, and I use the term loosely in this case, usually break down from the very start. MySQL isn't a "slower" database than MongoDB. One is a relational database, the other a NoSQL document store. They will/should be faster in the functional areas that they were designed to cover. In the case of MySQL (or any RDBMS) and MongoDB this overlap isn't as big as a lot of people assume it is. It's the same kind of broken apples and oranges comparison you get with Redis vs. MongoDB discussions.
There are so many variables (app functional requirements, hardware resources, concurrency, configuration, scalability, etc.) to consider that any benchmark or article that ends with "MongoDB is faster than MySQL" or vice versa is generalizing results to the point of uselessness.
If you want to do benchmark first define a strict set of functional requirements and business rules and then implement them as efficiently as possible on both persistence solutions. The result will be that one is faster than the other and in almost all cases the faster approach has some relevant downsides that might still make the slower solution more viable depending on requirements.
All this is ignoring that the benchmark above doesn't simulate any sort of real world scenario. There wont be a lot of apps doing max throughput inserts without any sort of threading/concurrency (which impacts performance on most storage solutions significantly).
Finally, comparing inserts like this is a little broken too. MongoDB can achieve amazing insert throughput with fire and forget bulk inserts or can be orders of magnitude slower with fsynced, replicated writes. The thing here is that MongoDB offers you a choice where MySQL doesn't (or less so). So here the comparison only make sense of the business requirements allow for fire and forget type writes (Which boil down to, "I hope it works, but no biggy if it didn't")
TL;DR stop doing simple throughput benchmarks. They're almost always useless.
A: It's wrong to look at python execution time and estimate database quality. Each request consist of at least 3 parts:
*
*request preparing (client side),
*request execution (server),
*response preparing (client side)
By my experience data convertion for MongoDB=>python takes much more time than for MySQL=>python.
Also you should use indexes in both databases. MongoDB works good only if you have indexes on fields that you use for queries.
Talking about MySQL, I think it's better to test performance on innoDB, MyISAM doesn't support transactions, foreign keys, triggers and as for me it's a little bit outdated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: how to get event of on completion of youtube video in android webview I was able to play youtube video on WebView. I want to finish/close/destroy the WebView automatically when youtube video is completed.
here is my code:
WebView engine = new WebView(this);
engine.getSettings().setJavaScriptEnabled(true);
engine.getSettings().setPluginsEnabled(true);
engine.loadUrl("http://www.youtube.com/embed/bIPcobKMB94?autoplay=1&rel=0&loop=0");//&enablejsapi=1");
setContentView(engine);
Actually I was trying to play songs (audio/video) from the playlist when audio is there in playlist it played in my custom player and when youtube video is there is played in WebView and songs are playing one after another automatically onCompletion. Youtube video played in WebView but after the completion of video, webview still open (not going to be destroy/finish). How could I finish WebView and get back to previous activity?
A: Android's webview implementation hides the underlying MediaPlayer related APIs and callbacks. The only situation when the application comes into picture is when a user tries to go full screen (clicking on full screen icon in video embedded in WebView). In this case, onShowCustomView() is called back provided the application has implemented and registered a WebChromeClient callback. There is no way for you to know when a video has finished playing inside a webview.
I know this isn't what you asked: but why not use the youtube app by dispatching an intent to play the url? You can use the startActivityForResult() method which will call back your onActivityFinished() API (you have to implement this callback) with a result code. Will this not work for you?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Multiperson team with multiple NuGet package sources and prebuild events fail I am currently working on a multiperson team and we have recently starting using NuGet. Our projects are setup with a prebuild event so that each person keeps in sycn and we keep the packages out of source control. This has worked well.
"$(SolutionDir)nuget" install "$(ProjectDir)packages.config" -o "$(SolutionDir)Packages"
We recently have setup an internal network drive for hosting company specific packages. I added the network location to my package sources. I am able to create the package and reference it fine.
When a team member adds the internal package source and does a build they get the "this command exited with code1." error and the package contents from the local packages are not copied over.
I saw this question, Multiperson team using NuGet and Source Control, and tried to add the -source option but the error still exists.
Looking at packages.config, it doesn't seem to specify which package source a package came from.
What do we need to do in order to effectively use multiple package sources in a mutliperson environment?
A: Try upgrading to using the new workflow. It doesn't use prebuild events but it give the same net effect. It will also show the actual error message (if there's any). You can also specify sources to use for restore in the targets file used by this technique.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NSTimer issue in Objective-C I am working on a Kid's Book App for iPad. It has a UIView which loads UIImageView to display UIImages (JPEG's), user can swipe on images to browse through pages. I have also added some interactivity to some of the pages by adding another UIImageView which would load a PNG file and on Tap Gesture I animate them. One one of the pages I have an animation of leaf's falling on the screen (page 10) and I am using NSTimer for this, it works fine, however when I swipe and move to next page, the animation is still happening. I want the animation to run ONLY on page 10 and should stop immediately if I move to page 9 (backward swipe) or page 11 (forward swipe). I tried to put a condition (if (pageNum == 10)) and it stops after few seconds, so I can still see few leafs falling on previous/forward pages. I guess I understand why its happening but don't know how to fix it. Below is the code snippet:
- (void)handleTap:(UITapGestureRecognizer *)recognizer {
NSLog(@"ChildrenBookViewController ==> handleTap.");
switch (((UIGestureRecognizer *)recognizer).view.tag)
{
case 1:
//Some animation for Page 1
break;
case 2:
//Some animation for Page 2
break;
//....
case 10:
// load our leaf image we will use the same image over and over
leafImage = [UIImage imageNamed:@"leaf_small.png"];
// start a timet that will fire 20 times per second
timer = [NSTimer scheduledTimerWithTimeInterval:(0.05) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
break;
case 11:
//Some animation for Page 11
break;
default:
NSLog(@"ChildrenBookViewController ==> handleTap. Switch Case: DEFAULT");
break;
}
}
// Timer event is called whenever the timer fires
- (void)onTimer
{
if (pageNum == 10)
{
// build a view from our leaf image
UIImageView* leafView = [[UIImageView alloc] initWithImage:leafImage];
// use the random() function to randomize up our leaf attributes
int startX = round(random() % 1024);
int endX = round(random() % 1024);
double scale = 1 / round(random() % 100) + 1.0;
double speed = 1 / round(random() % 100) + 1.0;
// set the leaf start position
leafView.frame = CGRectMake(startX, -100.0, 25.0 * scale, 25.0 * scale);
//leafView.alpha = 0.25;
// put the leaf in our main view
[self.view addSubview:leafView];
[UIView beginAnimations:nil context:leafView];
// set up how fast the leaf will fall
[UIView setAnimationDuration:5 * speed];
// set the postion where leaf will move to
leafView.frame = CGRectMake(endX, 500.0, 25.0 * scale, 25.0 * scale);
// set a stop callback so we can cleanup the leaf when it reaches the
// end of its animation
[UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
}else{
if (timer) {
[timer invalidate];
timer = nil;
}
}
}
- (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
UIImageView *leafView = context;
[leafView removeFromSuperview];
[leafView release];
}
A: Instead of invalidating your timer in onTimer method, you should invalidate it in the callback you set for the swipe gesture (changing pages) page 9 and 11 cases. That way the timer will be invalidated as soon as the user swipes to switch pages.
EDIT: As @Alex noticed, this will only stop requesting more animations, but the already running will continue... I assume you have a reference to leafView so, you should call
[leafView.layer removeAllAnimations] and then remove it from superview or hide it or whatever you want...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there an OpenID library for python which supports UI extensions? I'm using the python openid library available here:
https://github.com/openid/python-openid
I would like to use the UI extensions to OpenID to
ensure that the authentication process is performed via
a popup rather than redirection to the provider's site.
However, the above library does not seem to have support
for the extensions built in - has anyone added support
for the UI extensions to this library?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remote Git daemon immediately disconnects my client on a "git pull" I am attempting to do a simple
$git pull
From my remote master repository. When I do so, the command just hangs and never does anything, no timeout, no errors -- just waiting silently.
Meanwhile, on the remote system, I can watch my daemon do this:
[30395] Connection from 192.168.1.203:55260
[30395] Extended attributes (20 bytes) exist <host=192.168.1.125>
[30395] Request upload-pack for '/staging.git'
[30386] [30395] Disconnected
The Disconnected happens very quickly. But again, there is no error or reaction of any kind on my side.
Now, on my machine I was easily able to clone a new copy of my remote master. And from that new clone I can do a git pull without any problem.
So, what might be going on here? How can I troubleshoot this behavior?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create XML dynamically talking the data from UI i have a requirement in which i need to create an XML from the data entered by the user. i need to perform this task in Java. the number of data fields can vary depending on user requirement. I have designed the dynamic UI using JSPs and Javascript but i m not getting how to save the data into XML and then pass on to the server.
A: depends on where do you want the form data to be converted into XML. As you say, it has to happen in Java, I think you pretty much mean the conversion has to happen on server side.
i m not getting how to save the data into XML and then pass on to the server.
why do you need to convert it to xml on client side then?
Anyways, you can easily get the Form data at server side and convert it to xml using XStream , JAXB or using simple
You can look at this SO QA for further details: XML serialization in Java?
A: You might want to look into JAXB. If you have a defined XML schema it will automatically create java classes that will easily allow you to 'marshal' (move data from java -> XML) and much much more. It's incredibly useful!
http://jaxb.java.net/
A: You can use a function that creates the xml before sending.
each time the user completes a field, the function is called and adds an entry into the xml string.
At the end, when the user clicks submit, it wraps the xml entries into start/end tags and send the created xml text to the server.
OPTION2. You can transform the form elements into JSON and convert json object into xml. I guess there should be some functions that do that.
OPTION3. Send the user raw data to the server, and let the server create the xml based on what was received.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add stylecop check as a pre-build action to VS2010? In our project we have added StyleCop task to be executed after each commit by continuous integration server. The problem is that build often breaks because someone forgets to run Stylecop before commiting code to repository.
The solution will be to execute StyleCop before each VS2010 build. How can I do it?
Maybe it is possible to execute pre-build action per whole solution?
A: It seems you could use MSBuild integration (look here or here), which will make StyleCop checking a part of a build process.
Or you could use some sort of "commit policies" which run StyleCop during the commit and reject the commit if StyleCop checking is not passed. For example, here is one for TFS.
A: If you are SyleCop rule for all project in local or your teams ?
Hook MSBuild script !!
*
*Make folder in %ProgramFiles%\MSBuild\v4.0
v4.0 folder name is your .net framework.
ie.
v3.5 for .net framework 3.5
v4.0 for between 4.0 and 4.5...
*then make "Custom.After.Microsoft.Common.targets" and "Custom.Before.Microsoft.Common.targets"
my experience was "Custom.Before.Microsoft.Common.targets" was not working well.
*In "Custom.After.Microsoft.Common.targets" file contained under code
then StyleCop analysis before CoreCompile
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<CI_StyleCopPath>$(MSBuildExtensionsPath)\StyleCop\v4.7</CI_StyleCopPath>
<StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
</PropertyGroup>
<Import Project="$(CI_StyleCopPath)\StyleCop.targets"
Condition=" Exists('$(CI_StyleCopPath)\StyleCop.targets') "/>
<!-- Analysis with StyleCop before build -->
<PropertyGroup>
<BuildDependsOn>
StyleCop; <!-- StyleCop.targets -->
$(BuildDependsOn);
</BuildDependsOn>
</PropertyGroup>
</Project>
See my blog but contents are Korean ;-)
http://xyz37.blog.me/50053407359
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: File upload with other form fields(Like Text inputs) in struts 1.3 I am trying to upload an Excel file onto my server. There is one more form field which I need, the Sheet Name. Now i have to use the org.apache.struts.upload to do this. But i am not able to figure out how i am going to extract the Sheet name text field since i cannot directly access request parameters on the multipart/form-data enctype.
Thanks in advance.
A: You shouldn't be accessing request parameters directly in Struts 1, you should be using the ActionForm to encapsulate form values. All form values are available.
If you're not sure how to use the action form, here's a tutorial.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what standard says about static casting to temporary inheritor? sometimes (quite rarely) I need to get protected members from existing variables
like this:
struct S {
protected:
int i;
};
struct T : S {
using S::i;
};
int main() {
S s;
static_cast<T&>(s).i = 0;
}
I'm almost sure this ( static_cast(s) ) is UB, but is someone know what the C++ standard (2003) says about this situation?
A: This type of operation is actually the basis for implementing the constant reoccurring template pattern, where inside the base-class you actually static_cast the this pointer of the base-class to the derived-class template type. Since S is an unambiguous base class of T, and you are not accessing any members from the static_cast that are not already members of S, I don't see why you would encounter any issues.
Section 5.2.8 on static casting in paragraph 5 states:
An lvalue of type “cv1 B”, where B is a class type, can be cast to type “reference to cv2 D”, where D is a class derived (clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is not a virtual base class of D. The result is an lvalue of type “cv2 D.” If the lvalue of type “cv1 B” is actually a sub-object of an object of type D, the lvalue refers to the enclosing object of type D. Otherwise, the result of the cast is undefined.
You seem to be meeting all the requirements that avoid undefined behavior. That is:
*
*Class T is derived from S
*A pointer conversion from S to T does exist since S is both accessible and an unambiguous base-class of T (requirements from 4.10)
*You are using the same constant-value-qualification for both types
*S is not a virtual base-class of T
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Scraping non html-websites with R? Scraping data from html tables from html websites is cool and easy. However, how can I do this task if the website is not written in html and requires a browser to show the relevant information, e.g. if it's an asp website or the data is not in the code but comes in through java code?
Like it is here: http://www.bwea.com/ukwed/construction.asp.
With VBA for excel one can write a function that opens and IE session calling the website and then basically copy and pasting the content of the website. Any chance to do something similar with R?
A: This is normal HTML, with the associated normal trouble of having to clean up after scraping the data.
The following does the trick:
*
*Read the page with readHTMLTable in package XML
*It's the fifth table on the page, so extract the fifth element
*Take the first row and assign it to the names of the table
*Delete the first row
The code:
x <- readHTMLTable("http://www.bwea.com/ukwed/construction.asp",
as.data.frame=TRUE, stringsAsFactors=FALSE)
dat <- x[[5]]
names(dat) <- unname(unlist(dat[1, ]))
The resulting data:
dat <- dat[-1, ]
'data.frame': 39 obs. of 10 variables:
$ Date : chr "September 2011" "August 2011" "August 2011" "August 2011" ...
$ Wind farm : chr "Baillie Wind farm - Bardnaheigh Farm" "Mains of Hatton" "Coultas Farm" "White Mill (Coldham ext)" ...
$ Location : chr "Highland" "Aberdeenshire" "Nottinghamshire" "Cambridgeshire" ...
$ Power(MW) : chr "2.5" "0.8" "0.33" "2" ...
$ Turbines : chr "21" "3" "1" "7" ...
$ MW Capacity : chr "52.5" "2.4" "0.33" "14" ...
$ Annual homes equiv*.: chr "29355" "1342" "185" "7828" ...
$ Developer : chr "Baillie" "Eco2" "" "COOP" ...
$ Latitude : chr "58 02 52N" "57 28 11N" "53 04 33N" "52 35 47N" ...
$ Longitude : chr "04 07 40W" "02 30 32W" "01 18 16W" "00 07 41E" ...
A: That site just delivers HTML, as Thomas comments. Some sites use JavaScript to get values via an AJAX call and insert them into the document dynamically - those won't work via a simple scraping. The trick with those is to use a JavaScript debugger to see what the AJAX calls are and reverse engineer them from the Request and Response.
The hardest thing will be sites driven by Java Applets, but thankfully these are rare. These could be getting their data via just about any network mechanism, and you'd have to reverse engineer all that by inspecting network traffic.
Even IE/VBA will fail if its a Java applet, I reckon.
Also, don't confuse java and JavaScript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: CKEditor loop only works on the last instance I'm trying to set a focus event on all my CKEditor textareas on the page. Here's the code that loads on jQuery document ready:
for (var i in CKEDITOR.instances) {
alert(CKEDITOR.instances[i].name);
CKEDITOR.instances[i].on('focus', function() {
alert(CKEDITOR.instances[i].name);
remove_invalidation(CKEDITOR.instances[i].name);
});
}
(Note: remove_invalidation() is a function I wrote that just removes some CSS formatting on the textarea. It shouldn't affect the problem.)
I added a couple alerts to see what was happening. So, right away, as expected, when the document ready event kicks off this code, I get one textarea after another with the names of each of the CKEditor textareas. That works.
But, when I click inside any of the textareas to give them focus, the alert always pops up the name of the last textarea on the page.
A: try this:
for (var i in CKEDITOR.instances) {
(function(i){
alert(CKEDITOR.instances[i].name);
CKEDITOR.instances[i].on('focus', function() {
alert(CKEDITOR.instances[i].name);
remove_invalidation(CKEDITOR.instances[i].name);
});
})(i);
}
the issue was you are using the same i within each on focus event, and that i was getting incremented to the value for the last editor. Placing the code within an immediately executing function solves this problem by giving the code it's own scope.
A: Paraphrasing the MDN article Closures (section "Creating closures in loops: A common mistake"):
A number of closures have been created by the loop, but each one shares the
same single lexical environment, which has a variable with changing
values (i). The value of i is determined when the
on('focus') callbacks are executed. Because the loop has already run its
course by that time, the i variable (shared by all
closures) has been left pointing to the last entry in the CKEDITOR.instances
list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: "Invalid Default Value" mssql to MySql migration tool hi i got "Invalid Default Value for "BarcodeAppID" " when convervting a MsSQL database to MySQL, im new to both so im wondering what MySQL Isn't Supporting syntax wise ?
Thanks
DROP TABLE IF EXISTS `InfoCentre_dbo`.`BrowserBarcodes`;
CREATE TABLE `InfoCentre_dbo`.`BrowserBarcodes` (
`BarcodeAppID` INT(10) NOT NULL DEFAULT null,
`BrowserAppID` INT(10) NOT NULL DEFAULT null,
`BarcodeReaderPort` INT(10) NOT NULL,
`SilverLightServerListeningPort` INT(10) NOT NULL DEFAULT 0,
PRIMARY KEY (`BarcodeAppID`)
)
ENGINE = INNODB;
A: Try using
DEFAULT 0
instead of DEFAULT null.
A: Well, you try to create a field that can't be NULL and you try to set it as NULL :/ !
You have to change your default value or authorized the field to be NULL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I relate an existing Mercurial and git repositories using hg-git? This is a pretty esoteric question, so just to make clear here from the start: I am not talking about converting from svn to git, git to mercurial, or mercurial to git. I am talking about a complex situation that has arisen from taking advantage of "cross-system" plugins that allow Mercurial to interoperate, to some extent, with git and SVN.
For some time I have used the hg-subversion plugin to Mercurial to "track" an upstream SVN repository on code.google.com. Thanks to this plugin, Mercurial considers the repository to be "related" and is able to pull in just changes that have occurred since I last pulled from the repo. This allows me to maintain my own, private Mercurial repository that includes private changesets, branches, tags, etc., but which periodically syncs up and merges with the changes that have been occurring on the upstream SVN repo.
The upstream repo has moved, cleanly, from SVN to git. When I say cleanly, I mean they have taken with them the entire commit tree, or at least the part affecting the default/master branch that I care about.
I am now in a situation where I have a Mercurial repository that is up-to-date merged with the very last checkin on the now-defunct SVN repository, and I want to start pulling in changes from the new upstream git repository, starting at the change that occurred just after the svn repository was moved to github.
I can use the wonderful hg-git plugin to pull changes from this repository, but as the current repository has no notion of being "related" to the git upstream repo, it will pull ALL changes, including all the changes whose mirror-image changesets are already present in my repository.
So what I'm looking for is advice for how I can get my Mercurial repository to consider itself, via hg-git, related to the upstream git repository, and also consider all the appropriate commits from the git repository as "already pulled" for purposes of maintaining changeset parity.
I see that internally hg-git appears to use a file .hg/git-mapfile which I presume maps changesets between the upstream git and the local Mercurial repository. This is probably a clue.
What's the easiest way to get my local Mercurial repository into such a state where it essentially behaves as though it started as a clone of the upstream git repository, but maintains all of my own unrelated changesets that have been added over time?
(Note: I would prefer not to "start over" with a fresh clone, and then applying my private changes, because I want to maintain the historical integrity of this repository for my own build/debugging purposes).
A: I have done something similar with git before. In the git->git case I was able to do a git-merge --strategy=ours which basically made my current repository believe that everything that was being merged in was a no-op.
What you need to do that is a branch that represents everything upstream that you know is already merged into your tree and then do a no-op style of merge into your tree then start pulling in changes with "real" merges.
From this site:
https://www.mercurial-scm.org/wiki/TipsAndTricks#Keep_.22My.22_or_.22Their.22_files_when_doing_a_merge
I see that a command like the following may be able to help you merge in the upstream repository and ignore everything upstream:
$ hg --config ui.merge=internal:local merge #keep my files
That should allow you to re-sync your downstream with upstream.
A: I would clone the new upstream repository with Hg-git, then try to use the Convert extension to splice all the changes in the old local repository into the new one. In fact, I'd probably clone the local Hg-git repository into a native Mercurial repository and use a two-step pull from the upstream Git repository.
A: If no existing solution exists, I suppose one could write a script that patches and commits your changes to a new repository that is based on the git-clone instead. You "just" need to correlate the svn versions between hg-git-fromsvn and hg-svn, and replicate the update/patch/commit/merge sequence you've done on a new repo.
A fun project, to whomever does it. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Exchange 2010 Powershell + C#: how to do WHERE query I'm using the exchange powershell in C# like this:
public PowershellResult GetSendAsPermissions(string TargetIdentity)
{
string CommandName = "get-adpermission";
Command cmd1 = new Command(CommandName);
cmd1.Parameters.Add("Identity", TargetIdentity);
if (powershell.DomainController.Length > 0)
{
cmd1.Parameters.Add("DomainController", powershell.DomainController);
}
List<Command> commands = new List<Command>();
commands.Add(cmd1);
string errorMessages = string.Empty;
Collection<PSObject> commandResults = powershell.ExecutePowershellCommand(commands, out errorMessages);
PowershellResult psr = null;
if (errorMessages.Length == 0)
{
psr = new PowershellResult(true, "Successfully managed SendAs permission.", 0);
}
else
{
psr = new PowershellResult(false, string.Format("Error managing SendAs permission: {0}", errorMessages), 0);
}
return psr;
}
public Collection<PSObject> ExecutePowershellCommand(List<Command> commands, out string errorMessages)
{
errorMessages = "";
this.ps.Commands.Clear();
ps.Streams.Error.Clear();
if (commands != null)
{
foreach (Command cmd in commands)
{
this.ps.Commands.AddCommand(cmd);
}
Collection<PSObject> ret = null;
try
{
ret = this.ps.Invoke();
if (this.ps.Streams.Error.Count > 0)
{
StringBuilder stb = new StringBuilder();
foreach (ErrorRecord err in this.ps.Streams.Error)
{
if (err.Exception.Message != null)
{
stb.AppendLine(err.Exception.Message);
}
}
errorMessages = stb.ToString();
}
}
catch (Exception ex)
{
StringBuilder stb = new StringBuilder();
if (ex.Message != null)
{
stb.Append(ex.Message);
}
if (ex.InnerException != null)
{
if (ex.InnerException.Message != null)
{
stb.Append(string.Format(" {0}", ex.InnerException));
}
}
errorMessages = stb.ToString().Trim();
}
return ret;
}
else
{
return null;
}
}
Now I want to to add a "where" clause to the get-adpermission command like this:
Get-ADPermission | where {($_.ExtendedRights -like “*Send-As*”) -and ($_.IsInherited -eq $false) -and -not ($_.User -like “NT AUTHORITY\SELF”)}
I have absolutely no idea where to put the where clause or how to define those arguments in curly brackets. Anyone got an idea?
A: I see
Collection<PSObject> commandResults = powershell.ExecutePowershellCommand(commands, out errorMessages);
but nothing is done with commandResults - they're not passed back to the caller.
What it looks like you'll need is something like
var filteredResults = commandResults.Where(cr =>
(((string)cr.Properties["ExtendedRights"].Value).Contains("Send-As")) &&
(((bool)cr.Properties["IsInherited"].Value) == false) &&
(((string)cr.Properties["User"].Value) == "NT AUTHORITY\\SELF"))
That will (hopefully) get you a filtered list of comandResults with just the items you need. You'll want to pass that back to the caller somehow, or do something else with them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do i read information from java debugger (or any other method) Hi guys i would like to do something that sounds simple enough. but i have no idea where to start looking.
i have search Google a bit and haven't found anything related to what i want to do.
what i want to do is run a java application in debug, and print out the lines of code that run in the debugging process.
same as with going through code step by step, each step will print the line of code it stepped into.
i really have no idea where to start looking of how to so this. can someone help in giving me a direction.
thank you.
this is following another question (maybe i wasn't clear enough last time and didn't get a response)
https://stackoverflow.com/questions/5506367/is-there-a-way-to-tap-into-eclipse-debugger-with-an-addon
A: What you describe sounds pretty similar to what the Eclipse code coverage tool EclEmma offers. It shows you exactly which code is executed during the process it is monitoring.
It sounds like there is a problem you are trying to solve with your proposed solution though. What is the underlying problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AES encryption for .NET, Java (android) and iOS Using the example from this post Encryption compatible between Android and C#, I have successfully implemented AES encryption between a .NET application that provides XML feeds to my Android application.
Now, I am trying to use this same implementation for the iOS version of that app. I have found some really good examples of AES for iOS, but so far, none seem to match the scheme that I am currently using. From what I can tell, the problem is the 16-byte key that is shared between C# and Java (rawSecretKey). In the iOS examples, I've not been able to find a similar key to set with this same byte array. It has the passPhrase, but not the byte array.
If anyone knows of a good example that illustrates this type of implementation, it would be very helpful. One iOS example I found was http://dotmac.rationalmind.net/2009/02/aes-interoperability-between-net-and-iphone/, but again, I don't see how to include the 16-byte array as referenced in the first link at the top of my post.
A: .Net and IOS both support PKCS7Padding, but Java doesn't (unless use some third-party library)
.Net and Java both support ISO10126Padding, but IOS doesn't (unless use some third-patry library)
So I think you need to have separate .net encryption code for IOS and Java.
Here are some code examples:
for IOS:
+ (NSData*)encryptData:(NSData*)data :(NSData*)key :(NSData*)iv
{
size_t bufferSize = [data length]*2;
void *buffer = malloc(bufferSize);
size_t encryptedSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[key bytes], [key length], [iv bytes], [data bytes], [data length],
buffer, bufferSize, &encryptedSize);
if (cryptStatus == kCCSuccess)
return [NSData dataWithBytesNoCopy:buffer length:encryptedSize];
else
free(buffer);
return NULL;
}
for .NET:
public static byte[] AesEncrypt(byte[] bytes, byte[] key, byte[] iv)
{
if (bytes == null || bytes.Length == 0 || key == null || key.Length == 0 || iv == null || iv.Length == 0)
throw new ArgumentNullException();
using (var memoryStream = new MemoryStream())
{
using (var rijndaelManaged = new RijndaelManaged { Key = key, IV = iv, Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC })
{
using (var cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
cryptoStream.Write(bytes, 0, bytes.Length);
}
}
return memoryStream.ToArray();
}
}
for Java:
public static byte[] encrypt(byte[] bytes, byte[] key, byte[] iv)
throws Exception
{
Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"),
new IvParameterSpec(iv));
return cipher.doFinal(bytes);
}
I only provide the code for encryption because decryption code is very similar and you can figure it out easily.
Any more question please leave comments.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: testing gamekit framework on a simulator I'm trying to test whether I am using gamekit properly using a simulator. Is it possible for a simulator running my code to detect an external ipad or iphone if they are with in range using the gamekit?
A: A GameKit app in the simulator can connect to a version of it on the iPad/iPhone/iPad if both are on the same Wireless LAN.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Custom jquery.validate method always shows invalid I have a custom validation method that checks for duplicate usernames. The json returns correctly for notDuplicateUsername but the validation always shows up as invalid.
$('#register-form').validate({
//see source of http://jquery.bassistance.de/validate/demo/ for example
rules: {
schoolname: {
required: true
},
username: {
required: true,
notDuplicateUsername: true
},
password: {
required: true
},
email: {
required: true,
email: true
}
},
messages: {
schoolname: 'Please tell us where you want to use Word Strip.',
username: {
required: 'Please choose a username.',
notDuplicateUsername: 'Sorry, that username is already being used.'
},
password: 'Please choose a password.',
email: 'Please can we have your email address.'
}
});
jQuery.validator.addMethod(
'notDuplicateUsername',
function(value, element, params){
var toCheck = new Object();
toCheck['username'] = $('#username').val();
var data_string = $.toJSON(toCheck);//this is a method of the jquery.json plug in
$.post('check_duplicate_username.php', {username_data: data_string}, function(result){
var noDuplicate = true;
var returned_data = $.evalJSON(result);//this is a method of the jquery.json plug in
if (returned_data.status == 'duplicate'){
noDuplicate = false;
}
console.log('value of noDuplicate: '+noDuplicate);
return noDuplicate;
});
}
);
Any clues anyone?
A: Probably you might have sorted this out already, but just in case. I faced a similar problem and found that I was comparing wrong types. May be your server sends the status as a boolean or some other datatype and its comparison to a string fails and always returns false.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I make an installer that silently downloads and installs prerequisites? I have to make a rather complex installer for a C# add-in for Word. I've been researching this for almost two days now and I still haven't found something that can do everything needed.
The main issue here is due to the constraints regarding prerequisites. They mustn't be included in the main installer to keep it small so they'll have to be downloaded.
Additionally, they have to be installed silently without bothering the user. It is ok to show a progress bar or something similar but nothing that requires user input.
After reading about the Windows Installer, Inno, bootstrapper packages and dotNetInstaller I have finally reached the conclusion that the later would be best suited for this scope. However, there's a nasty downside which I have yet to resolve: prerequisites checking.
Is there a standard way to check whether a Microsoft redistributable is installed? The add-in needs the following components:
*
*Windows Installer 3.1
*.Net Framework 3.5
*PIA
*VSTO
Furthermore, I haven't been able to find the direct URLs for these components. I'm wondering how Windows Setups in VS get them.
As a last resort I could host them somewhere to have them at a known location but I'd like to avoid that.
A:
Furthermore, I haven't been able to find the direct URLs for these
components. I'm wondering how Windows Setups in VS get them.
If your using the Visual Studio Setup Project, you can embed them into the setup, and make them required for your application to be installed.
At least for the case of Windows Installer 3.1 and .NET Framework 3.5 SP1
Is there a standard way to check whether a Microsoft redistributable
is installed?
Checking the registry is a quick way.
A: I would first prompt the user about the downloads first because there would be an uproar if it secretly downloaded files without the users consent. It could also be used for malicious reasons if it were unsecure.
A: use this tool http://www.advancedinstaller.com/ for creating installer project it has the simple ui interface using which u can handel many comple scenarios in an easy way. U can purchase the tool or can use freeware edition
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: The party model, permissions, customers and staff We are using a party model for a booking application, so that customers and staff effectively share the same table in the database.
Previously customers could only 'book' an appointment if they paid and if a slot was available. Now, we want to create a premium_customer type role so that customers can make bookings without paying and even if there is no availability.
Does it make sense to add customers to a single security model, such as in an ACL or RBAC?
*
*If so, do we introduce roles called normal_customer and premium_customer alongside our reception and duty_manager and other staff roles?
*If not, should there be a separate security model for website users?
A: As I don't know all your requirements, i can't give you a definitive solution, but your Approach to create a role could be correct i many cases. However, you could also create a "Subscription", wich could have start- and end date.
A: yes it is fair to create another role to record premium customer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Delivery different kind of protocols in a SOA architecture I have a project that is currently in production delivering some web-services using the REST approach. Right now, I need to delivery some of this web-services in SOAP too (it means that I will need to deliver some of the same web-services in SOAP and others a bit different), so, I ask you:
*
*Should I incorporate to the existent project the SOAP stack (libraries, configuration files, ...), building another layer that deliver the data in envelopes way (some people call it "anti-corruption layer") ?
*Should I build another project using just the canonical model in common (become it in a shared-library) ?
*... Or how do you proceed in similar situations ?
Please, consider our ideal target a SOA architecture.
Thanks.
A: In our projects we have a facade layer which exposes the services and maps to business entities, and a business layer where the business logic is run.
So to add a SOAP end point for an existing service, we just create a new facade and call in to the same business logic.
In many cases it is even simpler, since we use WCF we can have a http SOAP endpoint for external clients, and a binary tcpip endpoint for internal clients. The new endpoint can be added by changing the configuration without any need to change the code.
A: The way I think about an SOA system, you have messages and pub/sub. The message is the interface. Getting those messages into and out of the system is an implementation detail. I create an endpoint that accepts a raw message document (more REST-like, but not really REST) as well as an endpoint that accepts the message as a single parameter to a SOAP call. The code that processes the incoming message is a separate concern from the HTTP endpoint enablement.
A: You can use an ESB for this. Where ESB receive the soap messages and send the rest request to the back end. WSO2 ESB provides this functionality. Please look at this sample[1].
[1] http://wso2.org/project/esb/java/4.0.0/docs/samples/proxy_samples.html#Sample152
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Scrolled but till header visible in listview in android I create a listview and that listview has a header. I use addHeaderView() method. But when i scroll down in listview the scrollbar vanishes. Is there any way to avoid this i.e i want to show the header all the times, if scrolled still it will show.
A: To do that you can't do that with the addHeaderView() method.
If you want to place a header on top you should place that in the layout, something like this.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/titleBarText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Title"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
A: The widget is behaving as intended. For what you need, you need to create a relativelayout with TextView at top followed by listview. The textview would act as the header and be static irrespective of your scroll.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to redefine large amounts of data quickly I'm currently writing an ASCII Command Prompt game engine and I am not sure how to redefine 256+ ASCII chars quickly. I am not up to the job of learning all 256 codes.
I was going about having a separate file with the variables to save space, but honestly I'm not upto the job of writing this:
char ascii_null = char(0);
differently 256 times.
A: The standard methods are to use #define or const to provide a name to values. These will more efficient since you won't be changing the values after you define them.
#define ascii_null char(0)
#define ascii_bell char(7)
or
const char ascii_null = char(0);
const char ascii_bell = char(7);
The easiest way to write those lines would be to copy a table from say here and pasting it into Excel. Then use Excel to build the lines with a formula: ="const char ascii_" & A1 & " = char(" & B1 & ")"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: iPhone duplicate/copy a viewcontroller entirely I have a view controller with user content like text/images/location data and i would like to duplicate the viewController and present it modally (presentModalViewController) when the user taps the edit button. The reason for doing this is because i want it to be clear that the user is entering the edit mode by using the transition/animation that comes with a modally presented controller.
Does anybody knows how to duplicate an entire viewController + its view? i don't want the overhead of reallocating the entire viewController. I tried a couple of things, but i haven't had any luck.
Any help/information would be welcome.
A: That sounds a little impractical. You could make an image of the current screen contents, present that using whatever animation you like on top of everything, and then remove it?
Or make other changes to your view (rearrangement of views, appearance of other controls, changes of colour) in your viewController's setEditing:animated: method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Vector2 class in C++ In C++, is there a Vector2 class and if so, what do I need to include to use it?
I want to use this to store 2-dimensional vectors such as position or velocity of a particle.
A: Here you go.
struct Vector2
{
float x;
float y;
};
Or alternatively you can use std::pair<float, float>.
Then you'll want to learn more about Structure Of Arrays (SOA) vs Arrays of Structures (AOS) and how it impacts the performance of your code.
Particle systems would typically go SOA.
Finally here is a series of blog posts on AOS & SOA applied to the implementation of a particle system.
EDIT: there are nice math libraries out there like Eigen or glm that would define such types for you along with many useful algorithms (with performant implementations).
A: There is no "vector2" class in the standard libraries.
There is a pair class that would suit your needs, but for this scenario it would probable be best to create your own vector class(because then you get to have the variables named x and y, rather than first and second), e.g.
class Vector2
{
public:
double x;
double y;
Vector2( double x, double y);
... etc
}
You can then overload the operator +, add functions for finding cross/dot product, etc.
The std::vector class is NOT what you need. The std::vector class is pretty much just a replacement for C malloced arrays.
A: There is std::pair in the header <utility>. It doesn't support vector arithmetic, though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: NSIS - Desktop Shortcut For All Users How can I create desktop shortcuts for all user while installing a package?
A: With !include NTProfiles.nsh [1] you can create a shortcut in the folder "${ProfilePathAllUsers}\Desktop".
[1] - http://nsis.sourceforge.net/NT_Profile_Paths
A: NSIS supports several of the common/shared special folders:
SetShellVarContext all
CreateShortcut "$desktop\myapp.lnk" "$instdir\myapp.exe"
This code assumes you are elevated...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Delphi XE - File Deleted Notification Event: I need to delete a physical file on a server via a client action, then notify a remote database of the file deletion event - would like this to happen entirely on serverSide.
Later versions of Delphi have exposed a lot of directory services that previously had been locked away in WinAPI calls. Currently I'm using Delphi XE but I'm not up to speed on all the new features (migrated from Delphi 7...)
Is there an event of some kind in the Delphi XE file/directory services that I can grab on the server side when a file is deleted, so I can notify interested parties of the delete event?
TIA
A: AFAIK, you can find a unit called: IOSys
It contains lots of stuff to play with folders and files. But there's no notification included.
You still need to use the function: FindFirstChangeNotification
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7501196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.