text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Split Paragraph in Java : Want to store paragraph after particular word address number I need logic, for example I have
String explanation = "The image-search feature will start rolling out in the next few days, said Johanna Wright, a Google search director. \"Every picture has a story, and we want to help you discover that story,\" she said.";
The total number of words are 300.
Now I want all strings after word number 150 in a separate string.
so can you give me logic please
A: have your tried...
explanation.substring(beginIndex, endIndex)
A: There are three things that will be very helpful.
The first is the String.split(String) method. It was introduced in Java 6. It works by passing in a regex and splitting the string into tokens based on that regex.
The second is the regex "\s*" which splits on all white space.
The third is a StringBuilder which lets you build strings from other strings without massive rebuilding penalties.
So, first we need to acquire words. We can do that with the split method using our white-space regex.
String[] words = String.split("\\s*");
From there, it should be rather trivial to count off the first 150 words. You can use a for loop that starts at 150 and moves up from there.
String sentence = "";
for(int i = 150; i < words.length; i++) {
sentence = sentence + words[i] + " ";
}
But this is very expensive because it rebuilds the string so much. We can make it better by doing this
StringBuilder sentence = "";
for(int i = 150; i < words.length; i++) {
sentence.append(words[i]).append(" ");
}
But it all together and wa-bam, you have your sentence formatted as you want. (Just watch out for that extra space on the end!)
A: One way would be explanation.replaceFirst("(\\S+\\s*){0,150}", "").
A: You can use regex to iterate over words as in example,
Pattern regex = Pattern.compile("\\b\\w");
Matcher regexMatcher = regex.matcher(context);
while (regexMatcher.find()) {
// if regexMatcher.groupCount()%150 == 0 then build the next string list
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: startActivity with Action and Uri crash the app I want to open a new activity and pass it a URI of local html file(which is in the assets of the project):
public void onClick(View v)
{
Intent i = new Intent("com.appstudio.android.MY_ACTION",Uri.parse("file:///android_asset/sfaradi_mazon.html"));
MainActivity.this.startActivity(i);
}
And this is how i declared the responding activity in the Manifest:
<activity android:name="BlessingActivity">
<intent-filter>
<action android:name="com.appstudio.android.MY_ACTION"/>
<data android:mimeType="text/html"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
But for some reason the app is crashing at startActivity(Action, Uri).
I'm getting an ActivityNotFoundException. No Activity was found to handle the intent
Any ideas?
Thanks!
A: You have specified a MIME type in the <intent-filter> but do not have it in the corresponding Intent. Either remove the <data> element or call setDataAndType() on the Intent instead of supplying the Uri in the constructor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Variable name from macro argument I'd like to do something like this:
class SomeClass { };
GENERATE_FUNTION(SomeClass)
The GENERATE_FUNCTION macro I'd like to define a function whose name is to be determined by the macro argument. In this case, I'd like it to define a function func_SomeClass. How can that be done?
A: #define GENERATE_FUNCTION(Argument) void func_##Argument(){ ... }
More information here:
http://en.wikipedia.org/wiki/C_preprocessor#Token_concatenation
A: #define GENERATE_FUNCTION(class_name) func_##class_name##
A: As everyone says, you can use token pasting to build the name in your macro, by placing ## where needed to join tokens together.
If the preprocessor supports variadic macros, you can include the return type and parameter list too:
#define GENERATE_FUNCTION(RET,NAM,...) RET func_##NAM(__VA_ARGS__)
..so, for example:
GENERATE_FUNCTION(int,SomeClass,int val)
..would expand to:
int func_SomeClass(int val)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: php loop doesnt work with $i assigned to a 21 digit number I have a php loop like :
for($i = $_GET['start']; $i < $_GET['end']; $i++){
echo $i;
}
when $i is assigned to something like 100000000000000000000 the script doesnt run and it returns no errors!! is there anywway I can fix this?
thanks
A: The value you are using is too large for PHP to handle.
"The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value."
http://php.net/manual/en/language.types.integer.php
Here is the solution that I tested using strings instead of integers and it works:
$start = (string)$_GET['start'];
$end = (string)$_GET['end'];
for($i = $start; strcmp($i, $end); $i = bcadd($i, 1)){
echo $i . "<br>";
}
A: First of all you need to specify which range of numbers your script should support.
Then you need to find the right data structures to handle the data, e.g. integer - or more likely in your case - gmp numbers.
Then you can just code. The for loop works as announced, you might want to not hard-code it against $_GET probably.
A: First, do not put $_GET['start'] and $_GET['end'] directly in your code.
Instead, assign these to variables and check to make sure they are numeric and in range.
For example: end cannot be less than start, etc...
for($i = $start; $i < $end; $i++){
echo $i;
}
Second, a number that large will hang your server.
A: Why not use the difference between start and end so your loop vars are smaller:
<?php
$min = 0;
$max = $_GET['end'] - $_GET['start'];
for($i = $min; $i < $max; $i++){
echo $i + $_GET['start'];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Datagrid column sorting problem, sort looks fine visually but the ItemSource is still the same Here is how i defined the DataGrid
<toolkit:DataGrid
Height="{Binding ElementName=parentCanvas, Path=ActualHeight}"
Width="{Binding ElementName=parentCanvas, Path=ActualWidth}"
SelectionMode="Single"
ScrollViewer.VerticalScrollBarVisibility="Auto"
SelectedIndex="{Binding CurrentSelectedIdx}"
ItemsSource="{Binding Path=GameHostDataList, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
AutoGenerateColumns="False"
x:Name="gamehostsDataGrid"
IsReadOnly="True"
Visibility="{Binding Path=GhListVisibility}">
<toolkit:DataGrid.Columns>
<toolkit:DataGridTextColumn Binding="{Binding FacilityId}" Header="Facility ID" MinWidth="45" Width="45*" IsReadOnly="True" SortMemberPath="FacilityId"/>
<toolkit:DataGridTextColumn Binding="{Binding FacilityName}" Header="Facility Name" MinWidth="100" Width="110*" IsReadOnly="True" SortMemberPath="FacilityName"/>
<toolkit:DataGridTextColumn Binding="{Binding GameHostIp}" Header="GH IP" MinWidth="70" Width="75*" IsReadOnly="True" SortMemberPath="GameHostIp"/>
<toolkit:DataGridTextColumn Binding="{Binding Status}" Header="Status" MinWidth="80" Width="85*" IsReadOnly="True" SortMemberPath="Status"/>
<toolkit:DataGridTemplateColumn Header="" Width="Auto" MinWidth="24">
<toolkit:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Margin="0" HorizontalAlignment="Center" VerticalAlignment="Center" ToolTip="Delete"
Command="{StaticResource deleteGhCommand}" Focusable="False"
Width="24" Height="24">
<Image Source="pack://application:,,,/DesktopShell;component/Resources/Buttons/Aha-Soft/No-entry.png" />
</Button>
</DataTemplate>
</toolkit:DataGridTemplateColumn.CellTemplate>
</toolkit:DataGridTemplateColumn>
</toolkit:DataGrid.Columns>
<e:Interaction.Triggers>
<e:EventTrigger EventName ="SelectionChanged">
<b:CommandAction Command="{Binding DisplayGhCommand}"/>
</e:EventTrigger>
</e:Interaction.Triggers>
</toolkit:DataGrid>
The data source is as follow:
ObservableCollectionEx<GamehostDataModel> gameHostDataList = new ObservableCollectionEx<GamehostDataModel>();
After sorting the column on the grid by clicking on the column header, the entries look sorted but when I click on the first row, the data corresponding from the unsorted list shows up. I am just wondering what is the correlation between the visual representation of the itemsource and the actual itemsource data?
Let's say for example:
Data Visually Data Itemsource
2 2
3 3
1 1
After clicking on the header to sort we have
Data Visually Data Itemsource
1 2
2 3
3 1
Is it supposed to rearrange the reference data source too?
A: That sounds like a bug to me. The ItemsSource should NOT be sorted by the grid.
A: I don't know much about the Toolkit DataGrid, but if it's like anything else in WPF, it won't sort your underlying ItemsSource. (How could it? Your ItemsSource could be a read-only IEnumerable.) Instead, it will create a collection view that wraps your ItemsSource items, and the collection view is what gets sorted. Collection views are how WPF supports sorting and grouping.
If you want to get a reference to the collection view (which contains the sorted list), see "How to: Get the Default View of a Data Collection".
A: NO it is not supposed to do that, It is visualizing your data just assumed that you have huge data source and visualize it in a datagrid and each time you sorting that in datagrid it goes to rearrange your data source! You can do if you want by hooking up a handler.
By the way you don’t need toolkit if you can use .NET 4.0 it has datagrid control as an embedded data element.
A: i assume that your real problem is to get the right selected item. so please do NOT use
<DataGrid SelectedIndex="{Binding CurrentSelectedIdx}"
<e:Interaction.Triggers>
<e:EventTrigger EventName ="SelectionChanged">
<b:CommandAction Command="{Binding DisplayGhCommand}"/>
</e:EventTrigger>
</e:Interaction.Triggers>
you should use the SelectedItem property to get what you want.
<DataGrid SelectedItem="{Binding MyViewModelSelectedItemProperty}" ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Call a method from my "MainActivity" in Android I'm currently messing up with the Google's C2DM notification service.
Following the steps in this tutorial: http://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html, I succesfully recieved a "push message" from the server.
However, in the "protected void onMessage" I need to send the message to the "MainClass" to print it in a toast. Since I'm not deeply familiarized with the Android developing, I will appreciate any help on this. Thank you
A: Use a broadcast to communicate with the activity.
*
*In onMessage send a broadcast.
*In your activity onResume register a broadcast receiver and make it display a toast (remember to unregister it in the onPause)
You would need also to handle the case when the activity is not running (maybe display a notification). In this case, make the broadcast an ordered broadcast. The broadcast receiver in the activity should be set with a high prio, then register a default broadcast receiver through your manifest (this one displays a notification, or opens the activity, or whatever you want).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What can I do to fix that Visual Studio won't display per file properties? I went to go turn on precompiled headers in a brand new project, so I went to go create the "/Create" setting for precompiled headers. But the property page is blank.
What happened, and how can I fix this?
A: This looks like a COM registration issue. It's hard to tell what caused it but the best bet for fixing is to repair the Visual Studio install. That should fix the issue.
*
*Go to Control Panel and run "Add / Remove Programs"
*Double click on "Visual Studio 2010 ..."
*Click Next on the installer
*Choose Repair / Reinstall
*Complete the Wizard
A: I recently came across a similar issue (though I was using CMake to generate the project file), turns out it was this bug in VS2010. If you specify an absolute path for the source file in the project file, and it is on the same drive as the project file, then the property pages for that source file will not be visible. The suggested workaround is to create a new drive mapping for the drive where your source resides, and then to open the project from the mapped drive.
A: This happened to me this morning in my Visual Studio 2008, I read all the solutions in internet, I tried everything - reset setting, userdata, repair, uninstall and reinstall VS, but none solve my problem. I was almost going to reinstall the OS (Windows 10).
At last I found out after using a dir command in other project, AM/PM was replaced with strange words, it's because of my datetime format was changed (in my case, it was changed to Afar format). After reset to default, everything came back to normal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery.data parsing string like 10E6 as int (10000000) Given an element like this <a data-test="10E6"> jQuery interprets the value as an integer in scientific notaion rather than a string as intended when I do elem.data('test')
Given that this is happening in a fairly large application I'm exploring my options for changing this behavior without having to switch to using elem.attr('data-test') everywhere that this may happen.
Since jQuery uses $.isNaN internally before trying to parse the value as a float I could override isNaN adding the regex ^[E\d]+$ like so:
$.isNaN = function( obj ) {
return obj == null || !$.rdigit.test( obj ) || /E/.test( obj ) || isNaN( obj );
}
or override the much more complex $.data
Does anyone have a better plan?
A: According to the documentation of .data() itself, the jQuery developers tell you to use .attr() to retrieve the value without coercing it. I'd imagine overriding the internals that jQuery is using would be a more detrimental problem than simply switching to the appropriate method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xcode: Why does my UITextField act slow in my UITableViewCell? I have an app where I load a UIViewController with an UITableView. In the UITableViewCells I have a UITextField. Which I have added in the cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
if ([indexPath section] == 0) {
// Setting the cell textLabel.
[[cell textLabel] setText:[Customize objectAtIndex:indexPath.row]];
if ([indexPath row] == 0) { // Text
// Adding and customizing UITextField.
TextFieldText = [[UITextField alloc] initWithFrame:CGRectMake(160, 10, 140, 30)];
TextFieldText.placeholder = @"Random";
TextFieldText.autocorrectionType = UITextAutocorrectionTypeNo;
TextFieldText.autocapitalizationType = UITextAutocapitalizationTypeNone;
TextFieldText.returnKeyType = UIReturnKeyDone;
[cell addSubview:TextFieldText];
and so on.
The problem is that when you type in it, it is a little slow. When a letter/symbol is typed it appears in the UITextField and for a very short second the marker is still on the left side of the letter/symbol and slide across the letter/symbol. The keyboard also appears kind of slow.
Any thoughts?
Thanks in advance :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Display String array in spring MVC I am trying to display string array in JSP page.
I have got a test String array in my controller set this to my registration model
String[] test={"ab","cb","sc","ad"};
registration.setTestArray(test);
Now I am trying to display it in jsp Its working fine if I do like this
<tr>
<c:forEach var="arr" items="${registration.testArray}">
<td>${arr} </td>
</c:forEach>
</tr>
But my problem is I want to display only some of the values from this array like 2nd and 4th index of this array.
I tried like
<tr>
<c:forEach var="arr" items="${registration.testArray}">
<td>${arr[2]} </td>
</c:forEach>
</tr>
but its throwing an error. This is just a test in my actual project I have long array of array from which I have to display some selected values.
I am thinking of doing this by first process my required values in controller and then display it in jsp. But I am not sure is this the best method. It would be great help if someone suggest me the better way.
A: It depends on how you get these "selected values". You can:
*
*${registration.testArray[2]}
*you can loop using a specific step of the c:forEach tag
*you can loop everything and check <c:if test="${selectedValues.contains(arrItem)}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: DateDiff Missing few records I am using the datediff function
SELECT stName
,stId
,stDob --(varchar(15))
,stJoinDt --(datetime)
FROM student stu
WHERE
DATEDIFF(yy,stu.stDob,stu.stJoinDt) between 18 and 75
Since the between operator is not effective I have also changed the code to
SELECT stName
,stId
,stDob
,stJoinDt
FROM student stu
WHERE
DATEDIFF(yy,stu.stDob,stu.stJoinDt) >= 18
AND DATEDIFF(yy,stu.stDob,stu.stJoinDt) < 75
Is there any other effective way to write datediff to capture all the missing records?
The missing records are
stDob stJoinDt
10/08/1925 2011-01-03
04/18/1935 2011-01-19
12/11/1928 2011-06-06
1/24/1927 2011-04-18
04/18/1918 2011-04-20
A: Those records should be missing because the number of years between stDob and stJoinDt is not between 18 and 75, as you are filtering them out with your condition that stDob and stJoinDt differ by between 18 and 75 years:
with student as (
select 'Bob' as stName, 1 as stId, '10/08/1925' as stDob, '2011-01-03' as stJoinDt
union select 'Bob' as stName, 2 as stId, '04/18/1935', '2011-01-19'
union select 'Bob' as stName, 3 as stId, '12/11/1928', '2011-06-06'
union select 'Bob' as stName, 4 as stId, '1/24/1927 ', '2011-04-18'
union select 'Bob' as stName, 5 as stId, '04/18/1918', '2011-04-20'
)
SELECT stName
,stId
,stDob --(varchar(15))
,stJoinDt --(datetime)
,datediff(yy, stu.stDob, stu.stJoinDt) as DiffYears
FROM student stu
Output:
stName stId stDob stJoinDt DiffYears
Bob 1 10/08/1925 2011-01-03 *86* (>75)
Bob 2 04/18/1935 2011-01-19 *76* (>75)
Bob 3 12/11/1928 2011-06-06 *83* (>75)
Bob 4 1/24/1927 2011-04-18 *84* (>75)
Bob 5 04/18/1918 2011-04-20 *93* (>75)
My guess would be you were wanting to capture all records where the person is at least 18 years old. In that case, remove the 75 part from the filter:
WHERE
DATEDIFF(yy,stu.stDob,stu.stJoinDt) >= 18
-- STOP HERE
Although technically this does not perform the correct calculation, because it is only finding the difference in the year values and not taking into account day and month. For instance, a date-of-birth of 12/31/1990 and a join date of 1/1/2008 would register as 18 years even though the person is only 17 years, 1 day old. I would recommend instead using the solution provided in this question:
where
(DATEDIFF(YY, stu.stDob, stu.stJoinDt) -
CASE WHEN(
(MONTH(stDob)*100 + DAY(stDob)) > (MONTH(stJoinDt)*100 + DAY(stJoinDt))
) THEN 1 ELSE 0 END
) >= 18
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript Deserialize is returning the class name instead of actual object So I'm running GetServerUpdateProgress() in the controller from a $.ajax call on my page. While debugging I can confirm that the variable: myobj is being properly created and filled with the correct data.
But when on the $.ajax success, I'm not getting the data in json format, instead I'm getting
a string of "TrackerMVC.ClassLib.UpdateAJAXProgress" - the objects type.
I've done this in the past with a .svc webservice and didn't have any problems getting the object values using this exact same method.
Any ideas? Thanks!
method:
public UpdateAJAXProgress GetServerUpdateProgress()
{
string BASE_URL = "http://localhost:55094";
string url = BASE_URL + "/Home/UpdateProgress";
WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultNetworkCredentials; // uses current windows user
var myojb = new UpdateAJAXProgress();
var response = (HttpWebResponse)wr.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
myojb = (UpdateAJAXProgress)js.Deserialize(objText, typeof(UpdateAJAXProgress));
return myojb; // during debugging this object has the correct values in the correct format
}
class:
public class UpdateAJAXProgress
{
public int Completed { get; set; }
public int Total { get; set; }
}
javascript:
$.ajax({
type: "POST",
async: false,
url: '@(Url.Action("GetServerUpdateProgress","Charts"))',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data); // data being returned is: "TrackerMVC.ClassLib.UpdateAJAXProgress"
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
}
});
A: You're misusing MVC.
You should declare your function as returning ActionResult, then return Json(myobj).
If you return a non-ActionResult from an MVC action, MVC will convert it to a string by calling ToString().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to change the colored background of some text objects in Jellybeans color scheme in Vim? I used to use gVim, but now I am switching to terminal Vim and would like to get rid of some annoying background highlighting which is being rendered under certain text. Here are some examples of what I am talking about:
The Vim color scheme I am currently using is Jellybeans, and I have located its file at ~/.vim/colors/jellybeans.vim.
What should I change in that color scheme file to get rid of the background highlighting around some of the text?
A: The pieces of text on red and violet background are probably spelling
errors. The color scheme you use does not configure the highlighting
for spelling errors, so the default one is active.
There are four highlighting groups responsible for spelling errors’
appearance: SpellBad, SpellCap, SpellRare, SpellLocal (see
:help spell-quickstart). The default options for these groups are
defined to be something like the following:
:hi SpellBad term=reverse ctermbg=224 gui=undercurl guisp=Red
:hi SpellCap term=reverse ctermbg=81 gui=undercurl guisp=Blue
:hi SpellRare term=reverse ctermbg=225 gui=undercurl guisp=Magenta
:hi SpellLocal term=underline ctermbg=14 gui=undercurl guisp=DarkCyan
You can change the highlighting settings of these groups to your
liking, and then append the corresponding :highlight commands
to a custom color scheme file.
Note that it is also possible to run :highlight commands manually
and experience changes in appearance on the fly, to find the right
colors without reloading the whole color scheme file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Error when trying to display a Dialog Had this problem when trying to display a Dialog with a time picker where an exception is thrown if I initialize the TimePickerDialog with the context returned from getBaseContext() as opposed to using a this reference to the current activity.
So this code is fine:
@Override
protected Dialog onCreateDialog( int id )
{
return new TimePickerDialog( this , mTimeSetListener, hr, min, false);
}
but this code throws an exception
protected Dialog onCreateDialog( int id )
{
return new TimePickerDialog( getBaseContext(), mTimeSetListener, hr, min, false);
}
If I want to display a Toast then I would use
Toast.makeText( getBaseContext() , ...
and this also works.
My question is I would have thought the context I want the Dialog to display in would be the baseContext so why does a Toast work using this but a Dialog needs a reference to "this" , i.e., the current activity as I would have thought they are both very similar in how they work?
A: Do not use getBaseContext() unless you know what you are doing and have a very specific and concrete reason for using it.
You do not need it for a Toast, and you do not need it for a Dialog. Whatever Activity you are using for those is a perfectly good Context for creating Toasts and Dialogs, so just use this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails validates_with error: :attributes cannot be blank I'm trying to use a validates_with validation to some code that makes sure two flags aren't both simultaneously true:
validates_with ConfirmationValidator
class ConfirmationValidator < ActiveModel::Validator
def validate(record)
if record.confirmed_good && record.confirmed_bad
record.errors[:base] << "Record is both confirmed and confirmed_bad"
end
end
end
But attempting to use this gets the following error:
gems/activemodel-3.0.7/lib/active_model/validator.rb:142:in `initialize': :attributes cannot be blank (RuntimeError)
Looking through that file makes it seem like this is due to some problem passing options, but I still can't quite tell what's going wrong. Any ideas?
A: As @Gazler points out above, your error actually maps to an EachValiator initialization problem. I ran into the same problem.
I'm running rails 3.0.9, using ActiveModel 3.0.9, not quite the same stack you seem to be running. I'm just beginning with custom validators. I have a ActiveModel::EachValidator, not quite what your code sample says. The EachValidator needs attributes passed as an array within the options to validates_with, e.g.
class Something < ActiveRecord::Base
validates_with GenericValidator, :attributes=>[:name, :image]
end
A: This can happen if you name your validator the same name a Rails validator has been named. Example, naming you validator:
PresenceValidator will lead to this exception.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using HQL with MySQL how can I order the result set before the group by so the right record is picked? Is there any way to write a greatest-n-per-group query in HQL (or potentially with Hibernate Criteria) in a single query?
I'm struggling with a problem that's similar to this:
Schema:
*
*Book has a publication_date
*Book has an Author
*Author has a Publisher
I have a Publisher in hand, as well as a search date. For all of that Publisher's Authors, I want to find the book that they published most recently before the search date.
I've been trying to get this working (and have looked at many of the other questions under hibernate as well as greatest-n-per-group) but haven't found any examples that work.
In straight MySQL, I'm able to use a subselect to get this:
select * from
(select
a.id author_id,
b.id book_id,
b.publication_date publication_date
from book b
join author a on a.id = b.author_id
join publisher p on p.id = a.publisher_id
where
b.publication_date <= '2011-07-01'
and p.id = 2
order by b.publication_date desc) as t
group by
t.author_id
This forces the order by to happen first in the subquery, then the group by happens afterwards and picks the most recently published book as the first item to group by. I get the author ID paired with the book ID and publication date. (I know this isn't a particularly efficient way to do it in SQL, this is just an example of one way to do it in native SQL that's easy to understand).
In hibernate, I've been unable to construct a subquery that emulates this. I also haven't had any luck with trying to use a having clause like this, it returns zero results. If I remove the having clause, it returns the first book in the database (based on it's ID) as the group by happens before the order by:
Book.executeQuery("""
select b.author, b
from Book b
where b.publicationDate <= :date
and b.author.publisher = :publisher
group by b.author
having max(b.publicationDate) = b.publicationDate
order by py.division.id
""", [date: date, publisher: publisher])
Is there any way to get hibernate to do what I want without having to spin through objects in memory or dive back down to raw SQL?
This is against a MySQL database and using Hibernate through Grails if it matters.
A: For that, you need a SQL window function. There is no way to do it in Hibernate/HQL, HQL doesn't support window functions.
greatest-n-per-group tag has the correct answers. For instance, this approach is pretty readable, though not always optimal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MySQL Dump Restore What is a good PHP script for restoring a large MySQL database from a local file that has already been uploaded to the server?
Thanks.
A: if it's an sql file than phpmyadmin is an option or u can do it from the mysql console with the command source
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Loading an HTML page in a modal I'm using simpleModal to display a picture slider on my website. The person would hit a button and the modal would pop up with the picture slider inside it. The problem is that I have another picture slider lower on the page. The picture slider only works once on a page. So if I put in the modal, the picture slider below it stops working. So, I made an HTML document that has just the picture slider on the page. How would I go about loading that HTML document inside the Modal window??
I'm using simpleModal for the modal
I'm using nivo-slider for the picture slider
Look on this page for the picture slider. <-- That is the page that the modal with the slider in it will go in.
This is the page I want to load inside the modal.
Look here for an example of the slider inside the modal.
So yeah, the reason I'm doing all this is because nivo-slider won't work twice on one page. So basically I'm looking for a workaround and this is what I thought of, but I don't know how to do it.
A: this is a shitty fix, but just copy the js for nivo and rename the function. then apply that version of the slider to your modal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: c# Rich text Format error in code hoping you can help
I have the following code
List<string> comconfig = populate.resolveconfig(_varibledic, populate.GetVaribles[0].Substring(populate.GetVaribles[0].IndexOf("=") + 1)); //get the aray of strings
string config = ""; //create a empty otput string
config = @"\rtf1\ansi\deff0\deftab240 {\fonttbl {\f000 Monaco;} {\f001 Monaco;} } {\colortbl \red255\green255\blue255; \red000\green000\blue000; \red255\green255\blue255; \red000\green000\blue000; }";
config = config + @"\f96\fs20\cb3\cf2 \highlight1\cf0 "; // assigned rtf header to output string
foreach (var strings in comconfig) //loop though array adding to output string
{
config = config + strings + @"\par ";
}
config = config + "}"; //close of RTF code
So trying to create a RTF string that I can later display. comconfig is an array of strings with some RTF mark up for highlighting and stuff.
trouble is that if I use @ then I get double \ which mess up the RTF, and if i dont use them, then the escape charatures mess up the code??
what is the best way to build up this string by adding a preformated RTF header and the aray of strings in the middle. it is displayed finaly in a RTF.textbox. or converted to a plain text string at the users request. I need to ignore the escape charatures with out messing up the RTF?
Cheers
Aaron
A: No, you don't get a double \. You're getting confuzzled by the debugger display of the string. It shows you what the string looks like if you had written it in C# without the @. Click the spy glass icon at the far right and select the Text Visualizer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP Warning: preg_match(): Unknown modifier I'm trying to redirect users to different pages based on OS but keep getting this warning:
PHP Warning: preg_match() [function.preg-match]: Unknown modifier '2' in /index.php on line 292
It only seems to happen with Windows NT 5.1 and MSIE 8.0 browser configuration:
function getOS($userAgent) {
// Create list of operating systems with operating system name as array key
$oses = array (
'iPhone' => '(iPhone)',
'iPad' => 'iPad',
'Android' => 'Android',
'Windows 3.11' => 'Win16',
'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)', // Use regular expressions as value to identify operating system
'Windows 98' => '(Windows 98)|(Win98)',
'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)',
'Windows XP' => '(Windows NT 5.1)|(Windows XP)',
'Windows 2003' => '(Windows NT 5.2)',
'Windows Vista' => '(Windows NT 6.0)|(Windows Vista)',
'Windows 7' => '(Windows NT 6.1)|(Windows 7)',
'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)',
'Windows ME' => 'Windows ME',
'Blackberry' => 'Blackberry',
'Open BSD'=>'OpenBSD',
'Sun OS'=>'SunOS',
'Linux'=>'(Linux)|(X11)',
'Macintosh'=>'(Mac_PowerPC)|(Macintosh)',
'QNX'=>'QNX',
'BeOS'=>'BeOS',
'OS/2'=>'OS/2',
'Search Bot'=>'(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)'
);
//'Safari' => '(Safari)',
foreach($oses as $os=>$pattern){ // Loop through $oses array
// Use regular expressions to check operating system type
if(preg_match("/".$pattern."/i", $userAgent)) {
// Check if a value in $oses array matches current
//user agent. <---- Line 292
Tried removing OS/2 and changing to OS2 but still redirects to the wrong page for MSIE 8 with Windows XP
A: problem is with OS/2 and using / as your delimeter. You can just escape the forwardslash like OS\/2 and it should work.
A: My guess is that its happening with the OS/2 value in your array. Since you used / as your delimiter, it is ending before the 2 and it thinks the 2 is a modifier like i (case insensitive) or s (dot match all).
Escaping the slash in OS/2 like this OS\/2 should fix it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: WebSockets receive only "disconnect" I'm trying this simple websocket example on Google Chrome:
var wsUri = "ws://echo.websocket.org/";
var output;
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
onOpen(evt)
};
..............
..............
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
window.addEventListener("load", init, false);
But i always receive only DISCONNECT!
There is something wrong?
Do I have to enable WebSockets protocol in my local Apache? If yes how to?
A: This server is not reliable. It even fails on their own demo page for Chrome 14.
The response for a WebSockets request of Chrome 14 is this, which is obviously not correct:
HTTP/1.1 200 OK
Server: Kaazing Gateway
Date: Tue, 27 Sep 2011 14:07:53 GMT
Content-Length: 0
Note that Chrome just switched to a new draft of the WebSockets protocol, which is a complete overhaul. This means that the server has to return a different handshake response and also has to decode messages that are sent, which was not the case with the previous draft. It might just be that they did not upgrade their server yet.
What you probably want is setting up your own server which is compliant with the new draft and test it on that server.
There are a lot of libraries for WebSockets servers popping up everywhere; you can have a look here and pick the server language of your choice.
A: You need to specify that websocket is a variable. Change this line:
websocket = new WebSocket(wsUri);
to this:
var websocket = new WebSocket(wsUri);
Hope it helps. This solved some problems for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What other classes do I need? I'm looking to create an application that will be used to help find a suitable University for prospective students to attend (which is based on various criteria about themselves). The application will be used by prospective students to enter details about themselves and a list of Universities will be displayed based on their profile.
I'm on the design stage (class diagram and etc) and i'm currently thinking of some Java classes I need to produce to do this. So far I've only thought of two...
*
*University class (to hold information about Universities)
*Interface class (this the GUI display)
Can someone help suggest what other class that I will need to create this application? You can suggest as many as you like.
A: Take every noun in your application description. Make it into a class. See if you can write a more detailed description of your app. Use those nouns as classes as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Java quickly draw image I have a BufferedImage which has a color model type of IndexColorModel. When I try and paint this image using Graphics2D.drawImage() it takes about 30 milliseconds. However, if I first convert this image to a DirectColorModel it only takes about 3 milliseconds to paint. In order to do this conversion I call
AffineTransformOp identityOp = new AffineTransformOp(new AffineTransform(), AffineTransformOp.TYPE_BILINEAR);
displayImage = identityOp.filter(displayImage, null);
This converts the displayImage from an IndexColorModel to a DirectColorModel. However, this process takes about 25 milliseconds.
My question is either how do I paint an IndexColorModel image faster or quickly convert to another ColorModel that I can paint faster?
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery UI datepicker: move to the next field after date select I've created a web form that uses the jQuery-UI datepicker. When a date is selected, the focus on the textbox where the date is entered is lost.
I would like to make the focus either stay in the datepicker-enabled textbox or else move to the text element on my web form. Is this possible?
A: $('.selector').datepicker({
onClose: function(dateText, inst) {
$(this).focus();
}
});
http://jsfiddle.net/HNeF9/
A: upon selecting a date, the onClose event is run... so you could put some code in there, and that could focus where you want to
$('.selector').datepicker({
onClose: function(dateText, inst) { ... }
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to inject one JSF2 page into another with jQuery's AJAX I'm using jQuery's .load function to load one JSF page into another.
This works really well until the loaded JSF page uses some AJAX functionality. When this happens, the parent JSF page's AJAX stops working. In fact, after the two pages are combined whichever page has its AJAX called next is the one that continues to work. The other page stops working. If I use the parent page first, the child breaks. If I use the child first, the parent breaks.
Am I doing something wrong? I'm guessing JSF isn't designed for this sort of behaviour and that's fine but then how do I go about doing what I want?
Basically, we have a report page. When the user clicks the link to a report we would like the report to load dynamically into the existing page. That way, the user doesn't experience a page refresh. It's a pretty slick behaviour BUT obviously isn't ideal due to the pages breaking.
I suppose I could do this with a page that contains every report in an outputpanel and then determine which one is rendered based on a value in the backing bean but I can see lots of occasions where I'd like to be able to "inject" one page into another (for dynamic dialogs for instance) and it would suck to have to keep everything in one giant template.
Has anyone else come across this sort of problem? How did you solve it?
A: Do not use jQuery.load(). It does not take JSF view state into account at all, so all forms will fail to work. Rather make use of <f:ajax> and rendered attribute instead. Here's a basic example:
<h:form id="list">
<h:dataTable value="#{bean.reports}" var="report">
<h:column>#{report.name}</h:column>
<h:column>
<h:commandLink value="Edit" action="#{bean.edit(report)}">
<f:ajax render=":edit" />
</h:commandLink>
</h:column>
</h:dataTable>
</h:form>
<h:form id="edit">
<h:panelGrid columns="3" rendered="#{not empty bean.report}">
<h:outputLabel for="name" value="Name" />
<h:inputText id="name" value="#{bean.report.name}" required="true" />
<h:message for="name" />
...
<h:panelGroup />
<h:commandButton value="save" action="#{bean.save}" />
<h:messages globalOnly="true" layout="table" />
</h:panelGrid>
</h:form>
You can if necessary split off the content into an <ui:include>.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Calling getProgressDrawable() on a RatingBar only displays one star I have a custom RatingBar in my app that should display either the site average rating or the user rating for a movie if a user has rated it. The color should change depending on whether the rating displayed is the site average or a user rating.
Here's the process:
User views movie. Site average rating for the movie is displayed.
Layout code for the RatingBar:
<RatingBar android:id="@+id/ratingBar" android:isIndicator="true"
android:layout_margin="10dip" style="@style/RatingBar"
android:progressDrawable="@drawable/site_rating_bar" android:stepSize="0.1" />
RatingBar style:
<style name="RatingBar" parent="@android:style/Widget.RatingBar">
<item name="android:numStars">10</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:minHeight">30dip</item>
<item name="android:maxHeight">30dip</item>
</style>
site_rating_bar.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+android:id/background"
android:drawable="@drawable/btn_rating_star_off" />
<item android:id="@+android:id/secondaryProgress"
android:drawable="@drawable/btn_rating_star_off" />
<item android:id="@+android:id/progress"
android:drawable="@drawable/btn_site_rating_star_on" />
</layer-list>
The user can click on the RatingBar and bring up a dialog where they can add their own custom rating of the movie. Upon close of the dialog, the code updates the rating displayed in the RatingBar above. I'd like to also change the ProgressDrawable so that the color of the stars changes to indicate the user has added a custom rating.
But when I try to set the ProgressDrawable programmatically it does update it so it's displaying the right color, but it only displays a single star, stretched across the screen.
ratingBar.setProgressDrawable(thisActivity.getResources().getDrawable(R.drawable.user_rating_bar));
user_rating_bar.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+android:id/background"
android:drawable="@drawable/btn_rating_star_off" />
<item android:id="@+android:id/secondaryProgress"
android:drawable="@drawable/btn_rating_star_off" />
<item android:id="@+android:id/progress"
android:drawable="@drawable/btn_user_rating_star_on" />
</layer-list>
I've tried saving the original bounds and resetting them, but it didn't help:
Rect bounds = ratingBar.getProgressDrawable().getBounds();
ratingBar.setProgressDrawable(thisActivity.getResources().getDrawable(R.drawable.user_rating_bar));
ratingBar.getProgressDrawable().setBounds(bounds);
Also tried resetting the numStars in case it had gotten lost.
Any ideas greatly appreciated. TIA. :)
A: I'm going through this same thing right now...I can't for the life of me get it to work as expected through code, so I'm going the janky-layout route. :(
<RatingBar
android:id="@+id/beer_rating"
android:numStars="5"
android:progressDrawable="@drawable/rating_bar"
android:indeterminateDrawable="@drawable/rating_bar"
android:stepSize="0.5"
android:isIndicator="true"
android:layout_gravity="center"
style="?android:attr/ratingBarStyleSmall" />
<RatingBar
android:id="@+id/beer_rating_average"
android:indeterminateDrawable="@drawable/rating_bar_average"
android:isIndicator="true"
android:layout_gravity="center"
android:numStars="5"
android:progressDrawable="@drawable/rating_bar_average"
android:stepSize="0.5"
android:visibility="gone"
style="?android:attr/ratingBarStyleSmall"/>
Then just flipping the visibility on them when needed:
findViewById(R.id.beer_rating).setVisibility(View.GONE);
findViewById(R.di.beer_rating_average).setVisibility(View.VISIBLE);
Sucks, but it works. Let me know if you come up with any other solves.
A: Try using:
Use ProgressBar.setProgressDrawableTiled(Drawable)
and set minSDK to 21
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Using list comprehensions to remove a list element by index A table is a list of lists, where the data is set up as follows:
data Position = CEO | Manager| Programmer | Intern deriving (Eq, Show)
data Field = EmployeeID Int | T Position | Name String | Salary Int deriving (Eq)
instance Show Field where
show (EmployeeID k) = show k
show (T p) = show p
show (Name s) = s
show (Salary k) = show k
type Column = Int
type Row = [Field]
type Table = [Row]
An example table would look like this:
employees = [[EmployeeID 1, Name "Shoo"],
[EmployeeID 2, Name "Barney"],
[EmployeeID 3, Name "Brown"],
[EmployeeID 4, Name "Gold"],
[EmployeeID 5, Name "Sky"]]
How would I go about using a list comprehension to create a function that removes a column from the table? I do not know how to operate on lists of lists. I need to have the function have a type of delete :: Column -> Row -> Row
A: If I were to implement this without list comprehensions, I'd use map and filter.
Happily, you can easily do both of those with list comprehensions.
I'm going to avoid using your code, but as an example, suppose I had the list of lists:
nameSets = [[ "dave", "john", "steve"]
,[ "mary", "beth", "joan" ]
,[ "daren", "edward" ]
,[ "riley"]
]
And I wanted to get excited versions of all the lists with three elements:
[ [ name ++ "!" | name <- nameSet ] | nameSet <- nameSets, length nameSet == 3 ]
-- [[ "dave!", "john!", "steve!"]
-- ,[ "mary!", "beth!", "joan!" ]
-- ]
Edit: Just noticed that your column is specified by index. In that case, a zip is useful, which can also be done with list comprehensions, but a language extension is needed.
In a source file, put {-# LANGUAGE ParallelListComp #-} at the top to do zips in list comprehensions.
Here's how they work:
% ghci -XParallelListComp
ghci> [ (x,y) | x <- "abcdef" | y <- [0..5] ]
[('a',0),('b',1),('c',2),('d',3),('e',4),('f',5)]
Or, without the extension
% ghci
ghci> [ (x,y) | (x,y) <- zip "abcdef" [0..5] ]
[('a',0),('b',1),('c',2),('d',3),('e',4),('f',5)]
A: List comprehension does not work very well for removing by index, but here's a try (homework adjusted):
deleteAt :: Column -> Row -> Row
deleteAt n r = [e|(i,e) <- zip (a list of all indexes) r, test i] where
test i = (True if index i should be kept and False otherwise)
If you want to make a list comprehension that operates on lists of lists, you can just nest the comprehensions:
operate :: Table -> Table
operate t = [[myFunction field|field <- row, myPredicate field]| row <- t]
myFunction :: Field -> Field
myPredicate :: Field -> Bool
A: Hmm, this isn't an answer since you requested using list comprehensions. But I think list comprehensions are quite ill-suited to this task. You only need take and drop.
ghci> take 2 [1,2,3,4,5]
[1,2]
ghci> drop 2 [1,2,3,4,5]
[3,4,5]
To delete an element at index i, append together the first i elements and the list with the first i+1 elements dropped.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to cast with GSON Is there the way to cast a string value within json to an int-, long- or double-member using GSON?
What I mean, I have a json string, something like this:
{'timestamp':'1243274283728', 'distanse':'122.1'}
And I want to map this json string to object of following class:
public class TestClass
{
public long timestamp;
public double distance;
}
Thank you in advance
A: Doesn't this work?
TestClass obj = new Gson().fromJson(
"{'timestamp':'1243274283728', 'distance':'122.1'}",
TestClass.class);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: plotting the real time data after certain specified interval in Matlab I have a question that I dont know how to figure it out. I am plotting my real time data obtained from temperature sensors in MATLAB. The sensor software generates the text file for each sensor and updates it after every minute. What do I have to do if I want the plot to be updated after certain period of time; let's say after 10 or 20 values or after every 5 mins.
A: You could use a timer.
Reusing the code of Nzbuu, it would be something like the following
function ReadAndUpdate
[X,Y] = readFile(); % Read file
set(h, 'XData', X, 'YData', Y) % Update line data
end
t = timer('TimerFcn',@ReadAndUpdate, 'Period', 5*60, ...
'ExecutionMode', 'fixedDelay')
start(t)
Here the function is trigged infinitely but you can stop it or set a condition.
A: Assuming you have a function readFile that reads the data from the file. You can do the following for something quick and dirty.
h = plot(NaN, NaN);
while true
[X,Y] = readFile(); % Read file
set(h, 'XData', X, 'YData', Y) % Update line data
pause(5*60) % Wait 5 minutes
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: It's possible to do a array of Matrix in Matlab? I'm doing a project in a University here in Brasil, and I'm using MatLab. I'm new in it, so I have to search a lot. A problem that's disturbing me right now is that I need to store many Matrix of different sizes in a Array.
The code is:
for count = 1:nColors
i = rgb2gray(segmented_images(:,:,:,count));
bw = im2bw(i,0.01);
s = regionprops(bw,'Centroid');
centroids = cat(1, s.Centroid);
end
Centroids is a Matrix, and the size of it varies. I need to store it, so I can use later. I tried
centroids(count) = cat(1, s.Centroid);
but MatLab said "In an assignment A(I) = B, the number of elements in B and
I must be the same."
A: You need a cell array: http://www.mathworks.co.uk/help/techdoc/matlab_prog/br04bw6-98.html
A: for count = 1:nColors
i = rgb2gray(segmented_images(:,:,:,count));
bw = im2bw(i,0.01);
s = regionprops(bw,'Centroid');
centroids(i).matrix = cat(1, s.Centroid);
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Restrict input to a specified language I use a TextInput component of Flex 4.5 to enter some text in English. I use the restrict attribute to ... restrict the keyboard input to characters a-zA-Z only. The problem is that if i copy/paste a word in another language, i can then paste it into the TextInput component. Is there a way to avoid that? If no, how can i validate the input against a specified language?
I found out that the unicode set of Chinese+ language symbols is \u4E00 to \u9FFF. So i write the following:
var chRE:RegExp = new RegExp("[\u4E00-\u9FFF]", "g");
if (inputTI.text.match(chRE)) {
trace("chinese");
}
else {
trace("other");
}
But if i type in the TextInput the word 'hello' then it validates...What is the error?
Since i cannot (my fault? or a bug?) use unicode range with RegExp, i wrote the following function to check if a word is in Chinese and that's it.
private function isChinese(word:String):Boolean
{
var wlength:int = word.length;
for (var i:int = 0; i < wlength; i++) {
var charCode:Number = word.charCodeAt(i);
if (charCode <= 0x4E00 || charCode >= 0x9FFF) {
return false;
}
}
return true;
}
A: The String.match() method returns an array which will always test to true, even if it's empty (see docs here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/String.html#match%28%29)
Use the RegExp.test() method instead to see if it matches:
// Check your character ranges:
//var chRE:RegExp = new RegExp("[\u4E00-\u9FFF]", "g"); // \u9FFF is unrecognised and iscausing issues.
var chRE:RegExp = new RegExp("[\u4E00]+", "g"); // This works.
if (chRE.test(inputTI.text)) {
trace("chinese");
}
else {
trace("other");
}
You'll need to check the character ranges too - I couldn't get it to match with \u9FFF in the regex.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Migrating django auto model loading to iPython .11+ - how to execute code after script loads? I'm having trouble migrating my old iPython ipy_user_conf.py script to the new .11+ iPython.
Before, loading models was as easy as this snippet in ipy_user_conf.py
My manage.py sets the django environment so iPython could import django successfully regardless of project / not having django on my global site packages.
Now, if I have the new iPython config file execute the same script, I get import errors.
Any suggestions? Aside from django-extensions shell_plus (this is my temporary solution).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: POSIX sh Redirection I may be missing something small, but is it possible to achieve this syntax in a POSIX (dash) compliant way:
$ ./myApp 2> stderr.txt 1> stdout.txt
I know in dash you cannot use >& but have to use 2>&1 but I do not want to do this. I have tons of data coming to stdout and I do not want to parse it to get my stderr. I feel like I am missing something extremely simple but I cannot put my finger on it...
Right now when I run the above command, I get only a few lines of my stdout (3) but it shows up in the stderr file and stdout is empty. I have also tried various ways of grouping it but still I have had no luck. Not sure what is going on...
UPDATE
This is the format of the actual command I am running so that you can see the full effect of what I am trying to accomplish:
$ LD_PRELOAD=/usr/lib/libtcmalloc.so /usr/bin/time -p myApp -c -f inputFile 2> stderr 1> stdout
This is where I mentioned that I tried multiple variants of groupings with (). Also, the executable myApp does not fork.
I thought that this command would work, but I have found otherwise:
$ LD_PRELOAD=/usr/lib/libtcmalloc.so /usr/bin/time -p (myApp -c -f inputFile) 2> stderr 1> stdout
A: Posting since I answered in the comments:
The syntax you posted is the correct syntax, but you may be getting some interference from the output of the time command. Try
time -p sh -c 'LD_PRELOAD=/usr/lib/libtcmalloc.so command >stdout.txt 2>stderr.txt'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WCF customBinding problem I've been playing around with a pollingDuplex example that is driving me nuts. I'm using a customBinding to integrate the readerQuotas element and I keep getting the error: "Contract requires Duplex, but binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it."
Where is that BasicHttpBinding coming from when I am using customBinding ? I've checked countless examples and my configuration file matches what they had but it doesn't work. Can anyone help me with this ?
Thanks.
<configuration>
<system.serviceModel>
<extensions>
<bindingElementExtensions>
<add name="pollingDuplex" type="System.ServiceModel.Configuration.PollingDuplexElement, System.ServiceModel.PollingDuplex"/>
</bindingElementExtensions>
</extensions>
<bindings>
<customBinding>
<binding name="DBNotification" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
<httpsTransport maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"/>
<pollingDuplex duplexMode="MultipleMessagesPerPoll" maxPendingSessions="2147483647" maxPendingMessagesPerSession="2147483647"/>
<binaryMessageEncoding>
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binaryMessageEncoding>
</binding>
</customBinding>
</bindings>
<services>
<service name="AdminWebService" behaviorConfiguration="DBNotificationServiceBehavior">
<endpoint address="adminservice" binding="customBinding" bindingConfiguration="DBNotification" contract="AdminWebService.IAdminWebService" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="DBNotificationServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceThrottling maxConcurrentSessions="2147483647"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
A: Is it possible that httpGetEnabled="true" implies using BasicHttpBinding? Do you really need this feature? Does the error goes away if you comment this line?
A: You're probably running into the "simplified configuration" problem - described in details at http://blogs.msdn.com/b/endpoint/archive/2009/11/09/common-user-mistake-in-net-4-mistyping-the-service-configuration-name.aspx. The "name" attribute in the <service> element must be the fully-qualified name of the service. Since your interface is AdminWebService.IAdminWebService, isn't your service name AdminWebService.AdminWebService? If so, fixing the name attribute should fix the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Assembly Language: printing lowercase to uppercase I have an assignment that is described like so:
- Reads printable characters (20h-7Fh) from the keyboard without echoing
- Uppercase letters are printed to display
- Lowercase letters are converted to uppercase and then printed to display
- Blank spaces and periods are printed to display; everything else is trashed
- Program ends when period is printed
My program so far is this:
.model small
.8086
.data
.code
start:
mov ax,@data
mov ds,ax
read:
mov ah,8
int 21h
cmp al,61
jl write
cmp al,7fh
jg read
sub al,20h
jmp write
write: cmp al,20h
jl read
mov dl,al
mov ah,2
int 21h
cmp dl,2eh
jne read
exit:
mov ax,4c00h
int 21h
end start
My program succesfully converts lowercase letters and prints the corresponding uppercase letter, but I am having trouble trashing everything else. What is the best way to only allow blank spaces, periods, and letters through to the display?
Looking at the ASCII chart,
21h - 2Dh can be trashed
2Fh - 40h can be trashed
5bh - 60h can be trashed
7bh - 7fh can be trashed
Can anyone help me come up with the best logic for comparing the input to these values and then trashing those that fall between the range above? We are graded on efficiency, with 0-20 instructions written awarded full credit. I am already at 20 instructions here and I haven't included compares to find the trash values.
EDIT
Here is what I have narrowed my code down to:
.model small
.8086
.data
.code
read:
mov ah,8
int 21h
cmp al,' '
je write
cmp al,'.'
je write
cmp al,'a'
jl read
cmp al,'Z'
jg convert
convert:
cmp al,'a'
jl read
sub al,20h
write:
mov dl,al
mov ah,2
int 21h
cmp dl,'.'
jne read
exit:
mov ax, 4c00h
int 21h
end read
Currently at 21 instructions! Is there any redundancy in my code that can be removed to get it down to 20?
A: I think you can save some instructions by doing something like this:
read:
if lowercase then make uppercase
if uppercase then print
if space then goto print
if period then quit
goto read
print:
do the print
goto read
A: You might modify your logic to do something like:
*
*if space or period, jump to write
*fold lowercase to uppercase
*if not uppercase letter, jump back to read
Note that the "fold lowercase to uppercase" doesn't need to check to see whether the input was a letter first. Just and xx where xx is an appropriate value should do it (I'll let you work out the value). This step will also modify characters other than letters, but since the next step is to check for a letter it doesn't matter.
A: I would setup a table for corresponding the values 20..7f, set flags for every range, and later use every input byte - 20h as index into the table.
A: TITLE SAMPLE ASSEMBLY CODE STRUCTURE
.MODEL SMALL
.STACK
.DATA
MSG1 DB "ENTER A LETTER: $"
MSG2 DB 10,"THE LETTER IN UPPERCASE IS: $"
MSG3 DB 10,"[PRESS ANY KEY TO CONTINUE] $"
.CODE
MOV AX,@DATA
MOV DS,AX
MOV ES,AX
balik:
MOV AX,3
INT 10H
;---------------------- YOUR EXECUTION OF CODE STARTS HERE-------------------
MOV AH,9
LEA DX,MSG1
INT 21H
MOV AH,1
INT 21H
AND AL,00DFH
MOV AH,9
LEA DX,MSG2
INT 21H
MOV AH,2
MOV DL,AL
INT 21H
MOV AH,9
LEA DX,MSG3
INT 21H
MOV AH,1
INT 21H
MOV BL,AL
CMP BL,27
JE TAPOS
JMP balik
TAPOS:
;-------------------------------END OF CODES----------------------------------
MOV AH,4CH
INT 21H
END
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to display full screen iAd on iPhone? I just recently read that full screen iAd only works on iPad. Do you think it is possbile to show a
full screen iad banner before user to click it on iphone?
A: Full screen iAd are ADInterstitialAd available only since iOS 4.3 and for iPad ONLY.
Hope this helps
A: I just implemented iad and it seems that they only have landscape and portrait ad banners. But the Ad is Full screen. Once they click on it. It takes over the application and lets you know to pause.
Then lets you know when it is done so you can resume whatever. But again the Ad Banners are only Landscape or Portrait.
Full Screen ipad iad's are listed in the Programming guide .
iAd Programming Guide
Doing a tutorial will get the implementation out pretty fast. But you should go over the manual as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is the largest value a long data type can hold I believe this question is sort of open ended, but I am seriously struggling. I keep getting an over flow.
I have two longs. The first is set to 16552800. I can add 32760 to it no problem. However I get an overflow error when I add 32820 to is.
Any ideas?!?!?!
Thanks!!!
A: A long in Visual Basic 6 is 32 bits and has a range from 2,147,483,648 to 2,147,483,647. You are nowhere near this limit. In VB.NET it is 64 bit.
It seems that you get an error when you add a number greater than or equal to 215 = 32768. Could you try 32767 and 32768 and see if that is the point at which the error starts occurring?
Are you sure that the overflow is coming from the addition? I suspect that you are trying to assign 32820 to a signed integer (range -32768 to +32767), and it's this assignment that gives the overflow, not the addition.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Mapping *.MVC to aspnet_isapi.dll on IIS7 We have a .net 3.5 application (MVC and WebForms mixed) that was hosted on IIS6. In order to make it work on IIS6 we had to add custom mappings to IIS such that *.MVC would map to aspnet_isapi.dll.
So our URL's would end up looking like this:
<host>\someController.mvc\action
But now that were setting this web app up on IIS7, with classic mode pooling, were trying to do the same thing so that we don't have to change anything about the application.
But after adding the *.MVC Handler mapping in IIS7 it still does not seem to be picking it up. Every time we navigate to our MVC pages, we get 404 errors. However, our .aspx pages load fine.
On closer inspection the Failed Request Tracing keeps complaining about the following
ModuleName="IIS Web Core", Notification="MAP_REQUEST_HANDLER", HttpStatus="404", HttpReason="Not Found", HttpSubStatus="0", ErrorCode="The system cannot find the file specified.
(0x80070002)", ConfigExceptionInfo=""
I'm running in circles. We were able to set this up on another IIS7 machine yet this one were trying to set it up on just refuses to work. I really don't know what I'm missing. Its like the mapping rule is not triggering at all. Because the same error occurs if we just type in random things for the file name in the URL.
A: I just dealt with this, and what really did it for me was getting rid of the entire MvcHttpHandler (remove it from your
<system.webServer>/<handlers>
configuration tag).
MSDN states that this handler is only useful when the UrlRoutingModule is not enabled for all requests (which in IIS7+ we can), hence why it's useful for IIS6 (and also why we need the *.mvc extension to route properly).
So just remove the MvcHttpHandler reference in your handlers, and make sure you:
*
*Have the application running in an app pool with Integrated Mode (not Classic)
*You have the runAllManagedModulesForAllRequests modules attribute set to "true"
<modules runAllManagedModulesForAllRequests="true">
If you are still getting 404's then it's either your MVC doing it (which really sidetracked me :S) another reason.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hash collision in Hashmap I need a simple scenario to produce a hashing collision in a HashMap. Could someone please provide one.
Is it possible to produce hashing collision if my hashmap keys are immutable?
Regards,
Raju komaturi
A: You could create your own type and create a bad hash function:
public class BadHash {
private String aString;
public BadHash(String s) {
aString = s;
}
public int hashCode() {
return aString.length();
}
public boolean equals(Object other) {
// boilerplate stuff
BadHash obj = (BadHash) other;
return obj.aString.equals(aString);
}
}
This will make it easy to create a collision.
An example would be:
BadHash a = new BadHash("a", value1);
BadHash b = new BadHash("b", value2);
hashMap.add(a);
hashMap.add(b);
These two entries would collide because a and b hash to the same value even though they are not equal.
A: Assuming you can change the key class's hash code method.
public int hashCode() {
return 1; // Or any constant value
}
This will make every single key collide.
A: Can't get much simpler than this:
Map<String, Object> map = new HashMap<String, Object>();
map.put("a", null);
map.put("a", null);
A: The simplest way is to set the initialCapacity of the HashMap to a low value and start inserting elements.
I suppose you could also design a class such that two objects can return the same hashCode value even though equals would return false.
From what I can see though, there's no way with the default HashMap to get it to tell you if there's a collision.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
}
|
Q: is it possible to register event handler like this? Why doesn't it work?
<body>
<p id="element_id">
blah
</p>
</body>
var pcontent = document.getElementById('element_id').innerHTML;
function exit(){
document.getElementById('id2').innerHTML = pcontent;
}
var a = '<div id="id2"><input type="button" value="exit" onclick= "exit()"></div>' ;
document.getElementById('element_id').innerHTML= a;
http://jsfiddle.net/B94kx/
A: The problem is that the function exit is not a global function. onclick="exit()" tries to run a global function called exit, which doesn't exist. You defined the function in the scope of the event handler (it's the window's onLoad event, as you can see from the panel on the left).
The simple solution is to define the function as a global value by setting it as a property of the window object:
window.exit = function() {
document.getElementById('id2').innerHTML = pcontent;
};
Updated fiddle
A nicer solution would be to stop misusing the DOM by using innerHTML and inline event handlers. It's a bit clunky, but here's your code using proper DOM methods.
A: The problem here is not your code but instead the way in which you are running the code on jsfiddle. Your fiddle has the onLoad option set which means all of the javascript code runs in the onLoad callback. So the exit function is defined in the callback and not in the global scope. Hence the event handler can't reference exit.
This can be fixed by simply removing the onLoad option and instead using no wrap (body)
Working Fiddle: http://jsfiddle.net/NjbVh/
Or alternately you can force exit to be a global by attaching it to the window.
window.exit = function() {
document.getElementById('id2').innerHTML = pcontent;
}
A: You are losing your scope, making exit() not visible
here's a quick and dirty solution:
var pcontent = document.getElementById('element_id').innerHTML;
window.exit = function() {
document.getElementById('id2').innerHTML = pcontent;
}
var a = '<div id="id2"><input type="button" value="exit" onclick="window.exit()"></div>' ;
document.getElementById('element_id').innerHTML= a;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the difference between compiling and refreshing a materialized view? We just ran into a problem where materialized views weren't refreshing, and giving a compile error. One of the senior developers says he just figured out how to fix it -- by telling toad to compile the materialized view.
So my question is pretty simple: what's the difference between a refresh and a "compile"?
A: A Refresh of a materialized view is a data operation. The data in the MV is brought up to date as specified when the view was created, e.g., fast refresh, complete refresh, etc.
When you compile the MV, Oracle revalidates the query upon which the view is based. Your MV may be invalid due to changes in one or more of the underlying objects upon which the MV is based.
A: A refresh updates the data that the materialized view holds. This cannot be done if the materialized view's definition is invalid.
A compile validates the definition of the materialized view, i.e. that the SQL is valid and that the objects it relies on exist.
A: Compile = validation and run
Refresh = resubmitting the data.
It holds the same meaning and definition as it does outside of programming.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: chosen.js :: Does anyone have an actual working example? Has anyone used and customized some basic chosen.js code?
I have downloaded the js, css and png, copied some code from the examples, wrote my own super-simple example, but I must be missing something. I have verified that the code.jquery.js is included and gets loaded, same with the chosen.css.
When I try to bring up even an extremely simple SELECT field (drop-down), I get a very small field, and clicking the field does nothing. When I disable chosen.js, I simply get the SELECT with all the options displayed.
Here's how I add a simple SELECT within jQuery (I have to populate the field dynamically, although in this example it's all hard-coded):
$html = '<select name="items" id="items" multiple="multiple" size="1" class="chosenElement">';
$html += '<option value="foo">foo</option>';
$html += '<option value="bar">bar</option>';
$html += '<option value="baz">baz</option>';
$html += '<option value="qux">qux</option>';
$html += '</select>';
Then, right when I display the modal dialog box containing the options, I call:
$('.modal-body').html($html);
$('.chosenElement').chosen();
So far, I have modified and tested all kinds of permutations, Googled for solutions or examples, but nothing seems to work. It's probably something very silly, like a missing semi-colon somewhere, but I've wasted so much time on this "10-minute implementation" that I need to ask for soem help.
https://github.com/harvesthq/chosen
A: If you really want to test the "most basic" example, I'd suggest:
*
*Work on hardcoded HTML (vs dynamically added html)
*Remove all the attributes from the select element
*Only add back the attributes to the select element once a basic example runs fine.
Note that the multiple="multiple" attribute on the select element does make chosen.js behave differently.
I have ran your code here: http://jsfiddle.net/99Dkm/1/
And it works just fine.
I suspect the problem is not chosen.js library but rather how you use it (wrapping inside some basic jQuery onready function missing or else).
Notice that in my working examples on jsFiddle I only included chosen.css & chosen.jquery.js.
note: get the URLs for those files (javascript & css) from http://cdnjs.com/libraries/chosen
A: you have to target the select
$('#items').chosen();
jsFiddle
A: When you populate the field dynamically, is the JSON result set coming back w/ "Text" and "Value" attributes? If it's not, Chosen will not format the results properly within its list. In fact, it won't add them at all. I learned this the hard way because my results were initially coming back w/ "Name" and "ID" attributes instead.
A: Try removing the size="1" attribute from the select box and/or setting a style attribute with a larger width. Chosen bases the width of the generated elements on the width of the underlying select box so if your select box is very small, the Chosen select will be as well. Hope that helps.
A: wrap the jQuery code inside :-
$(document).ready(function(){
$('.chosenElement').chosen();
});
A: Ran into a similar problem. I wasn't able to figure out what was causing it by in my situation this worked:
$j('select').livequery(
function(){
$j(this).chosen({width: "300"});
$j('.search-field input').height(14);
},
function(){
//remove event
});
A: The documentation on Chosen options includes:
If your select is hidden when Chosen is instantiated, you must specify
a width or the select will show up with a width of 0.
To avoid a zero-width field appearing, you need to use the "width" option, or make sure your original Select is visible when you call Chosen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Simple JavaScript/HTML Slideshow New to Javascript, but after some research it loks like this would be the best method in implementing my desired output. I'm trying to produce a slideshow of images (5 pre-selected images) that automatically change between 5 second intervals. Can anyone point towards a tutorial or guide me along in this process? Any help is very much appreciated.
A: A really nice jQuery slideshow type plugin is this http://www.devtrix.net/sliderman/
It has many different transitions between slides, and is really easy to use.
There are many out there, so a quick google search of "jQuery Slideshow" will produce hundreds of results.
A: Just google for javascript content sliders
Here's 350 image and content sliders:
http://www.jqueryrain.com/example/jquery-slider-slideshow/
and here's 25 more:
http://vandelaydesign.com/blog/web-development/jquery-image-galleries/.
A: There are thousands of examples, some very complex and sophisticated. The difficoult, rather, is to find one easy to understand for beginners.
After some research I've found this from css-tricks. (Uses jquery also).
A: I know this is an old post but I though I would share my tutorial, for the benefit of anyone who comes across this question in future.
Simple Slideshow
Hope this helps somebody.
Its a pretty simple and basic slideshow that is easy to build / implement.
Just In case the link becomes invalid here is the code:
The first stage is to set up the html as follows:
<div id="slideShow">
<div id="slideShowWindow">
<div class="slide">
<img src="”img1.png”/">
<div class="slideText">
<h2>The Slide Title</h2>
<p>This is the slide text</p>
</div> <!-- </slideText> -->
</div> <!-- </slide> repeat as many times as needed -->
</div> <!-- </slideShowWindow> -->
</div> <!-- </slideshow> -->
Next we will write the CSS, which is as follows:
img {
display: block;
width: 100%;
height: auto;
}
p{
background:none;
color:#ffffff;
}
#slideShow #slideShowWindow {
width: 650px;
height: 450px;
margin: 0;
padding: 0;
position: relative;
overflow:hidden;
margin-left: auto;
margin-right:auto;
}
#slideShow #slideShowWindow .slide {
margin: 0;
padding: 0;
width: 650px;
height: 450px;
float: left;
position: relative;
margin-left:auto;
margin-right: auto;
}
#slideshow #slideshowWindow .slide, .slideText {
position:absolute;
bottom:18px;
left:0;
width:100%;
height:auto;
margin:0;
padding:0;
color:#ffffff;
font-family:Myriad Pro, Arial, Helvetica, sans-serif;
}
.slideText {
background: rgba(128, 128, 128, 0.49);
}
#slideshow #slideshowWindow .slide .slideText h2,
#slideshow #slideshowWindow .slide .slideText p {
margin:10px;
padding:15px;
}
.slideNav {
display: block;
text-indent: -10000px;
position: absolute;
cursor: pointer;
}
#leftNav {
left: 0;
bottom: 0;
width: 48px;
height: 48px;
background-image: url("../Images/plus_add_minus.png");
background-repeat: no-repeat;
z-index: 10;
}
#rightNav {
right: 0;
bottom: 0;
width: 48px;
height: 48px;
background-image: url("../Images/plus_add_green.png");
background-repeat: no-repeat;
z-index: 10; }
As you can see there isn’t anything exciting or complicated about this CSS.
In fact it doesn’t get more basic, but I promise that’s all that’s needed.
Next we will create the jQuery:
$(document).ready(function () {
var currentPosition = 0;
var slideWidth = 650;
var slides = $('.slide');
var numberOfSlides = slides.length;
var slideShowInterval;
var speed = 3000;
//Assign a timer, so it will run periodically
slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>');
slides.css({ 'float': 'left' });
//set #slidesHolder width equal to the total width of all the slides
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
$('#slideShowWindow')
.prepend('<span class="slideNav" id="leftNav">Move Left</span>')
.append('<span class="slideNav" id="rightNav">Move Right</span>');
manageNav(currentPosition);
//tell the buttons what to do when clicked
$('.slideNav').bind('click', function () {
//determine new position
currentPosition = ($(this).attr('id') === 'rightNav')
? currentPosition + 1 : currentPosition - 1;
//hide/show controls
manageNav(currentPosition);
clearInterval(slideShowInterval);
slideShowInterval = setInterval(changePosition, speed);
moveSlide();
});
function manageNav(position) {
//hide left arrow if position is first slide
if (position === 0) {
$('#leftNav').hide();
}
else {
$('#leftNav').show();
}
//hide right arrow is slide position is last slide
if (position === numberOfSlides - 1) {
$('#rightNav').hide();
}
else {
$('#rightNav').show();
}
}
//changePosition: this is called when the slide is moved by the timer and NOT when the next or previous buttons are clicked
function changePosition() {
if (currentPosition === numberOfSlides - 1) {
currentPosition = 0;
manageNav(currentPosition);
} else {
currentPosition++;
manageNav(currentPosition);
}
moveSlide();
}
//moveSlide: this function moves the slide
function moveSlide() {
$('#slidesHolder').animate({ 'marginLeft': slideWidth * (-currentPosition) });
}
});
A: Here is a Very simple code to create simple JavaScript/HTML slideshow only by using simple JavaScript and HTML codes :
<script language="JavaScript">
var i = 0; var path = new Array();
// LIST OF IMAGES
path[0] = "image_1.gif";
path[1] = "image_2.gif";
path[2] = "image_3.gif";
function swapImage()
{
document.slide.src = path[i];
if(i < path.length - 1) i++;
else i = 0;
setTimeout("swapImage()",3000);
}
window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Disable UIView respond to UIIntefaceOrientationDidChange I have a uiimageview within a uiview and I would like it to not rotate when uiinterfaceorientationdidchange is called but I would like everything else to rotate. Right now everything is rotating, how can I set certain objects not to rotate?
A: A UIImage has a property imageOrientation. Or, make a custom view controller with only a UIImageView and in the shouldRotateToInterfaceOrientation: method of thatcontroller return NO. Then, in the interface builder for your main view controller, add a custom object and change its class to your custom UIImageView. Or you can add it as a subview programatically.
Check out the UIViewController Class Reference for more info.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android: How do you remove the selection behavior from the Gallery? I really need horizontal scrolling in my app, so I overrode Gallery and I'm trying to do something with an OnItemSelectedListener, and a GestureDetector I'm calling from an OnTouchListener I've set on the Gallery. What I want is to remove the auto-selection of Gallery items as I scroll, but I want to be able to click an item to select it.
If I set an OnClick listener on a view that is populated in the adapter, the Gallery fails to scroll. Also, the OnItemClicked event is never called for the listener I set for that on the Gallery.
A: To remove selection from all items you should do this:
youGallery.setUnselectedAlpha(1);
A: Maybe my answer to this question will help you. It's something which wasn't intended to be ever realized...
A: For your case why dont you just use a HorizontalScrollView. Just put a linear layout inside and add as many imageview's as you need if your using images, or dynamicaly add it in java code.
This will elemenate the selection of gallery by default. This will be easier than trying to Override the Gallery widget default methods.
A: Why not you set some tag while you click on an item in the Gallery to select.
Now once again when you click after the item is selected just check for the tag that you had set, and based on the condition you can move to new screen and whatever task you want to perform.
But keep one thing in mind, you have to set the tag with every gallery item while building the gallery view.
I hope you will get what I want to say.
If still you have any problem then let me know.
I had the same scenario and I solved that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: make .combine function scaleable I am trying to use foreach and am having problems making the .combine function scalable. For example, here is a simple combine function
MyComb <- function(part1,part2){
xs <- c(part1$x,part2$x)
ys <- c(part1$y,part2$y)
return(list(xs,ys))
}
When I use this function to combine a foreach statement with an iterator other than 2 it returns it incorrectly. For example this works:
x = foreach(i=1:2,.combine=MyComb) %dopar% list("x"=i*2,"y"=i*3)
But not this:
x = foreach(i=1:3,.combine=MyComb) %dopar% list("x"=i*2,"y"=i*3)
Is there a way to generalize the combine function to make it scalable to n iterations?
A: Your .combine function must take either two pieces and return something that "looks" like a piece (could be passed back in as a part) or take many arguments and put all of them together at once (with the same restrictions). Thus at least your MyComb must return a list with components x and y (which is what each piece of your %dopar% do.
A couple of ways to do this:
MyComb1 <- function(part1, part2) {
list(x=c(part1$x, part2$x), y=c(part1$y, part2$y))
}
x = foreach(i=1:3,.combine=MyComb1) %dopar% list("x"=i*2,"y"=i*3)
This version takes only two pieces at a time.
MyComb2 <- function(...) {
dots = list(...)
ret <- lapply(names(dots[[1]]), function(e) {
unlist(sapply(dots, '[[', e))
})
names(ret) <- names(dots[[1]])
ret
}
s = foreach(i=1:3,.combine=MyComb2) %dopar% list("x"=i*2,"y"=i*3)
x = foreach(i=1:3,.combine=MyComb2, .multicombine=TRUE) %dopar% list("x"=i*2,"y"=i*3)
This one can take multiple pieces at a time and combine them. It is more general (but more complex).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Workaround Way To Install Numpy? Right now I have a script which uses numpy that I want to run automatically on a server. When I ssh in and run it manually, it works fine. However, when I set it to run as a cron job, it can't find numpy. Apparently due to the shared server environment, the cron demon for whatever reason can't find numpy. I contacted the server host's tech support and they told me to set up a vps or get my own damn server. Is there any way to hack a workaround for this? Perhaps, by moving certain numpy files into the same directory as the script?
A: If you have numpy installed somewhere on the server, you can add it into the import path for python; at the beginning of your script, do something like this:
import sys
sys.path.append("/path/to/numpy")
import numpy
A: The cronjob runs with an empty environment. As such, it's either not using the same python binary as you are at the shell, or you have PYTHONPATH set, which it won't have under crontab.
You should run env -i HOME=$HOME sh to get a fascimile of the cronjob's environment. Set environment variables until your command works, and record them.
You can then set these in your crontab file, again using the env command, like:
* * * * * env PYTHONPATH=/my/pythonpath OTHERVAR=correct-value /path/to/mycommand
A: Your cron job is probably executing with a different python interpreter.
Log in as you (via ssh), and say which python. That will tell you where your python is. Then have your cron job execute that python interpreter to run your script, or chmod +x your script and put the path in a #! line at the top of the script.
A: Processes invoked by the cron daemon have a minimal environment, generally consisting of $HOME, $LOGNAME and $SHELL.
It sounds like numpy is perhaps somewhere on your $PYTHONPATH? If so, you will need to specify that within the crontab line. Such as
/usr/bin/env PYTHONPATH=... <then the command to run>
If you are on a Linux system using vixie cron, then you can also specify global variables in your crontab by using lines such as
# my environment settings
PYTHONPATH = <path>
SOMETHING_ELSE = blah
<then my normal cron line>
See man -s 5 crontab
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MPMoviePlayerController does not load first video in scrolling gallery I'm developing on iOS SDK 4.3.
I have an horizontally-scrolling paged gallery that can display images or videos from a remote feed. For the paged views I'm using the publicly available ATPagingView: pages are reused similarly to TableViewCells. But for the videos I'm using a single MPMoviePlayerController, whose .view property I assign to the several pages as a subview (I know, I know...):
moviePlayerController = [[MPMoviePlayerController alloc] init];
moviePlayerController.repeatMode = MPMovieRepeatModeNone;
moviePlayerController.controlStyle = MPMovieControlStyleEmbedded;
moviePlayerController.shouldAutoplay = false;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieLoadStateChangeAction:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
You can see I've registered for MoviePlayer event LoadState notifications.
When a new page goes onscreen, I start loading a video if needed:
- (void)currentPageDidChangeInPagingView:(ATPagingView *)pagingView
{
if (pagingView.currentPageIndex < 0)
return;
NSLog(@"currentPageDidChangeInPagingView");
GalleryPageView *currentPage = (GalleryPageView *)[pagingView viewForPageAtIndex:pagingView.currentPageIndex];
if (![currentPage.gestureRecognizers count]) {
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resetZoom)];
recognizer.numberOfTapsRequired = 2;
[currentPage.zoomView addGestureRecognizer:recognizer];
recognizer.delegate = self;
[recognizer release];
}
moviePlayButton.hidden = YES;
[activityView stopAnimating];
FeedItem *feedItem = (FeedItem *)[dataRoot objectAtIndex:pagingView.currentPageIndex];
if (feedItem.contentType == FeedContentTypeMovie) {
moviePlayerController.contentURL = [NSURL URLWithString:feedItem.movieUrl];
[moviePlayerController prepareToPlay];
[activityView startAnimating];
}
Now, IFF the first page contains a video, even after I call moviePlayerController.prepareToPlay, it doesn't load: no loadState event is fired. Following pages instead work as expected.
I've tried to pre-load a fixed video on MPlayerController initialization, but in that case the fixed video is correctly loaded (MPMovieLoadState == 3), while video on first page causes a change to MPMovieLoadStateUnknown.
The movie URL is correct.
When I scroll back from page 2 to page 1, first video is loaded (MPMovieLoadState == 3), but it doesn't show.
What do you suggest investigating? Is the shared-view architecture so horrible? It works for the following pages, after all. Is there any known weird behavior by prepareToPlay? For example, is it possible MPC gets angry if the view is "mistreated" by anyone, and then it refuses to load stuff? How else would you explain MPMovieLoadStateUnknown? I'm pretty sure there is no other ghost instance of MPC messing around (I've read it could be a problem).
Thank you and sorry for the long post.
A: I had to end up using AVPlayer because of something very similar to this in my code.
A: I had the same problem. In iOS7 this does not happen, but in iOS 6 loadState is 3, which is not contemplated in:
enum {
MPMovieLoadStateUnknown = 0,
MPMovieLoadStatePlayable = 1 << 0,
MPMovieLoadStatePlaythroughOK = 1 << 1, // Playback will be automatically started in this state when shouldAutoplay is YES
MPMovieLoadStateStalled = 1 << 2, // Playback will be automatically paused in this state, if started
};
typedef NSInteger MPMovieLoadState;
I had autoplay set to NO and use prepareToPlay waiting for the notifications to play, so when MPMoviePlayerLoadStateDidChangeNotification is received, before playing, I check the loadState like this:
if (self.moviePlayerC.loadState & MPMovieLoadStatePlayable || self.moviePlayerC.loadState & MPMovieLoadStatePlaythroughOK)
Maybe in iOS6 loadState is a bitWise value that can contains several states at the same time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why does PHP have no length argument on functions which deal with binary data? Why is it that functions that deal with binary data dont have length arguments? I come from a C background, so this is really confusing me. I thought that perhaps the string object holds the length, but that doesnt appear to be the case (correct me if im wrong). Two examples of functions that exhibit this behavior are base64_encode/decode and bin2hex.
Thanks!
A: php's string objects hold the length internally. You can get this value by calling strlen, but since php has automatic management, you rarely need to worry about that:
echo strlen("a\0b\0c"); // 5
A: PHP strings are not like C-strings.
It's been a while since I thought about the internals. As I remember, php variables are known as "zvals", which is basically a struct that tracks things like the datatype, length, and the data themselves.
So internally (at least down to a pretty low level), PHP probably avoids relying on null-termination to know where a string ends.
EDIT: Here's an old article that discusses some of the internal implementation of userspace variables in PHP
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: adding UILabel in Objective-C, change Background Color I add a UILabel using objective c, have a white rectagle around them. How do I remove this rectangle so the background shows through?
I looked in the documnetion for uilabel view and did not see anything per to background.
code
UILabel *mContact=[ [UILabel alloc] initWithFrame:CGRectMake(273,442,32,20)];
mContact.text=@"Contact";
mContact.font=[UIFont fontWithName:@"Helvetica" size:9.0 ];
[self.view addSubview:mContact];
-Ted
A: UILabel has a background property it inherits from UIView, set it to clear:
@property(nonatomic, copy) UIColor *backgroundColor
mContact.backgroundColor = [UIColor clearColor];
A: Try this out:
myLabel.backgroundColor = [UIColor clearColor];
--or--
myLabel.backgroundColor = [UIColor whateverColorYouWant];
Also, check out the UILabel Class Reference
A: [mContact setBackgroundColor:[UIColor clearColor];
//or
mContact.backgroundColor = [UIColor clearColor];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using RSA for hash I am pondering creating a hash function (like md5 or sha1) using the RSA crypto algorithm. I am wondering if there are any obvious reasons that this algorithm wouldn't work:
*
*Generate RSA public/private keys.
*Discard private key, never store it at all.
*Begin with a hash with a length of the block size for the RSA encryption.
*Encrypt message using public key, one block at a time.
*For each encrypted block of the message, accumulate it to the hash using a specified algorithm (probably a combination of +, xor, etc.)
To verify a message has the same hash as a stored hash, use the saved public key and repeat the process.
Is this possible, secure, and practical?
Thanks for any comments.
A: RSA encryption is not deterministic: if you follow the RSA standard, you will see that some random bytes are injected. Therefore, if you encrypt with RSA the same message twice, chances are that you will not get twice the same output.
Also, your "unspecified step 5" is likely to be weak. For instance, if you define a way to hash a block, and then just XOR the blocks together, then A||B and B||A (for block-sized values A and B) will hash to the same value; that's collision bonanza.
Academically, building hash functions out of number-theoretic structures (i.e. not a raw RSA, but reusing the same kind of mathematical element) has been tried; see this presentation from Lars Knudsen for some details. Similarly, the ECOH hash function was submitted for the SHA-3 competition, using elliptic curves at its core (but it was "broken"). The underlying hope is that hash function security could somehow be linked to the underlying number-theoretic hard problem, thus providing provable security. However, in practice, such hash functions are either slow, weak, or both.
A: There are already hashes that do essentially this, except perhaps not with the RSA algorithm in particular. They're called cryptographic hashes, and their salient point is that they're cryptographically secure - meaning that the same strength and security-oriented thought that goes into public key cryptographic functions has gone into them as well.
The only difference is, they've been designed from the ground-up as hashes, so they also meet the individual requirements of hash functions, which can be considered as additional strong points that cryptographic functions need not have.
Moreover, there are factors which are completely at odds between the two, for instance, you want hash functions to be as fast as possible without compromising security whereas being slow is oftentimes seen as a feature of cryptographic functions as it limits brute force attacks considerably.
SHA-512 is a great cryptographic hash and probably worthy of your attention. Whirlpool, Tiger, and RipeMD are also excellent choices. You can't go wrong with any of these.
One more thing: if you actually want it to be slow, then you definitely DON'T want a hash function and are going about this completely wrong. If, as I'm assuming, what you want is a very, very secure hash function, then like I said, there are numerous options out there better suited than your example, while being just as or even more cryptographically secure.
BTW, I'm not absolutely convinced that there is no weakness with your mixing algorithm. While the output of each RSA block is intended to already be uniform with high avalanching, etc, etc, etc, I remain concerned that this could pose a problem for chosen plaintext or comparative analysis of similar messages.
A: Typically, it is best to use an algorithm that is publicly available and has gone through a review process. Even though there might be known weaknesses with such algorithms, that is probably better than the unknown weaknesses in a home-grown algorithm. Note that I'm not saying the proposed algorithm has flaws; it's just that even if a large number of answers are given here saying that it seems good, it doesn't guarantee that it doesn't. Of course, the same thing can be said about algorithms such as MD5, SHA, etc. But at least with those, a large number of people have put them through a rigorous analysis.
Aside from the previous "boilerplate" warnings against designing one's own cryptographic functions, it seems the proposed solution might be somewhat expensive in terms of processing time. RSA encryption on a large document could be prohibitive.
A: Without thinking too much about it, it seems like that would be cryptographically secure.
However, you'd have to be careful of chosen plaintext attacks, and if your input is large you may run into speed issues (as asymmetric crypto is significantly slower than cryptographic hashes).
So, in short: yes, this seems like it could be possible and secure… But unless there is a really compelling reason, I would use a standard HMAC if you want a keyed hash.
A: As mentioned above step 4.) is to be done deterministic, i.e. with modulus and public key exponent, only.
If the hash in step 3.) is private, the concept appears secure to me.
Concerning Step 5.): In known CBC mode of kernel algorithms the mix with previous result is done before encryption, Step 4.), might be better for avoiding collusions, e.g. with a lazy hash; XOR is fine.
Will apply this, as available implementations of known hash functions might have backdoors :)
Deterministic Java RSA is here.
EDIT
Also one should mention, that RSA is scalable without any limits. Such hash function can immediately serve as Mask Generation Function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: jQuery/XML return the current target li id from an xml node for individual functions I need to return the current value of the selected video-thumb li, so if I click on the 2nd li return id is 2 etc. What I currently have returns 2 if I select both the first and second li. I will eventually need to fire a different function depending on the selected li. If this is totally off on reaching that goal please point me in the correct lead.
What I am trying to accomplish: I parse the xml and then display it on the page (append it to #container). Within the appended html, li are added. Upon this addition I need to iterate to the correct target li. So if I click target li with the xml id of 3 I need to fire a function for only that target li and so on for all iterated xml nodes. Any direct as always is greatly appreciated.
Thanks!
jQuery:
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="js/video-js/video.js"></script>
<link rel="stylesheet" href="js/video-js/video-js.css" type="text/css" media="screen" title="Video JS" charset="utf-8">
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "videos.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('videos').each(function(){
var title = $(this).find('title').text();
var id = $(this).find('id').text();
var url = $(this).find('url').text();
var url2 = $(this).find('url2').text();
var desc = $(this).find('desc').text();
//alert(url2);
$('#container').append('<div id="desc">'+title+'<br>'+desc+'</div><video class="video-js" width="740" height="400" controls="controls" preload="true"><source src="'+url+'"/><source src="'+url2+'"/></video><li class="video-thumb">'+id+'</li>');
$('.video-thumb').click(function() {
if(id == 2){
alert("click = " + id);
} else {
return false
alert("loser");
}
})
});
}
});
//VideoJS.setupAllWhenReady();
});
XML:
<xml>
<videos>
<title>title one</title>
<id>1</id>
<url>videos/video1.mp4</url>
<url2>videos/video1.webm</url2>
<desc>111 Writing things in here. Writing things in here. Writing things in here.</desc>
</videos>
<videos>
<title>title 2</title>
<id>2</id>
<url>videos/video1.mp4</url>
<url2>videos/video1.webm</url2>
<desc>2 Writing things in here. Writing things in here. Writing things in here.</desc>
</videos>
<videos>
<title>title 3</title>
<id>3</id>
<url>videos/video1.mp4</url>
<url2>videos/video1.webm</url2>
<desc>3 Writing things in here. Writing things in here. Writing things in here.</desc>
</videos>
<videos>
<title>title 4</title>
<id>4</id>
<url>videos/video1.mp4</url>
<url2>videos/video1.webm</url2>
<desc>4 Writing things in here. Writing things in here. Writing things in here.</desc>
</videos>
</xml>
A: You're binding a click handler to each list item that is being added. That is fine, but instead you could add only one handler to the outermost element that will catch all clicks, and depending on which li was clicked, you can take the appropriate action.
Here's some code to get you started,
$(xml).find('videos').each(function() {
// create HTML and add this video to the page
});
// Add just one click handler to the container node.
$("#container").delegate(".video-thumb", "click", function() {
// get the id from the text of the li node that was just clicked.
var id = $(this).text();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to bind a jQuery plugin to an element in ASP.NET code? I have a jQuery plugin which works like most plugins in this format
$(somelement).SomePlugin(some options); one of the options is a string.
Now I have a situation where the string is determined during runtime in ASP.NET in code behind and it's different for each element. This could be done in OnItemDataBound of a server control. There could be tens of them in the page.
How do I bind the jQuery plugin in code behind?
Addition:
Each 'someelement' can have a different id.
A: I would recommend you use the HTML5 data attribute. For example:
<li data-thestringoption="some String"></li>
<li data-thestringoption="some other String"></li>
Then, when you invoke your plugin, you can use that data attribute:
$('li').each(function() {
$(this).SomePlugin({
someOption: 32,
theStringOption: $(this).data('thestringoption')
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rebasing everyone onto changed git history after filter-branch Our git repo has a bunch of large files in its history that are no longer needed. I want to remove them using the filter-branch technique explained in Pro Git:
http://git-scm.com/book/en/v2/Git-Internals-Maintenance-and-Data-Recovery
I'll then use git push --force all to send this to our shared repo, as explained here:
Update a development team with rewritten Git repo history, removing big files
BUT. Pro Git says I'll need to have everyone rebase since I'm changing history. We've only sparingly used rebase, usually just as an alternative way to merge. I can have everyone re-clone, but that's a last resort; several devs have local branches with changes they'd like to keep.
So: What exactly will everyone need to do in our local repositories to rebase onto the newly-changed shared repo? And do we have to do it once per tracking branch? Our repo is referred to as origin and the master branch is master, if you want to give step-by-steps (and I'd love it if you would).
A: Here is an option.
*
*Create your rebased master on a branch called rebased_master (instead of your original master).
*You would than push that branch and have all your developers pull it down and rebase their local branches onto rebased_master. If they rebase them off the equivalent commit from before the rebase, and didn't have any changes to the files you are removing, all should be well.
*Once everyone has moved their dev branches to rebased_master, you can delete your original master and move rebased_master to master
note: I haven't tested this, so make sure you have a copy of your repo to restore in case something goes wrong.
A: The key is for each individual developer not to lose their original reference to master until after they've done their rebase. To do this, have them do a fetch (not a pull) after the forced push, then for each local branch, do:
git rebase --onto origin/master master <local_branch>
When that's done, then they can checkout their master and update it by:
git pull --force
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How to set the plot in matlab to a specific size? Generally, I wish to plot a rather complex x-y plot (lots of overlapping curves) to an A3 format so:
A4 210x297
A3 = A4*2 = 420 x 297
... - 10mm each side = 400 x 277 (size of desired plot window)
What is the easiest way to set the size of the plot so it fits that size when printed in PDF (or any other common output format)?
A: See the matlab documentation for figure properties.
Namely:
*
*PaperSize - Explicitly defines the size of the canvas.
*PaperType - Sets PaperSize to one of several standard paper sizes.
The built in plot tool lets you save figures as all sorts of image formats so you should be good to go. Fiddling with the above settings should get your figure to be the correct size for printing.
Happy plotting!
A: As @LewisNorton explained, you need to set the Paper*** properties of the figure. Below is an example for producing a PDF file with dimensions 420 x 297 mm (A3 size), where the margins between the plot and the file borders are 10 mm each (top,bottom,left,right).
%# centimeters units
X = 42.0; %# A3 paper size
Y = 29.7; %# A3 paper size
xMargin = 1; %# left/right margins from page borders
yMargin = 1; %# bottom/top margins from page borders
xSize = X - 2*xMargin; %# figure size on paper (widht & hieght)
ySize = Y - 2*yMargin; %# figure size on paper (widht & hieght)
%# create figure/axis
hFig = figure('Menubar','none');
plot([0 1 nan 0 1], [0 1 nan 1 0]), axis tight
set(gca, 'XTickLabel',[], 'YTickLabel',[], ...
'Units','normalized', 'Position',[0 0 1 1])
%# figure size displayed on screen (50% scaled, but same aspect ratio)
set(hFig, 'Units','centimeters', 'Position',[0 0 xSize ySize]/2)
movegui(hFig, 'center')
%# figure size printed on paper
set(hFig, 'PaperUnits','centimeters')
set(hFig, 'PaperSize',[X Y])
set(hFig, 'PaperPosition',[xMargin yMargin xSize ySize])
set(hFig, 'PaperOrientation','portrait')
%# export to PDF and open file
print -dpdf -r0 out.pdf
winopen out.pdf
Without a printer at hand, I am using a virtual screen ruler to check the measurements; Simply display the PDF file with your preferred viewer, and the set the zoom level at 100% (I am using Sumatra PDF). If you want to try this yourself, just be aware that some viewers (Adobe Reader) might be using a custom DPI not matching the system default resolution (mine at 96 pixels/inch).
Here you can see the bottom and left margins equal to 10mm. The same holds for the other two margins:
Note that in the example above, I made the axis cover the entire figure (no gray area in the figure). By default, MATLAB leaves some empty space for tick labels, axis labels, title, etc.. This is of course different from the margins mentioned above, which I assume you already know :)
A: Download export fig(Requires Ghostscript).
Try running:
surf(peaks);title('voila');export_fig 'test.pdf';
When using Adobe to print the pdf file, set 'Page Scaling' to 'Fit to Printable Area'.
A: If you want a custom shape (e.g. for a long, thin plot or for a square plot to include in another file), set both the PaperSize and PaperPosition options.
set(gcf, 'PaperSize', [30 10], 'PaperPosition', [0 0 30 10])
print -pdf filename
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7561999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Correct HTTP Status Code when rejecting a request because User-Agent header is invalid I'm currently working on an HTTP based API. Our terms of use require the user to send an appropriate user-agent header (e.g. "-" is considered invalid). Now I'm not quite sure which would be the correct HTTP status the server should be responding with, if the request is rejected. Any suggestions?
A: 400 Bad Request or 403 Forbidden would be the two I'd pick
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Sessions vanishing when doing a header redirect with php Only impacts Internet Explorer and Firefox (works in chrome and opera).
When I try to do a header redirect the session is dropped. For an example I wrote the small bit of code below as a test...
Page1 (test.php)
<?php
session_start();
$_SESSION['testvar']=true;
session_write_close();
//header('Location: ./test2.php');
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'test2.php';
header("Location: http://$host$uri/$extra");
exit;
//header('Location: http://' .$_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT']. '/test2.php');
//header('Location: http://192.168.1.111:78/test2.php');
?>
Page2 (test2.php)
<?php
session_start();
echo $_SESSION['testvar'];
echo "<br>test Page #2 (You should see a 1 above if it worked!)<br><br>";
?>
I have literally tried absolutely everything I can think of (and or google).
A: First As other guys told, you have to check php.ini file for the dir that stores the session handlers
there is fragment from php.ini file that shows what to do:
Handler used to store/retrieve data.
session.save_handler = files
; Argument passed to save_handler. In the case of files, this is the path
; where data files are stored. Note: Windows users have to change this
; variable in order to use PHP's session functions.
;
; As of PHP 4.0.1, you can define the path as:
;
; session.save_path = "N;/path"
;
; where N is an integer. Instead of storing all the session files in
; /path, what this will do is use subdirectories N-levels deep, and
; store the session data in those directories. This is useful if you
; or your OS have problems with lots of files in one directory, and is
; a more efficient layout for servers that handle lots of sessions.
;
; NOTE 1: PHP will not create this directory structure automatically.
; You can use the script in the ext/session dir for that purpose.
; NOTE 2: See the section on garbage collection below if you choose to
; use subdirectories for session storage
;
; The file storage module creates files using mode 600 by default.
; You can change that by using
;
; session.save_path = "N;MODE;/path"
;
; where MODE is the octal representation of the mode. Note that this
; does not overwrite the process's umask.
session.save_path = "/tmp"
Note that this folder has to be created manualy with the appropriate permissions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sending user results by Email Hi I am wondering is there a way of sending the user an email (from my Gmail address) with results of calculations that occurs within the app itself?
For example a form is filled out with values for electricity rates and these rates are then computed and processed into information on savings for a particular product.
What I have is a custom alert box popup with the results and a button saying email me the results and then a EditText becomes visible below asking for the email address of the user.
Is this possible or would a simple notification be easier to do?
A: You could do it via a form or by using the JavaMail API or you could use an existing email client from the phone.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Help understanding jQuery jQuery(function ($) {..}
I am trying to learn jQuery and came across some code that started like the above statement. What does that mean?
A: That is a shortcut for:
jQuery(document).ready(function($) {
// ...
});
It sets up an event handler for when the document is ready to have its DOM manipulated. It's good practice to initiate your jQuery code after the document is ready. The first parameter $ references the jQuery object so you can use $ in place of jQuery in your code.
A: I believe this allows you to abstract $ into an anonymous function. As a few different javascript libraries use the $ syntax you don't want to create conflicts. So instead you call jQuery using its explicit identifier jQuery and pass in $. Now you can use $ all you want inside the anonymous function and not need to worry about conflicting with other libraries.
A: Jacob is correct.
Other variations you will see along with jQuery(function($){..} are
$(document).ready(function(){...}
jQuery(document).ready(function(){...}
$(function(){...}
All wait until your DOM has fully loaded.
A: Passing a function to a call to jQuery() has the effect of executing that function when the dom is ready.
The function is passed a reference to jQuery as the first parameter. So, Setting the name of the arg in that function to $ allows you to use $ as shorthand for jQuery from within your function. $ is a global reference to jQuery by default, so you only need to specify $ as a parameter in your function if you are overriding $ elsewhere, for example by using jQuery.noconflict(). This is common practice for plugin developers, since they can't be guaranteed that $ has not been overridden by the plugin consumer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is sub-domain considered cross-domain? Is http://nonsecure.form.xyz.org and https://secure.form.xyz.org considered different domain? I am asking this because my javascript in secure one cannot call it's parent. Secure domain is inside non-secure domain through an iframe.
EDIT
Conclusion
You can perform cross-domain scripting but cannot perform cross-protocol scripting (e.g. https and http)
A: What you can do here is set document.domain = "form.xyz.org" on both sides before attempting any cross-domain scripting.
However, you cannot cross-script between different protocols.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: RegEx for UK area codes. I need to be able to validate UK telephone numbers when input and present them in the correct format when displayed.
I have seen several unfathomable RegEx examples but they don't get the right format for all UK numbers or reject some valid formats (or allow some invalid formats).
I found a list of the required formats and it looks right (and a lot more complicated than I first envisaged) but how do I turn this into a "simple" RegEx pattern?
NSN length:
*
*10 mostly;
*9 for some 01xxx areas;
*9 for all 0500, some 0800;
*7 for two special 08xx numbers.
Format:
NSN = 10:
*
*(01xxxx) xxxxx
*(01xxx) xxxxxx
*(01x1) xxx xxxx
*(011x) xxx xxxx
*(02x) xxxx xxxx
*03xx xxx xxxx
*055 xxxx xxxx
*056 xxxx xxxx
*070 xxxx xxxx
*07xxx xxxxxx
*0800 xxx xxxx
*08xx xxx xxxx
*09xx xxx xxxx
NSN = 9:
*
*(016977) xxxx
*(01xxx) xxxxx
*0500 xxxxxx
*0800 xxxxxx
NSN = 7:
*
*0800 1111
*0845 46 47
Notes:
*
*01 ranges can have NSN as 10 or 9.
*0800 range can have NSN as 10, 9 or 7.
*0845 range can have NSN as 10 or 7.
A: Well the simplest (although not the most elegant) solution would be to simply concatenate your list with the | operator e.g.:
\(01\d\{4}\) \d{5}|\(01\d{3}) \d{6}|(01\d1) \d{3} \d{4}|0800 1111
The nice thing about this is that if you write a short conversion script from the list you have to the regexp then if you get a new list in the future you can re-generate the regexp without having to do complicated debugging.
Although you could optimise this by factoring out common sub-expressions, I'd only do that if you discover that performance is a problem. Which is unlikely with a decent RE engine on modern machines.
A: Take your list of valid patterns and perform these steps:
*
*Put ^ at the start of the line, and $ at the end of the line.
*Put a backslash before every parenthesis.
*Replace xxxx with [0-9]{n} where n is the number of digits.
*Join each line with |.
You can either do these steps manually, or else you can write a program to perform the steps and generate the regex for you.
For example if you have these patterns:
*
*(01xxxx) xxxxx
*(01xxx) xxxxxx
*(01x1) xxx xxxx
then the regex would be this:
^\(01[0-9]{4}\) [0-9]{5}$|^\(01[0-9]{3}\) [0-9]{6}$|^\(01[0-9]1\) [0-9]{3} [0-9]{4}$
You may also want to make the spaces optional by adding a question mark after them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to quickly insert huge datas into datastore while running on GAE development server? Background:
While coding on GAE's local Development Web Server, user need to upload Mega-level datas and store (not straight forward store, but need many format check and translate) them into Datastore using deferred library.
Usually about 50,000 entities, CSV File size is about 5MB, and I tried to insert 200 entities each time using deferred library.
And I used python.
Problem
The development server is really slow that I need to wait one/more hours to finish this upload process.
I used --use_sqlite option to speed up the development web server.
Question:
Is there any other method or tuning that can make it faster?
A: appengine-mapreduce is definitely an option for loading CSV files. Use blobstore to upload CSV file and then setup BlobstoreLineInputReader mapper type to load data into datastore.
Some more links: Python Guide to mapreduce reader types is here. The one of interest is BlobstoreLineInputReader. The only input it requires is the key to the blobstore record containing uploaded CSV file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Out of scope and Invalid Summary error on NSArray I am trying to create the UIPickerview as described in the iPhone development book by Dave Mark. I have a NSArray which is declared as a property in the h file which will store the data for the UIPickerview. So here is what I have:
in the .h file:
@interface RootViewController : UIViewController {
NSArray *dateForPicker;
}
@property (nonatomic, retain) NSArray *dateforPicker;
@end
In the .m file viewDidLoad method (I do have @synthesize for thedateForPicker property at the beginning of the .m file):
NSArray *tempArray = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
self.dateforPicker = tempArray;
[tempArray release];
When the UIPickerview comes up, it comes up with "?" in all the rows. So when I used a breakpoint to inspect the values of tempArray and dateForPicker in the viewDidLoad method, I find that the tempArray is fine but the dateForPicker never gets the values from the tempArray. Xcode says "Invalid Summary" for the dateForPicker array and has "out of scope" as the values for the five rows. What is going on? As described by the book, this should work.
Here is the code for the UIPickerView:
#pragma mark -
#pragma mark picker data source methods
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [dateforPicker count];
}
#pragma mark picker delegate methods
-(NSString *)pickView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
forComponent:(NSInteger)component{
return [dateforPicker objectAtIndex:row];
}
@end
A: Some problems with your code. I'm not clear if you've typed this into the question manually or copied and pasted from your actual code:
*
*You are setting self.dateforPicker and not self.dateForPicker, there is a difference in capitalisation between your ivar and your property. In iOS the compiler will have synthesized a dateforPicker ivar when you declared your property, which was set in your viewDidLoad, but in your other methods you may be referring to the dateForPicker ivar, which is never touched.
*Your RootViewController does not declare that it implements the UIPickerViewDataSource or UIPickerViewDelegate protocols
*Your declaration of the titleForRow method is wrong - yours begins with pickView rather than pickerView so will not get called.
If you have the correct number of rows in your component (you said multiple question marks, how many?), so it looks like the data source is wired up properly, but you also need to connect the delegate, as this is what actually supplies the values for each row. The datasource, confusingly, only supplies the number of components and the number of rows per component.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Seg fault when trying to use strtok() on a 2D array I was hoping someone could help me figure out why I am getting a segmentation fault on my code below. My user has inputted a line of text, which is passed to the parse function. The parse function should initialize a 2D array (I would ideally like to dynamically allocate the array, but for now I am making it an array of size [25][25]).
Starting at the beginning of input strtok() is called. If strtok() sees a pipe symbol, it should increase the count of pipes and go to the next row of the matrix. For example, if the user inputted foo bar | foo1 | foo2 bar1 foo2, the 2D array would look like:
array[][] = { foo, barr;
foo1;
foo2, bar1, foo2; }
Eventually I would like to pass this array to another function. However, If I actually input the above into my program, this is the result:
/home/ad/Documents> foo bar | foo1 | foo2 bar1 foo2
test1
Segmentation fault
ad@ad-laptop:~/Documents$
Thus, given where I put these debug statements, the problem is with saving the tokens? This is the first time I have worked with a 2D array so I am sure it is something wrong with my pointer logic. What can I do to fix this segmentation fault? Thanks for your time.
Code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
int MAX_PATH_LENGTH = 1024; //Maximum path length to display.
int BUF_LENGTH = 1024; // Length of buffer to store user input
char * delims = "|"; // Delimiters for tokenizing user input.
const int PIPE_READ = 0;
const int PIPE_WRITE = 1;
void execute(char *args, int numPipes, int numArgs){
int i;
int j;
for(i = 0; i <= numArgs; i++){
for(j = 0; j < 25; j++){
printf("args[%d][%d]", i, j);
}
}
}
void parse(char *input) {
char argArray[25][25];
int numPipes = 0;
int i = 0;
int j = 0;
char *tokenPtr = NULL;
tokenPtr = strtok(input, delims);
while(tokenPtr != NULL) {
if(strcmp(tokenPtr, "|") == 0){ //is token a pipe?
numPipes++;
i++;
j = 0;
}
else {
argArray[i][j++] = *tokenPtr;
printf("test1\n");
tokenPtr = strtok(input, NULL);
printf("test2\n");
}
}
execute(*argArray, numPipes, i);
}
int main () {
char path[MAX_PATH_LENGTH];
char buf[BUF_LENGTH];
char* strArray[BUF_LENGTH];
while(1) {
getcwd(path, MAX_PATH_LENGTH);
printf("%s> ", path);
fflush(stdout);
fgets(buf, BUF_LENGTH, stdin);
parse(buf);
bzero(strArray, sizeof(strArray)); // clears array
}
}
A: Only the first call to strtok should receive the input. Subsequent calls (while parsing the same string) should have NULL as their first argument.
A: You misread the manpage for strtok:
In each subsequent call that should parse the same string, str should be NULL.
And you did: tokenPtr = strtok(input, NULL);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Entity Framework - Problems to update user information I'm new to Entity Framework, and I have to update a record in my database. I used the "Edit" example generated by the MVC3 framework and tried to customize to my needs.
I have a password field and before submit it to update I need to encrypt it with MD5. All process is running ok, except for the db.SaveChanges(); it saves the data posted by the form. Doesn't matter if I try to change the password, the framework just ignore that and save the data as it was posted in the form.
My .cshtml file:
<div class="editor-label">
@Html.Label("password", "Senha")
</div>
<div class="editor-field">
@Html.Password("password")
</div>
My method:
[HttpPost]
public ActionResult Editar(FormCollection form)
{
var newPassword = form["password"];
var email = Session["email"].ToString();
UserSet user = db.UserSet.SingleOrDefault(m => m.Email == email);
if (ModelState.IsValid)
{
//Changing password
user.Password = Crypto.CalculateMD5Hash(newPassword);//this line is ignored
TryUpdateModel(user);
db.SaveChanges();
return Redirect("~/Home/Mural");
}
return View(user);
}
What am I missing?
A: Your line
TryUpdateModel(user);
Will overwrite anything you've done on your model prior.
Change the order to
TryUpdateModel(user);
user.Password = Crypto.CalculateMD5Hash(newPassword);//this line is ignored
And it'll probably work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: API for getting movie soundtrack list Is there any free API for getting the list of soundtracks from a given movie?
Thanks
A: IMDB seems to be the best place for soundtrack lists.
This might be what you want:
http://www.deanclatworthy.com/imdb/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: web analytics software which can analyze existing log archives too I am looking for a web analytic solution which can also help me to analyze my existing log files. we are moving from sawmill to other solutions.. explored Google Urchin and it has some limitations on analyzing custom existing logs.
Currently exploring webtrends, but i am not sure if it supports custom log analysis
any ideas??
A: WebTrends will not support custom log formats. Maybe the best way with WebTrends would be to use the Data Collector and/or the API from the Data Collector. Or you put your specific informations within the URL as the Data Collector would do. Here is the link to the API: http://product.webtrends.com/dcapi/sw/index.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: rails - email activation upon user signup I want the user to click on an activation link before being "activated" or before they can log in with the email/password.
I am not using an gems and want to keep it that way. My problem is that after the user registers, they can login in without clicking on the activation code. I have an confirmation_token line and a confirmed line to the model.
user controller:
def create
@user = User.new(params[:user])
if @user.save
render "root_path"
else
render "new"
end
end
def confirmed
user = User.find(:first, :conditions => {:confirmation_token => params[:confirmation_token]})
if (!params[:confirmation_token].blank?) && user && !user.confirmed?
user.confirmed!
self.current_user = user
flash[:notice] = "Thank you. You account is now activated."
redirect_to account_preference_path(current_user)
else
flash[:notice] = "Sorry we don't have your email in our database."
redirect_to root_path
end
end
user model:
def confirmed!
self.confirmed = true
self.confirmation_token = nil
save(false)
end
Am I missing anything? Thanks!
I know there are gems like devise, auth-logic, etc out there but I want to learn how to write it from scratch. Thanks.
EDIT:
session controller
def create
user = User.authenticate(params[:email], params[:password])
if user && user.confirmed == true
cookies.permanent.signed[:remember_token]
redirect_to account_path(user.id), :notice => "Welcome, #{user.first_name}"
else
flash.now.alert = "Invalid email or password."
render "new"
end
end
A: Of course, after much trial and tribulation, I figured it out. Before, I was redirecting the routes to a new controller where they can edit their password instead of just sending them to the route that just confirms the code. Silly mistake that cost me a lot of headache, but live and learn. Thanks everyone who looked into it.
A: You might want to search for some tutorials to at least guide you through the process, you'll get a better feel for coding rails correctly.
Basically your problem is that your not doing a check to see if the user is confirmed or not on login. One way would be to add this inside your session create method.
if user && user.confirmed?
The best solution though is probably to use filters like this
before_filter :authenticate, :only => [:new, :create, :edit, :destroy]
Then you have an authenticate method that checks for a current user, and then have logic that says the current_user can only be a confirmed user. This will check that the user is valid on all the pages that they need to be, instead of only on login.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: CodeIgniter - modular? I'm building several sites that need similar "modules." For example, the sites may have the exact same login system, forum, etc.
Is there a way I could build these modules once and just "drop" them in these various sites? Some of the challenges I see:
*
*Keeping the code consistent in the various sites. Any changes made to a module should propagate to all of the sites using that module. I guess I need a way to upgrade?
*Database: these functionality need to work as part of a bigger application. Maybe the module needs to define relationships with other tables in its respective site.
I'm sure there are more problems. I think I should be looking at this: https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/wiki/Home, but I don't have any experience with it.
So, I'm looking for solutions, suggestions, or more problems to this idea.
A: I would write them as libraries and use Git submodules to manage each module. Phil Sturgeon actually just wrote a great post about doing this in CodeIgniter.
If you're not using version control, I can't see an easy way to sync across all of your applications. Yes, HMVC will let you break apart your application into actual modules, but it won't help in syncing those modules across your applications.
A: You can create and use third party packages by adding them to the third party folder (which is new for CI 2). There is not much about it in the docs, but i found this.
http://codeigniter.com/user_guide/libraries/loader.html
You can autoload the third party packages in the autoload file. Packages can have their own controllers, models, views etc.
Interestingly, Phil Sturgeon wrote a bit (http://philsturgeon.co.uk/blog/2010/04/codeigniter-packages-modules) about packages not being modules (in the strict sense of the term), but you could probably use third party packages for what you need.
A: Here is my question about 'Database communication in modular software'
that you may find useful.
I'm little bit familiar with Drupal, and as a modular application, I think it can be taken as good example of how relationships between modules should be defined.
Here is one good post about art-of-separation-of-concerns
I would like to hear if you have run into some concrete challenges, solutions and references concerning modular design in CI.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How could I add this attribute? I have a class that is called ShapeBase. It is abstract and draw method must be implemented. It has instance variables for things like width and height. From this, Circle, Line, and Rectangle are subclasses and implement the draw method. The Line class does not have an isFilled property (get / set) but Rectangle, and Circle do. I could obviously just add the property to both separatly, but later on I may want to dynamically gather all shapes that can be 'filled'. I thought of making a filled interface but, the problem is then I have to implement the getter and setter for both. In C++ I'd make use of multiple inheritance to solve this, but what can I do in Java to solve this kind of problem?
Thanks
A: You could have a FillableShapeBase which is abstract and extends ShapeBase but has the added isFilled property with getters and setters. Rectangle and Circle could inherit from FillableShapeBase.
A: public abstract class FillableShape extends Shape {
// isFilled
}
public class Circle extends FillableShape {
....
}
public class Rectangle extends FillableShape {
....
}
A: Why not simply make FilledShape an abstract class that inherits from ShapeBase and implements isFilled?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it okay for a model to populate its own properties? If I have a model that essentially represents a single row in a database, is it scale-friendly and test-friendly, and all around okay practice to have it populate it's own properties, or should it have its properties injected, the same way you would inject an object?
Example:
Class blog {
$id;
$title;
$body;
public function load($id) {
// db query to load id, title, body
}
}
OR
Class blog {
$id
$title
$body
}
// load blog data into $data, and then...
$blog = new Blog($data)
A: If you want to de-couple the data storage layer from the models itself, you should make it injectable.
If the models are the data storage abstraction, you don't need to care, you only need to inject the models which then should have defined interfaces so you have the rest of your application testable.
But it merely depends on your needs and your design.
A: It's considered a bad practice to commingle database access inside your model classes directly. Injecting values is generally preferred.
That said, if you were dead set on doing something like $model->load($id) and having it fetch from a datasource, you could get away with something like:
class Model {
private $_dataProvider;
// inject data-provider dependency in constructor
public function __construct($dataProvider){
$this->_dataProvider = $dataProvider;
}
public function loadById($id){
$myData = $this->_dataProvider->loadDataById($id);
$this->setFoo($myData['foo']);
...
}
}
By injecting a data access class, you can pass a mock in for testing, or replace your database with some web service, or whatever. As long as $dataProvider has a loadDataById() method that takes an int and returns the appropriate data structure, you're good.
Personally, I prefer keep my models nice and focused on representing whatever it is they're modeling. I rely on external service classes and repositories to load data, inject it into models, and return them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DB4O performance retrieving a large number of objects I'm interesting in using DB4O to store the training data for a learning algorithm. This will consist of (potentially) hundreds of millions of objects. Each object is on average 2k in size based on my benchmarking.
The training algorithm needs to iterate over the entire set of objects repeatedly (perhaps 10 times). It doesn't care what order the objects are in.
My question is this: When I retrieve a very large set of objects from DB4O, are they all loaded into memory, or are they pulled off disk as needed?
Clearly, pulling hundreds of millions of 2k objects into memory won't be practical on the type of servers I'm working with (they hvae about 19GB of RAM).
Is Db4o a wise choice here?
A: db4o activation mechanism allows you to control which object are loaded into memory. For complex object graphs you probably should us transparent activation, where db4o loads an object into memory as soon as it is used.
However db4o doesn't explicit remove object from memory. It just keeps a weak reference to all loaded objects. If a object is reachable, it will stay there (just like any other object). Optionally you can explicitly deactivate an object.
I just want to add a few notes to the scalability of db4o. db4o was built for embedding in application and devices. It was never built for large datasets. Therefore it has its limitations.
*
*It is internally single-threaded. Most db4o operation block all other db4o operations.
*It can only deal with relatively small databases. By default a database can only be 2GB. You can increase it up to 127 GB. However I think db4o operates well in the 2-16 GB range. Afterwards the database is probably to large for it. Anyway, hundreds of millions of 2K objects is way to large database. (100Mio 2K obj => 200GB)
Therefore you probably should look at larger object databases, like VOD. Or maybe a graph database like Neo4J is also a good choise for your problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Puzzling Problem - C# Lambda Delegates disappearing after I can't post a full working example right now, but I was hoping someone would have an idea of what might be going on here. (I'll try to toss together a small working sample later this evening if no one can explain what might be happening from what's posted)
List<CVENT.Idea> ideas = ideaDAL.GetList(filter);
foreach (CVENT.Idea idea in ideas) // Setup foreign key mapping
BuildRelationships(idea, 8);
// Breakpoint set on next line.
ideas = (from idea in ideaDAL.GetList(filter)
where IdeaSatisfiesCriteria(idea,filter)
select idea).ToList();
// I then Run To Cursor to This Line so I get a before and after the previous line.
foreach (CVENT.Idea idea in ideas) // Setup foreign key mapping
BuildRelationships(idea, 8);
return ideas;
So I am loading some ideas from our DAL layer. This works fine. I then have a "BuildRelationships" function that assigns some Lambda expressions to Func delegate variables for each idea.
In Build Relationships function
private CVENT.Idea BuildRelationships(CVENT.Idea idea, int userID)
{
idea.MapComments = thisIdea => commentBLL .GetList(thisIdea.IdeaID, userID).ToList();
return idea;
}
In my idea entity
public Func<Idea, List<Comment>> MapComments { get; set; }
This is a read only implementation of a Foreign Key Mapping Pattern where I am injecting the initialization for the foreign keys into my entity so that it can lazy load the foreign entity on demand.
The problem is that after the line I have the first breakpoint set on all of the Mapping variables are cleared to null (hence the second call to remap the relationships). I am guessing it has something with the creation of a new list because of ToList(), but what I don't understand is why the Mapping delegate variables aren't getting carried over with the rest of the properties. Any ideas?
(IdeaSatisfiesCriteria only does comparisons nothing is getting changed within the function.)
A: ideas = (from idea in ideaDAL.GetList(filter)
where IdeaSatisfiesCriteria(idea,filter)
select idea).ToList();
All the mappings disappear because you are re-querying your ideas from the DAL instead of taking the existing list to which you applied the mappings. You probably intended to do this:
ideas = (from idea in ideas
where IdeaSatisfiesCriteria(idea,filter)
select idea).ToList();
A: You haven't really shown enough code to make it clear what's going on, but when you reassign ideas here:
ideas = (from idea in ideaDAL.GetList(filter)
where IdeaSatisfiesCriteria(idea,filter)
select idea).ToList();
That isn't using the previous objects referred to within ideas at all as far as I can see... it's creating completely new objects, so why would you expect it to carry over any other properties? Presumably the other properties are being populated from a database - whereas you don't have anything in the database for the mappings, which is why you have to call BuildRelationships in the first place.
Basically, unless your DAL is meant to do some caching of the objects it's created, you're creating two lists of entirely different objects - so anything which isn't populated by whatever's creating the objects in the first place isn't going to be set.
Just to be clear, this has nothing to do with it being a lambda expression or a delegate - if you had any other sort of property which wasn't stored in the database, that would be "lost" too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create a menu 'toolbar' like on the default Google homepage? I am trying to create a homepage with a 'toolbar' look like the one that is used in the default google homepage.
I have managed to put some HTML and CSS together, but I still have not been able to work out how to do the following two things:
*
*How to "gray out" the background of the menu item as the mouse hovers over it (like in the Google page)
*How to implement a nested menu. With this, I suspect that this may not be possible with CSS alone and so I may need to use javascript (in which case, I'll use jQuery)
The menu structure is like this:
Menu 1 Menu 2
Menu 1 Sub Item 1 Menu 2 Sub item 1
Menu 1 Sub Item 2 Menu 2 Sub item 2
Menu 2 Sub Item 2 Sub Item 1
Menu 2 Sub Item 2 Sub Item 2
Menu 2 Sub Item 3
Here is the (HTML and CSS) I have come up with so far:
<html><head>
<style type="text/css">
*{
padding:0px;
margin:0px;}
h2, h3{
color: #1f497d;
padding: 10px 0px 10px 0px;
}
body{
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #52525c;
line-height: 18px;
}
#navigation{
background-color: #2d2d2d;
color: #FFFFFF;
height: 25px;
list-style-type: none;
font-size: 13px;
}
#navigation ul li {
list-style-type: none;
padding: 5px 20px 3px 5px;
float: left;
}
#navigation a{
color: #CCCCCC;
text-decoration: none;
}
#navigation a:hover, a:visited, a:active{
color: #FFFFFF;
border-bottom-color: #c00000;
border-bottom-width: 2px;
border-bottom-style: solid;
}
#navigation a.current{
color:#FF0000;}
.tab{
width: 10%;
float: left;
text-align: center;
font-size: 16px;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #CCCCCC;
border-right-width: 1px;
border-right-style: solid;
border-right-color: #CCCCCC;
border-left-width: 1px;
border-left-style: solid;
border-left-color: #CCCCCC;
}
.tab2{
float: right;
width: 8%;
text-align: center;
margin: 2px;
background-color: #EFEFEF;
color: #336699;
}
</style>
</head>
<body>
<div>
<div id="navigation">
<ul>
<li class="current"><a href="#">Menu Item 1</a></li>
<li> <a href="#">Menu Item 2</a></li>
<li><a href="#">Menu Item 3</a></li>
<li><a href="#">Menu Item 4</a></li>
<li><a href="#">Menu Item 5</a></li>
<li><a href="#">Menu Item 6</a></li>
<li><a href="#">Sign in</a></li>
</ul>
</div>
</div>
</div>
</body></html>
Can someone help me with how to implement 1 and 2?
A:
Can someone help me with how to implement 1
1. How to "gray out" the background of the menu item as the mouse hovers over it (like in >the Google page)
a:hover
{
background-color:gray;
}
Hope that helps, I'll work on number 2
A: For number 2, you can make a pure CSS nested menu like this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Require file including variable I am currently using the following code to include a file in my webpage:
require_once $_SERVER['DOCUMENT_ROOT'] . '/include/file.php';
However, I have now edited my system so I input the URL into a data file in the root which makes other parts of my site function and allows me to use different directories.
In short, I am using a splash page on a website, where the root is now /directory rather than in the root, thus the URL in my data file is http://www.domain.com/directory.
So, what I need to work out is how to point this line at the directory using the variable from the data file which contains the URL
So $_SERVER['DOCUMENT_ROOT'] becomes irrelevant because I need to grab the data from the variable in the data file which is NOT in the root anymore.
It needs to be something like:
require_once (variable from file a few directories back) + absolute path to file;
I want this line of code to be future-proof too, if I need to build a site using a different directory then the root.
I hope that makes sense!
A: Create a SITE_ROOT and use that instead. That way, it will work with any directory change.
define('SITE_BASE', '/directory/');
define('SITE_ROOT', $_SERVER['DOCUMENT_ROOT'] . SITE_BASE);
You can then use SITE_BASE for creating your URIs:
<a href="<?php echo SITE_BASE ?>subdir/">link</a>
and SITE_ROOT for accessing files on the system:
require_once SITE_ROOT . 'include/file.php';
A: Have you considered setting include_path in your php.ini file? For instance, my own php.ini file has include_path = ".:/path/to/web/root", which allows me to not worry about where my files are when including them.
In your case, you would want to set it to include_path = ".:/path/to/web/root/directory". If you don't know the path to the web root, just run echo $_SERVER['DOCUMENT_ROOT']; to find it.
This solution is "future-proof", as you only need to change that php.ini value and everything falls into place.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parsing data from text file into multiple arrays in Java Let me start by saying I am fairly new to Java so forgive me if I am making obvious mistakes...
I have a text file that I must read data from and split the data into separate arrays.
The text file contains data in this format (although if necessary it can be slightly modified to have identifier tags if it is the only way)
noOfStudents
studentNAme studentID numberOfCourses
courseName courseNumber creditHours grade
courseName courseNumber creditHours grade
courseName courseNumber creditHours grade
.
.
studentNAme studentID numberOfCourses
courseName courseNumber creditHours grade
courseName courseNumber creditHours grade
courseName courseNumber creditHours grade
.
.
The first line indicates the total number of "students" that will be listed and will need to be moved to arrays.
One array will contain student information so
studentName, studentID, numberOfCourses
to one array, and
courseName, courseNumber, creditHours, grade
to the second array.
My problem is stemming from how to parse this data.
I'm currently reading in the first line, converting to int and using that to determine the size of my student array.
After that I am at a loss for how to move the data into arrays and have my program know which array to move which lines into.
One thing to note is that the number of courses each student takes is variable so I can't simply read 1 line into one array, then 3 lines into the next, etc.
Will I need to use identifiers or am I missing something obvious? I've been looking at this problem for a week now and at this point I'm just getting frustrated.
Any help is greatly appreciated! thank you
edit: Here is the code section I am working on at the moment.
public static void main(String args[])
{
try{
// Open the file
FileInputStream fstream = new FileInputStream("a1.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine; // temporarily holds the characters from the current line being read
String firstLine; // String to hold first line which is number of students total in file.
// Read firstLine, remove the , character, and convert the string to int value.
firstLine = br.readLine();
firstLine = firstLine.replaceAll(", ", "");
int regStudnt = Integer.parseInt(firstLine);
// Just to test that number is being read correctly.
System.out.println(regStudnt + " Number of students\n");
// 2D array to hold student information
String[][] students;
// Array is initialized large enough to hold every student with 3 entries per student.
// Entries will be studentName, studentID, numberOfCourses
students = new String[3][regStudnt];
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Split each line into separate array entries via .split at indicator character.
// temporary Array for this is named strArr and is rewriten over after every line read.
String[] strArr;
strArr = strLine.split(", ");
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
I hope this helps someone lead me in the right direction.
I guess the major problem I'm having from this point is finding out how to loop in such a way that the student info is read to the student array, then the course info to the appropriate course array location, then start again with a new student until all students have been read.
A: Give this code segment a try, I think its exactly according to your requirement. If you have any confusion do let me know!
class course {
String name;
int number;
int credit;
String grade;
}
class student {
String name;
String id;
int numberCourses;
course[] courses;
}
class ParseStore {
student[] students;
void initStudent(int len) {
for (int i = 0; i < len; i++) {
students[i] = new student();
}
}
void initCourse(int index, int len) {
for (int i = 0; i < len; i++) {
students[index].courses[i] = new course();
}
}
void parseFile() throws FileNotFoundException, IOException {
FileInputStream fstream = new FileInputStream("test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int numberStudent = Integer.parseInt(br.readLine());
students = new student[numberStudent];
initStudent(numberStudent);
for (int i = 0; i < numberStudent; i++) {
String line = br.readLine();
int numberCourse = Integer.parseInt(line.split(" ")[2]);
students[i].name = line.split(" ")[0];
students[i].id = line.split(" ")[1];
students[i].numberCourses = numberCourse;
students[i].courses = new course[numberCourse];
initCourse(i, numberCourse);
for (int j = 0; j < numberCourse; j++) {
line = br.readLine();
students[i].courses[j].name = line.split(" ")[0];
students[i].courses[j].number = Integer.parseInt(line.split(" ")[1]);
students[i].courses[j].credit = Integer.parseInt(line.split(" ")[2]);
students[i].courses[j].grade = line.split(" ")[3];
}
}
}
}
You may test it by printing the contents of students array, after the execution of ParseStore
A: Having an identifier (could be an empty line) for when a new student begins would make it easy, as you could just do
if("yourIdentifier".equals(yourReadLine))
<your code for starting a new student>
A: Here is some pseudocode that should get you on track:
Student[] readFile() {
int noOfStudents = ...;
Student[] students = new Student[noOfStudents];
for (int i = 0; i < noOfStudents; ++i) {
students[i] = readStudent();
}
return students;
}
Student readStudent() {
int numberOfCourses = ...;
String name = ...;
String id = ...;
Course[] courses = new Course[numberOfCourses]
for (int i = 0; i < numberOfCourses; ++i) {
courses[i] = readCourse();
}
return new Student(id, name, courses);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Redirect on select option in select box At the moment I am using this:
<select ONCHANGE="location = this.options[this.selectedIndex].value;">
it redirect me on the location inside of the option value. But it doesn't work as expected .. mean that if I click on the first option of the select, then onChange action not running. I was thinking about javascript, but I think you'll have some better suggestions guys. So how can I make it work if I click on each option it'll redirect me to the it's value?
A: to make it as globally reuse function using jquery
HTML
<select class="select_location">
<option value="http://localhost.com/app/page1.html">Page 1</option>
<option value="http://localhost.com/app/page2.html">Page 2</option>
<option value="http://localhost.com/app/page3.html">Page 3</option>
</select>
Javascript using jquery
$('.select_location').on('change', function(){
window.location = $(this).val();
});
now you will able to reuse this function by adding .select_location class to any Select element class
A: I'd strongly suggest moving away from inline JavaScript, to something like the following:
function redirect(goto){
var conf = confirm("Are you sure you want to go elswhere?");
if (conf && goto != '') {
window.location = goto;
}
}
var selectEl = document.getElementById('redirectSelect');
selectEl.onchange = function(){
var goto = this.value;
redirect(goto);
};
JS Fiddle demo (404 linkrot victim).
JS Fiddle demo via Wayback Machine.
Forked JS Fiddle for current users.
In the mark-up in the JS Fiddle the first option has no value assigned, so clicking it shouldn't trigger the function to do anything, and since it's the default value clicking the select and then selecting that first default option won't trigger the change event anyway.
Update:
The latest example's (2017-08-09) redirect URLs required swapping out due to errors regarding mixed content between JS Fiddle and both domains, as well as both domains requiring 'sameorigin' for framed content. - Albert
A: For someone who doesn't want to use inline JS.
<select data-select-name>
<option value="">Select...</option>
<option value="http://google.com">Google</option>
<option value="http://yahoo.com">Yahoo</option>
</select>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[data-select-name]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
window.location.href = this.options[this.selectedIndex].value;
}
</script>
A: Because the first option is already selected, the change event is never fired. Add an empty value as the first one and check for empty in the location assignment.
Here's an example:
https://jsfiddle.net/bL5sq/
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="">Select...</option>
<option value="https://google.com">Google</option>
<option value="https://yahoo.com">Yahoo</option>
</select>
A: This can be archived by adding code on the onchange event of the select control.
For Example:
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value=""></option>
<option value="http://google.com">Google</option>
<option value="http://gmail.com">Gmail</option>
<option value="http://youtube.com">Youtube</option>
</select>
A: {{-- dynamic select/dropdown --}}
<select class="form-control m-bot15" name="district_id"
onchange ="location = this.options[this.selectedIndex].value;"
>
<option value="">--Select--</option>
<option value="?">All</option>
@foreach($location as $district)
<option value="?district_id={{ $district->district_id }}" >
{{ $district->district }}
</option>
@endforeach
</select>
A:
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="">Select...</option>
<option value="https://reactjs.org/">React Js</option>
<option value="https://angularjs.org/">Angular Js</option>
</select>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
}
|
Q: Compile-time constant id Given the following:
template<typename T>
class A
{
public:
static const unsigned int ID = ?;
};
I want ID to generate a unique compile time ID for every T. I've considered __COUNTER__ and the boost PP library but have been unsuccessful so far. How can I achieve this?
Edit: ID has to be usable as the case in a switch statement
Edit2: All the answers based on the address of a static method or member are incorrect. Although they do create a unique ID they are not resolved in compile time and therefore can not be used as the cases of a switch statement.
A: It is possible to generate a compile time HASH from a string using the code from this answer.
If you can modify the template to include one extra integer and use a macro to declare the variable:
template<typename T, int ID> struct A
{
static const int id = ID;
};
#define DECLARE_A(x) A<x, COMPILE_TIME_CRC32_STR(#x)>
Using this macro for the type declaration, the id member contains a hash of the type name. For example:
int main()
{
DECLARE_A(int) a;
DECLARE_A(double) b;
DECLARE_A(float) c;
switch(a.id)
{
case DECLARE_A(int)::id:
cout << "int" << endl;
break;
case DECLARE_A(double)::id:
cout << "double" << endl;
break;
case DECLARE_A(float)::id:
cout << "float" << endl;
break;
};
return 0;
}
As the type name is converted to a string, any modification to the type name text results on a different id. For example:
static_assert(DECLARE_A(size_t)::id != DECLARE_A(std::size_t)::id, "");
Another drawback is due to the possibility for a hash collision to occur.
A: This seems to work OK for me:
template<typename T>
class Counted
{
public:
static int id()
{
static int v;
return (int)&v;
}
};
#include <iostream>
int main()
{
std::cout<<"Counted<int>::id()="<<Counted<int>::id()<<std::endl;
std::cout<<"Counted<char>::id()="<<Counted<char>::id()<<std::endl;
}
A: Use the memory address of a static function.
template<typename T>
class A {
public:
static void ID() {}
};
(&(A<int>::ID)) will be different from (&(A<char>::ID)) and so on.
A: Using this constant expression counter:
template <class T>
class A
{
public:
static constexpr int ID() { return next(); }
};
class DUMMY { };
int main() {
std::cout << A<char>::ID() << std::endl;
std::cout << A<int>::ID() << std::endl;
std::cout << A<BETA>::ID() << std::endl;
std::cout << A<BETA>::ID() << std::endl;
return 0;
}
output: (GCC, C++14)
1
2
3
3
The downside is you will need to guess an upper bound on the number of derived classes for the constant expression counter to work.
A: I encountered this exact problem recently.
My solution:
counter.hpp
class counter
{
static int i;
static nexti()
{
return i++;
}
};
Counter.cpp:
int counter::i = 0;
templateclass.hpp
#include "counter.hpp"
template <class T>
tclass
{
static const int id;
};
template <class T>
int tclass<T>::id = counter::nexti();
It appers to work properly in MSVC and GCC, with the one exception that you can't use it in a switch statement.
For various reasons I actually went further, and defined a preprocessor macro that creates a new class from a given name parameter with a static ID (as above) that derives from a common base.
A: Here is a possible solution mostly based on templates:
#include<cstddef>
#include<functional>
#include<iostream>
template<typename T>
struct wrapper {
using type = T;
constexpr wrapper(std::size_t N): N{N} {}
const std::size_t N;
};
template<typename... T>
struct identifier: wrapper<T>... {
template<std::size_t... I>
constexpr identifier(std::index_sequence<I...>): wrapper<T>{I}... {}
template<typename U>
constexpr std::size_t get() const { return wrapper<U>::N; }
};
template<typename... T>
constexpr identifier<T...> ID = identifier<T...>{std::make_index_sequence<sizeof...(T)>{}};
// ---
struct A {};
struct B {};
constexpr auto id = ID<A, B>;
int main() {
switch(id.get<B>()) {
case id.get<A>():
std::cout << "A" << std::endl;
break;
case id.get<B>():
std::cout << "B" << std::endl;
break;
}
}
Note that this requires C++14.
All you have to do to associate sequential ids to a list of types is to provide that list to a template variable as in the example above:
constexpr auto id = ID<A, B>;
From that point on, you can get the given id for the given type by means of the get method:
id.get<A>()
And that's all. You can use it in a switch statement as requested and as shown in the example code.
Note that, as long as types are appended to the list of classes to which associate a numeric id, identifiers are the same after each compilation and during each execution.
If you want to remove a type from the list, you can still use fake types as placeholders, as an example:
template<typename> struct noLonger { };
constexpr auto id = ID<noLonger<A>, B>;
This will ensure that A has no longer an associated id and the one given to B won't change.
If you won't to definitely delete A, you can use something like:
constexpr auto id = ID<noLonger<void>, B>;
Or whatever.
A: Ok.....so this is a hack that I found from this website. It should work. The only thing you need to do is add another template parameter to your struct that takes a counter "meta-object". Note that A with int, bool and char all have unique IDs, but it is not guaranteed that int's will be 1 and bool will be 2, etc., because the order in which templates are initiated is not necessarily known.
Another note:
This will not work with Microsoft Visual C++
#include <iostream>
#include "meta_counter.hpp"
template<typename T, typename counter>
struct A
{
static const size_t ID = counter::next();
};
int main () {
typedef atch::meta_counter<void> counter;
typedef A<int,counter> AInt;
typedef A<char,counter> AChar;
typedef A<bool,counter> ABool;
switch (ABool::ID)
{
case AInt::ID:
std::cout << "Int\n";
break;
case ABool::ID:
std::cout << "Bool\n";
break;
case AChar::ID:
std::cout << "Char\n";
break;
}
std::cout << AInt::ID << std::endl;
std::cout << AChar::ID << std::endl;
std::cout << ABool::ID << std::endl;
std::cout << AInt::ID << std::endl;
while (1) {}
}
Here is meta_counter.hpp:
// author: Filip Roséen <filip.roseen@gmail.com>
// source: http://b.atch.se/posts/constexpr-meta-container
#ifndef ATCH_META_COUNTER_HPP
#define ATCH_META_COUNTER_HPP
#include <cstddef>
namespace atch { namespace {
template<class Tag>
struct meta_counter {
using size_type = std::size_t;
template<size_type N>
struct ident {
friend constexpr size_type adl_lookup (ident<N>);
static constexpr size_type value = N;
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template<class Ident>
struct writer {
friend constexpr size_type adl_lookup (Ident) {
return Ident::value;
}
static constexpr size_type value = Ident::value;
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template<size_type N, int = adl_lookup (ident<N> {})>
static constexpr size_type value_reader (int, ident<N>) {
return N;
}
template<size_type N>
static constexpr size_type value_reader (float, ident<N>, size_type R = value_reader (0, ident<N-1> ())) {
return R;
}
static constexpr size_type value_reader (float, ident<0>) {
return 0;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template<size_type Max = 64>
static constexpr size_type value (size_type R = value_reader (0, ident<Max> {})) {
return R;
}
template<size_type N = 1, class H = meta_counter>
static constexpr size_type next (size_type R = writer<ident<N + H::value ()>>::value) {
return R;
}
};
}}
#endif /* include guard */
A: using template and if constexpr, need c++17
#include <iostream>
template <typename Type, typename... Types>
struct TypeRegister{
template<typename Queried_type>
static constexpr int id(){
if constexpr (std::is_same_v<Type, Queried_type>) return 0;
else{
static_assert((sizeof...(Types) > 0), "You shan't query a type you didn't register first");
return 1 + TypeRegister<Types...>::template id<Queried_type>();
}
}
};
int main(){
using reg_map = TypeRegister<int, float, char, const int&>;
std::cout << reg_map::id<const int&>() << std::endl;// 3
// std::cout << reg_map::id<const int>() << std::endl;// error
}
A: This is sufficient assuming a standards conforming compiler (with respect to the one definition rule):
template<typename T>
class A
{
public:
static char ID_storage;
static const void * const ID;
};
template<typename T> char A<T>::ID_storage;
template<typename T> const void * const A<T>::ID= &A<T>::ID_storage;
From the C++ standard 3.2.5 One definition rule [basic.def.odr] (bold emphasis mine):
... If D is a template and is defined in more than one translation
unit, then the last four requirements from the list above shall apply
to names from the template’s enclosing scope used in the template
definition (14.6.3), and also to dependent names at the point of
instantiation (14.6.2). If the definitions of D satisfy all these
requirements, then the program shall behave as if there were a single
definition of D. If the definitions of D do not satisfy these
requirements, then the behavior is undefined.
A: What I usually use is this:
template<typename>
void type_id(){}
using type_id_t = void(*)();
Since every instantiation of the function has it's own address, you can use that address to identify types:
// Work at compile time
constexpr type_id_t int_id = type_id<int>;
// Work at runtime too
std::map<type_id_t, std::any> types;
types[type_id<int>] = 4;
types[type_id<std::string>] = "values"s
// Find values
auto it = types.find(type_id<int>);
if (it != types.end()) {
// Found it!
}
A: This can't be done. An address to a static object is the closest you can get to a unique id, however in order to take addresses of such objects (even static const integrals) they must be defined somewhere. Per the one definition rule, they should be defined within a CPP file, which cannot be done since they are templates. If you define the statics within a header file, then each compilation unit will get its own version of it implemented of course at different addresses.
A: I had a similar problem a few months ago. I was looking for a technique to define identifiers that are the same over each execution.
If this is a requirement, here is another question that explores more or less the same issue (of course, it comes along with its nice answer).
Anyway I didn't use the proposed solution. It follows a description of what I did that time.
You can define a constexpr function like the following one:
static constexpr uint32_t offset = 2166136261u;
static constexpr uint32_t prime = 16777619u;
constexpr uint32_t fnv(uint32_t partial, const char *str) {
return str[0] == 0 ? partial : fnv((partial^str[0])*prime, str+1);
}
inline uint32_t fnv(const char *str) {
return fnv(offset, str);
}
Then a class like this from which to inherit:
template<typename T>
struct B {
static const uint32_t id() {
static uint32_t val = fnv(T::identifier);
return val;
}
};
CRTP idiom does the rest.
As an example, you can define a derived class as it follows:
struct C: B<C> {
static const char * identifier;
};
const char * C::identifier = "ID(C)";
As long as you provide different identifiers for different classes, you will have unique numeric values that can be used to distinguish between the types.
Identifiers are not required to be part of the derived classes. As an example, you can provide them by means of a trait:
template<typename> struct trait;
template<> struct trait { static const char * identifier; };
// so on with all the identifiers
template<typename T>
struct B {
static const uint32_t id() {
static uint32_t val = fnv(trait<T>::identifier);
return val;
}
};
Advantages:
*
*Easy to implement.
*No dependencies.
*Numeric values are the same during each execution.
*Classes can share the same numeric identifier if needed.
Disadvantages:
*
*Error-prone: copy-and-paste can quickly become your worst enemy.
It follows a minimal, working example of what has been described above.
I adapted the code so as to be able to use the ID member method in a switch statement:
#include<type_traits>
#include<cstdint>
#include<cstddef>
static constexpr uint32_t offset = 2166136261u;
static constexpr uint32_t prime = 16777619u;
template<std::size_t I, std::size_t N>
constexpr
std::enable_if_t<(I == N), uint32_t>
fnv(uint32_t partial, const char (&)[N]) {
return partial;
}
template<std::size_t I, std::size_t N>
constexpr
std::enable_if_t<(I < N), uint32_t>
fnv(uint32_t partial, const char (&str)[N]) {
return fnv<I+1>((partial^str[I])*prime, str);
}
template<std::size_t N>
constexpr inline uint32_t fnv(const char (&str)[N]) {
return fnv<0>(offset, str);
}
template<typename T>
struct A {
static constexpr uint32_t ID() {
return fnv(T::identifier);
}
};
struct C: A<C> {
static constexpr char identifier[] = "foo";
};
struct D: A<D> {
static constexpr char identifier[] = "bar";
};
int main() {
constexpr auto val = C::ID();
switch(val) {
case C::ID():
break;
case D::ID():
break;
default:
break;
}
}
Please, note that if you want to use ID in a non-constant expression, you must define somewhere the identifiers as it follows:
constexpr char C::identifier[];
constexpr char D::identifier[];
Once you did it, you can do something like this:
int main() {
constexpr auto val = C::ID();
// Now, it is well-formed
auto ident = C::ID();
// ...
}
A: Here is a C++ code that uses __DATE__ and __TIME__ macro to get unique identifiers for types <T>
Format:
// __DATE__ "??? ?? ????"
// __TIME__ "??:??:??"
This is a poor quality hash function:
#define HASH_A 8416451
#define HASH_B 11368711
#define HASH_SEED 9796691 \
+ __DATE__[0x0] * 389 \
+ __DATE__[0x1] * 82421 \
+ __DATE__[0x2] * 1003141 \
+ __DATE__[0x4] * 1463339 \
+ __DATE__[0x5] * 2883371 \
+ __DATE__[0x7] * 4708387 \
+ __DATE__[0x8] * 4709213 \
+ __DATE__[0x9] * 6500209 \
+ __DATE__[0xA] * 6500231 \
+ __TIME__[0x0] * 7071997 \
+ __TIME__[0x1] * 10221293 \
+ __TIME__[0x3] * 10716197 \
+ __TIME__[0x4] * 10913537 \
+ __TIME__[0x6] * 14346811 \
+ __TIME__[0x7] * 15485863
unsigned HASH_STATE = HASH_SEED;
unsigned HASH() {
return HASH_STATE = HASH_STATE * HASH_A % HASH_B;
}
Using the hash function:
template <typename T>
class A
{
public:
static const unsigned int ID;
};
template <>
const unsigned int A<float>::ID = HASH();
template <>
const unsigned int A<double>::ID = HASH();
template <>
const unsigned int A<int>::ID = HASH();
template <>
const unsigned int A<short>::ID = HASH();
#include <iostream>
int main() {
std::cout << A<float>::ID << std::endl;
std::cout << A<double>::ID << std::endl;
std::cout << A<int>::ID << std::endl;
std::cout << A<short>::ID << std::endl;
}
A: If non-monotonous values and an intptr_t are acceptable:
template<typename T>
struct TypeID
{
private:
static char id_ref;
public:
static const intptr_t ID;
};
template<typename T>
char TypeID<T>::id_ref;
template<typename T>
const intptr_t TypeID<T>::ID = (intptr_t)&TypeID<T>::id_ref;
If you must have ints, or must have monotonically incrementing values, I think using static constructors is the only way to go:
// put this in a namespace
extern int counter;
template<typename T>
class Counter {
private:
Counter() {
ID_val = counter++;
}
static Counter init;
static int ID_val;
public:
static const int &ID;
};
template<typename T>
Counter<T> Counter<T>::init;
template<typename T>
int Counter<T>::ID_val;
template<typename T>
const int &Counter<T>::ID = Counter<T>::ID_val;
// in a non-header file somewhere
int counter;
Note that neither of these techniques is safe if you are sharing them between shared libraries and your application!
A: Another alternative is to consider the following class Data with the unique, static member field type:
template <class T>
class Data
{
public:
static const std::type_index type;
};
// do [static data member initialization](http://stackoverflow.com/q/11300652/3041008)
// by [generating unique type id](http://stackoverflow.com/q/26794944/3041008)
template <class T>
std::type_index const Data<T>::type = std::type_index(typeid(T));
produces the output (MinGWx64-gcc4.8.4 -std=c++11 -O2)
printf("%s %s\n", Data<int>::type.name(), Data<float>::type.name())
//prints "i f"
It's not exactly an integer id or pretty-printable string, nor a constexpr, but can be used as an index in (un)ordered associative containers.
It also appears to work if the Data.h header is included in multiple files (same hashCode() values).
A: Here is a pragmatic solution, if you are ok with writing a single additional line DECLARE_ID(type) for each type you want to use:
#include <iostream>
template<class> struct my_id_helper;
#define DECLARE_ID(C) template<> struct my_id_helper<C> { enum {value = __COUNTER__ }; }
// actually declare ids:
DECLARE_ID(int);
DECLARE_ID(double);
// this would result in a compile error: redefinition of struct my_id_helper<int>’
// DECLARE_ID(int);
template<class T>
class A
{
public:
static const unsigned int ID = my_id_helper<T>::value;
};
int main()
{
switch(A<int>::ID)
{
case A<int>::ID: std::cout << "it's an int!\n"; break;
case A<double>::ID: std::cout << "it's a double!\n"; break;
// case A<float>::ID: // error: incomplete type ‘my_id_helper<float>’
default: std::cout << "it's something else\n"; break;
}
}
A: template<typename T>
static void get_type_id() { void* x; new (x) T(); }
using type_id_t = void(*)();
works fine with optimizations
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
}
|
Q: IPhone: File Upload using dispatch_async for background upload I want to perform a image upload while the running application at the background. I am able to upload the image to the server using the code on this link.
How can I upload a photo to a server with the iPhone?
I heard the NSUrlConnection can be asynchronous and it was used in the EPUploader. In my code, I add some extra method that will create a file in the application directory used for the EPUploader. During this creation of the file, I don't want it to create on the main thread of the application so I wrap all the code including the EPUploader itself with the
dispatch_async on the global queue. That way I won't block the main thread while the file are creating.
It has no problem if I use dispatch_sync but dispatch_async I find something weird when I placed the breakpoint at NSUrlConnection connection :
- (void)upload
{
NSData *data = [NSData dataWithContentsOfFile:filePath];
//ASSERT(data);
if (!data) {
[self uploadSucceeded:NO];
return;
}
if ([data length] == 0) {
// There's no data, treat this the same as no file.
[self uploadSucceeded:YES];
return;
} /* blah blah */
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (!connection) {
[self uploadSucceeded:NO];
return;
}
else
return;
I went to debug at the breakpoint and instead of going to if statement, the debugger jumps to the first return statement of this method. After that, the selectors I passed on to this class never gets called. This happen only on dispatch_async and it work on dispatch_sync on the global queue.
Does anybody know how to solve this issue?
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(queue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
self.uploadIndex = 0;
ALAsset *asset = [self.assets objectAtIndex:0];
[[FileUploader alloc] initWithAsset:[NSURL URLWithString:@"http://192.168.0.3:4159/default.aspx"]
asset:asset
delegate:self
doneSelector:@selector(onUploadDone:)
errorSelector:@selector(onUploadError:)];
//[self singleUpload:self.uploadIndex];
[pool release];
});
A: There are a couple of things that should be changed.
*
*Remove the NSAutoreleasePool, it is not needed.
*Copy the block to the heap because it's life will probably exceed that of the calling code.
Example:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(queue, [[^{
self.uploadIndex = 0;
ALAsset *asset = [self.assets objectAtIndex:0];
[[FileUploader alloc] initWithAsset:[NSURL URLWithString:@"http://192.168.0.3:4159/default.aspx"]
asset:asset
delegate:self
doneSelector:@selector(onUploadDone:)
errorSelector:@selector(onUploadError:)];
} copy] autorelease]);
If you are using ARC (which you certainly are since you should be) there is no need for the copy or autorelease.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Scaling limited API requests over time for large bundles of requests I'm implementing Klout API with a web application I have been working.
Klout allows you to do 10 requests / second, and 10,000 / day.
Each user account can view N other user accounts with their Klout scores.
Would the best way to gather this information be to periodically request scores from Klout API as a background process and store these results in the database?
If I do this, let's say we have 10 users who have 30 other user's Klout scores they want to view.
In a daily background process, let's also say we go through each of the 10 users and look up each of their 30 followed user Klout scores.
This would ping Klout's API at a maximum of 300 times throughout this process (however you can include up to 5 users to look up their scores per request -- so the number of requests could be reduced to 60).
In order to avoid the 10 requests per second cap, should I sleep the process for about 10 seconds between each request? Would that be the best way to avoid any API errors?
Psuedo Example:
$maxUserPerRequest = 5;
foreach ($users as $user){
$follows = getKloutFollows($user); // list of klout scores to look up per user
$minimize = 0; // allow to minimize total requests by 5 users per req.
$batch = array() // array of 5 users to request
foreach($follows as $follow){
$batch[] = $follow;
// query 5 users at a time
if ($maxUserPerRequest % $minimize==0){
$kloutAPI->getScore($batch); // storing results
$batch = array();
sleep(10); // avoid overloading API requests
}
$minimize++;
}
}
A: That should be enough to avoid getting the errors, but doing mass database appends and storing the data for more than 5 days would still violate the Terms of Service.
I would just keep a counter of each request. Make 10 requests. Sleep for 1000. Reset the counter. Make 10 requests. Sleep for 1000.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the purpose of a ModelLocator Singleton in ActionScript The use I have for it is for storing user credentials, and calling a transfer object that functions as a sort of "cache" for the current session in all of the flex modules.
Thinking about objects that have to be present in every module. Is there any alternative to a singleton instance for this?
A: Yes! Automated dependency injection frameworks, such as Mate, Robotlegs, Parsley, or Swiz. Check out http://www.developria.com/2010/06/robotlegs-for-framework-beginn.html and http://www.developria.com/2010/05/mate-for-framework-beginners.html for a more in-depth look about how two of these work.
For just a few reasons you should avoid Singletons, see http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using chardet to detect bad encoding in a MySQL db with JDBC Recently we moved our mysql db from Latin1 to UTF8. After trying a few different approaches to convert it we weren't able to find any that didn't also introduce some pretty nasty dataloss (and many simply did nothing).
This left me wondering if we have lots of different encodings going on since there doesn't seem to be a single approach that covers our test cases (various posts in our database). To test this theory I wrote a small scala app (my first, feel free to make fun of just how cobbled and non-idiomatic it is! :D) that used chardet to look at the posts and tell me the encoding.
Only one problem, everything is always UTF8.
Here's the code:
package main.scala
import org.mozilla.universalchardet.UniversalDetector
import java.sql.DriverManager
object DBConvert {
def main(args: Array[String]) {
val detector = new UniversalDetector(null)
val db_conn_str = "jdbc:mysql://localhost:3306/mt_pre?user=root"
val connection = DriverManager.getConnection(db_conn_str)
try {
val statement = connection.createStatement()
val rs = statement.executeQuery("SELECT * FROM mt_entry where entry_id = 3886")
while (rs.next) {
val buffer = rs.getBytes("entry_text_more")
detector.handleData(buffer, 0, buffer.length)
detector.dataEnd()
val encoding:String = detector.getDetectedCharset;
if (encoding != null) println("Detected encoding = " + encoding) else println("No encoding detected.");
detector.reset();
// Just so we can see the output
println(rs.getString("entry_text_more"))
}
} catch {
case _ => e: Exception => println(e.getMessage)
}
finally {
connection.close()
}
}
}
I tried passing useUnicode the JDBC query string, also characterEncoding. Neither of them budged the UTF-8 always coming out. Also tried using getBinaryStream and others, still UTF-8.
Fully admit that Character encoding makes my head bend a bit and playing with a new language may not be the best way of fixing this problem. :) That said I'm curious - is there a way to grab the data from the db and detect what encoding it was put in there as, or is it one of those things that simply since it's encoded as UTF-8 in the DB, no matter how you retrieve it that's just what it is (funny characters and all)?
Thanks!
A: Once I had a similar problem. See this answer. Setting the encoding inside the connection string may help.
A: Note that the Table Charset and the Connection CHarset and the Default Database Encoding are all same UTF-8. I had one instance in which Datbases default was UTF-8 , but the table coloumns was still Latin so i had some problem. Please see if thats the case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Android Google Maps API Key I'm developing an app that uses Google Maps. I got the debug keystore and got the API key to work while I am debugging my program in Eclipse, but I am thoroughly confused in how to change this so that it works on an Android device when I export the .apk. I have searched around Google, but am mainly finding things that use the debug.keystore and I don't think this is what I want to use when I deploy this on an Android device, because I sent my .apk to a friend and he said he is getting gray boxes on the Map View.
Can anyone fill me in, step-by-step, on how to correctly make a new keystore for my app and how to sign my app so that it will work outside of debugging on Eclipse? A video tutorial would be preferable, but if not, simple 1-2-3 step type instructions would work. Thanks!
A: Eclipse (through ADT) has a nice wizard that lets you create a real keystore and build a signed apk. Right click your project, then Android Tools -> Export signed Application package
For the google maps key just follow these instructions
A: head to the command prompt, (I use windows so I'm going to go that route but same general idea for the other OS's)
The keytool program you'll need is part of the JDK so you do have it if your able to compile the apps at all. but it may not be on the app path so you can't just type it into the command line to be used.
for me it was in:C:\Program Files\Java\jdk1.7.0_21\bin so to get it on the app path I typed this in set PATH=%PATH%;C:\Program Files\Java\jdk1.7.0_21\bin
next you need to change to the directory your keystore files are in for me that is: C:\android\keys so I used the command cd C:\android\keys to change to the proper directory
then you need to run the keytool with the proper settings so it knows your after the key and not trying to do something else. the command I used was: keytool -list -v -keystore Testkeys and Testkeys is the name of my keystore use the name of your keystore there instead.
Last by not least it will spit out a whole bunch of different information but the one your looking for will look something like this
SHA1: A1:DF:83:DD:04:B2:26:10:B2:EB:26:00:90:75:D0:10:66:5E:A9:8A
you want all the numbers and : that are after the "SHA1: " that is your app key for the published version of your app, the one you need to register with the google maps api service, and then they will give you a new map api key that you need to put in your project and then republish it, and then the maps will work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iPhone app, alert users when they aren't connected to the internet? What's an easy way to code an alert that warns users when they aren't connected to the Internet? I'm using Xcode, right now when there is no connection it is just a white screen in uiwebview.
A: Here you can check if wifi has connection, 3g,or none atall:
if ([[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWiFi) {
// Do something that requires wifi
} else if ([[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWWAN) {
// Do something that doesnt require wifi
} else if ([[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == NotReachable) {
// Show alert because no wifi or 3g is available..
}
Apple provides all the necessary Reachability api/source here: Reachability Reference
I have made these custom convenience functions for myself in all my projects:
+ (BOOL)getConnectivity {
return [[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] != NotReachable;
}
+ (BOOL)getConnectivityViaWiFiNetwork {
return [[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWiFi;
}
+ (BOOL)getConnectivityViaCarrierDataNetwork {
return [[Reachability reachabilityWithHostName:@"google.com"] currentReachabilityStatus] == ReachableViaWWAN;
}
And used like so:
if ([ServerSupport getConnectivity]) {
// do something that requires internet...
else {
// display an alert
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Network Unavailable"
message:@"App content may be limited without a network connection!"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil] autorelease];
[alert show];
}
A: If your application requires persistent internet connection, you can include the key UIRequiresPersistentWiFi in your plist file. Using this, iOS will automatically display an alert to the user in the airport mode.
Also, iOS will ensure that the wifi radio isn't switched off/hibernated while your app is in the foreground.
A: Note that internet connectivity is very dynamic on a mobile device (multiple radios, multiple access points, multiple cell towers, travel, competing radio interference, "your holding it wrong", etc.), and thus Reachability is not a perfect solution, as the net connectivity can very often can change just before, during or after Reachability performs its checks. Reachability can outright lie (yes we're connected to an access point, true even if broadband is dead on the other side of the access point). It's also quite common for Reachability to report no connectivity, just as its own request turns the radios on to get a great connection a couple seconds later.
Best thing to do is to just try to access data from the network, spin an activity indicator while waiting, and offer the user some API element to give up if they end up waiting too long, in their opinion, not some developer's opinion... They know better than you do how long it takes for a (re)connection to come up in their area, and how long they are willing to wait.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery popup with faded background conflicts with transparent PNGs I'm building a popup shopping cart in a webshop, which acts like a kind of lightbox. The cart pops up when it should, and the background fades to gray when it should.
Problem: some elements in the page light up when fading, this is very ugly.
I'm using jQuery.fadeIn and jQuery.fadeOut.
My problem is demonstrated here.
Click on the phrase "Shopping Bag" in the top right corner to see what happens.
A: Looks like you have to fade the background separately, not rely on it inheriting the opacity from the containing element. Do you understand what I mean? You would have to perform two fadeIn/fadeOut in parallel.
A: Here you go my friend
.popup-cart-container {
display: none;
left: 0;
position: absolute;
top: 0;
z-index: 1000;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Check if remote file has changed I'm using PHP cURL module to extract timestamp of a remote file via HTTP headers. I've managed to grab modification timestamp by using CURLOPT_FILETIME constant. Of course, I'm doing this in order too see if the remote file has changed without downloading it's contents.
$ch = curl_init($url); /* create URL handler */
curl_setopt($ch, CURLOPT_NOBODY, TRUE); /* don't retrieve body contents */
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); /* follow redirects */
curl_setopt($ch, CURLOPT_HEADER, FALSE); /* retrieve last modification time */
curl_setopt($ch, CURLOPT_FILETIME, TRUE); /* get timestamp */
$res = curl_exec($ch);
$timestamp = curl_getinfo($ch, CURLINFO_FILETIME);
curl_close($ch);
What is, in your opinion the best way to check if remote file has changed? Should I go with timestamp check only? Or are there some other clever options that didn't came to my mind?!
A: Your approach looks good for finding the Last-Modified time value. (Need to watch out for -1 return for CURLINFO_FILETIME, meaning that no Last-Modified header value was identified.)
You could save the time returned, and in future checks see if it has changed. If it's changed, fetch the new file via Curl.
Another option would be to save ETag and Last-Modified headers, then use a conditional request to get the image again. This would be more complex, but you'd save the additional HEAD request each time. You can see some of the details in this SO question: if-modified-since vs if-none-match.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: syntax error, unexpected '}' I am at a loss and I've spent a few weeks reading site after site to try and understand what I can do. The problem is that I am learning as I have been doing since I have a website - mostly the hard way. ;)
I would be very grateful if you can help me.
This error is related to wp-content/plugins/color-widgets/colorwidgets.php
Above the line (53 in this case) is:
}
<?php }
} ?>
<div style="background-color:<?php echo $textbgcolor; ?>; color:<?php echo $textfontcolor; ?>; text-align:<?php echo $texthalign; ?>; padding:<?php echo $textpadding; ?>"><?php echo $text; ?></div>
<?php if ($themestyle == 'Yes') { echo $after_widget; } ?>
</div>
<?php
**The } is in the line under <?php.
Underneath } is:**
/** @see WP_Widget::update */
function update($new_instance, $old_instance) {
return $new_instance;
}
**I deleted the } but syntax error, unexpected '}' still exists when I try to access my site, so I put it back.
..............
I then added admin to the end of URL and got a different message.
Fatal error: Class 'ColorWidgets' not found in /wp-includes/widgets.php on line 324
The line is (below):**
$this->widgets[$widget_class] = & new $widget_class();
Above this is:
/**
* Singleton that registers and instantiates WP_Widget classes.
*
* @package WordPress
* @subpackage Widgets
* @since 2.8
*/
class WP_Widget_Factory {
var $widgets = array();
function WP_Widget_Factory() {
add_action( 'widgets_init', array( &$this, '_register_widgets' ), 100 );
}
function register($widget_class) >{
$this->widgets[$widget_class] = & new widget_class();
The last line is the error line, and below is:
}
function unregister($widget_class) >{
if ( isset($this->widgets[$widget_class]) )
>unset($this->widgets[$widget_class]);
}
.............
I apologise for the amount of time needed to follow my post and I'd greatly appreciate feedback. Thank-you for listening. :)
A: This error indicated that you have more closing brances. To fix it, you have to scroll through your code the check where the problem is.
Next time, when developing, try to always add opening and closing braces before actually filling it with code and try to indent and format your code like this, so that you will minimize the same error and potentially another error / bug:
if()
{
if()
{
if()
{
}
}
}
instead of
if(){
if(){
if()
{
}
}
}
or
<?php
if()
{
?>
<!-- your code-->
<?php
}
?>
instead of
<?php
if(){
?>
<!-- your code--><?php}
?>
It would also be better if you have editor that support formatting source-code. I use Netbeans for this.
A: In essence the error is saying you have more closing braces than opening ones. Double check you braces and you'll probably find they don't match.
UPDATE:
Fix one error at a time. If you were still getting "Unexpected }" don't add something else until you've fixed that error.
A: First of all, try to make sure you have paired ALL the braces in the code.
Second, if this isn't working, check to see if you have missed some trailing semicolons in the code. This can be easily done if you have a regex-enabled search function in your IDE and a well-implemented writing style.
I would check for the second one first, but this is my case only.
Wishing you best of luck,
Victor
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there a good example of an MVC framework in practice? I have read hundreds of articles on models, and how they are used in the MVC framework. However, I've had a hard time finding a good example of one being used in the wild.
I feel like seeing something that goes beyond the limits of a tutorial would help me understand the end goal.
Do you know of any open source - and fully functioning - frameworks that I could check out as examples?
NOTE - I'm not looking for simply CodeIgniter - unless it's a site or app that was based on CodeIgniter and therefore has stuff that I didn't download with the CI framework itself.
A: Magento is an open source ecommerce system build upon the Zend Framework.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Making ruby faster for memory intensive programs I'm running a pretty memory intensive program in ruby which is fast initially and then slows down as the memory utilization increases.
The program has two phases: (1) build a large hash: string => list in memory, (2) do some computation on the hash. The slowdown occurs in phase 1.
Why does this happen? Is it that there are more calls to the garbage collector? Or is ruby swapping memory out to disk?
In either case, is there any configuration I can do to speed things up? For instance, can I increase the heap-size or the maximum amount of memory that ruby is allowed to consume? I didn't see anything in the man-page.
A: I find ruby to be really slow too with large datasets, the way I deal with it is to run ruby 1.9.2 or higher, or even jruby if possible. If that is not enough, when traversing extremely large datasets I usually revert to the mapreduce paradigm, that way I only need to keep one row in memory at a time. For something akin to your problem in with building the hash, I'd just have a ruby program emit to $stdout for chaining or divert the output to a file:
$ ruby build_csv.rb > items.csv
$ cat items.csv
foo,23
foo,17
bar,42
then have a second program that can read the datastructure into a hash
@hsh = Hash.new { |hash, key| hash[key] = [] }
File.open("items.csv").each_line do |l|
k,v = l.split(',')
@hsh[k] << v
end
The previous program could of course be faster if it used the CSV library. Anyway, it'll read in the hsh to something like this.
@hsh => {"foo"=>[23, 17], "bar"=>[42]}
Splitting a problem into many small programs really makes a difference for speed, because less is kept in memory, if the operation on the hash only needs to work on a single key, then it's easy to write that part as something that just reads until a new key is found, produces output on the last key and then proceeds with the new key, in much the same fashion as the first round. Keeping memory use down like this by splitting and producing intermediate results on file really speeds up the process a lot. If you can divide your data, you can also run the several stage one / mapping jobs at once either in the shell or by using threads.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Singleton design pattern in a Cluster environment Singleton object will create instances per jvm basis. How it works in clustering environment?
What are the alternatives?
A: Technically, you can use Terracotta to cluster the JVM. I think it will guarantee the singleton instance.
But I think it's not what you want. Singletons are just "global state". So you don't need the same instance as long as the state (field values) in it is the same. I don't know how you cluster your application, but I guess you can have cluster-wide data.
A: One alternative is to not create a Singleton:
http://code.google.com/p/google-singleton-detector/
Google thinks they're a bad idea.
Clustered caching sounds like what you want. Maybe a Terracotta or a Coherence is a better idea.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Error when trying to cast from System.Double to System.Single I am sure this will turn out to be something simple. I have the following Silverlight 4 C# code:
Rectangle r = new Rectangle();
r.Stroke = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
r.SetValue(Canvas.LeftProperty, 150f);
r.SetValue(Canvas.TopProperty, 50f);
r.Width = 100;
r.Height = 100;
LayoutRoot.Children.Add(r);
For some reason, when I run my application, it is getting an error on the SetValue lines. The error I am getting is:
Uncaught Error: Unhandled Error in Silverlight Application DependencyProperty of type System.Double cannot be set on an object of type System.Single.
I tried to cast implicitly to Single, but still got the same error. Any ideas?
A: You're passing in a boxed float, and the rectangle is then trying to unbox it to a double. Just pass in doubles to start with, and it should be fine:
r.SetValue(Canvas.LeftProperty, 150d);
r.SetValue(Canvas.TopProperty, 50d);
Note that Canvas.Left and Canvas.Top are of type double, not float.
A: These properties have type double. You are passing single precision values, floats. Pass doubles and all will be well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Winforms: How to Bind a List to multiple DataGridView I want to be able to bind a List to multiple DataGridViews such that manipulation through one of the gridviews would be propogated to all other gridviews.
List<Domain> data;
1st approach:
BindingList<Domain> list = new ..;
data.ForEach( d => { list .Add(d); } );
grid1.DataSource = list;
grid2.DataSource = list;
This didn't work. The grids share properties other than the data.
2nd approach:
BindingList<Domain> list1 = new ..;
BindingList<Domain> list2 = new ..;
data.ForEach( d => { list1.Add(d); list2.Add(d); } );
grid1.DataSource = list1;
grid2.DataSource = list2;
This approach works for updates. However, adds and deletes weren't propograted.
3rd approach:
BindingList<Domain> list = new ..;
data.ForEach( d => { list .Add(d); } );
BindingSource ds1 = new BindingSource();
BindingSource ds2 = new BindingSource();
ds1.DataSource = list;
ds2.DataSource = list;
grid1.DataSource = ds1;
grid2.DataSource = ds2;
This propogates adds and deletes, however, when a new row is added to 1 view, but not yet commited, an empty row is displayed in all other grids. Seems like a new record is inserted into the List before the editing completes.
How can I properly bind multiple datagridviews to one List? (This is extremely easy in Flex.) I'd appreciate any reference to the relevant section in MDSN.
A: I made a little test app, just to make sure that sharing a binding source was possible the way I remembered. You can find it here (for at least 30 days).
What I found that propbably caused your problem is that all your grids probably have adding/deleting rows enabled. A new row in grid1 is displayed as a new row in grid2, but grid2 (quite unnecessarily) displays a template row below that.
I made a little main window with a read-only grid on a binding source and an edit dialog with an editable grid on the same binding source. The binding source is the only wiring between the two, no event handling to signal updates, no reassigning of datasources. Everything is synced perfectly, even the current row (because of the CurrencyManager). A new row in the dialog only shows as one empty row in the 'main' window.
Hope this helps, and is not over-simplified.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: drawImage() not drawing pre-loaded image object. Using OO javascript I'm writing a simple 2D side scroller game using JavaScript + Canvas. I am trying to do this while learning OO JavaScript. I'm encountering an issue where my image will not draw to the canvas, despite being loaded correctly. Here's the code:
//===================================
// class - Canvas
//===================================
var classCanvas = function(id){
canvas = document.getElementById(id);
context = canvas.getContext("2d");
}
//===================================
// abstract class - Image Drawer
//===================================
var classImageDrawer = function(that){
this.draw = function(){
context.drawImage(that.img,
that.spriteCoordsX,
that.spriteCoordsY,
that.width,
that.height,
that.posX,
that.posY,
that.width,
that.height);
}
}
//===================================
// class - Level
//===================================
var classLevel = function(name, src){
this.name = name;
this.img = new Image();
this.img.src = src;
this.img.onload = function(){ };
this.spriteCoordsX = 0;
this.spriteCoordsY = 0;
this.posY = 0;
this.posX = 0;
this.height = 400;
this.width = 600;
this.drawer = new classImageDrawer(this);
}
//==================================
// Begin
//==================================
var game = new classCanvas("playground");
game.LevelOne = new classLevel("LevelOne", "images/foreground-land.png");
game.LevelOne.drawer.draw();
I have checked the code, and I know the image is getting loaded correctly. No errors occur during runtime, the image "foreground-land.png" simply DOESN'T show up on the canvas!
A: Your image may be loading fine, but as far as I can tell your call to game.LevelOne.drawer.draw() has no guarantee that foreground-land.png has loaded at that point (remember, images are loaded asynchronously without blocking the execution of other code).
Your onload function for the image object in your classLevel class is empty and anonymous. Nothing happens when the image is finished loading. I'm not sure how you want to structure your code given everything else you have going on, but you should only allow the call to game.LevelOne.drawer.draw() to succeed if the resources it depends upon have been fully loaded. The best way to do this would be to hook into the onload callback for all resources you require for that object (in this case, it's just the one image).
A: Loading images is an async operation, you are (basically) ignoring the loading process, and acting as though it is sync operations.
One thing you could look at is using a 3rd parameter as a callback ("LevelOne", "images/foreground-land.png", function() { this.drawer.draw() }) and doing that as the onload
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Override CSS and HTML Styles in Outlook 2007, Word 2007 In Internet Explorer 8, it is possible to override CSS styles and HTML tags using:
Tools -> Internet Options -> Accessibility (button) -> Format documents using my style sheet (check box).
There I can specify a file containing my own CSS snippet. Specifying the "!important" modifier causes the CSS code to override existing formatting.
Is there a way to do this or something similar in Outlook 2007? I understand that Outlook 2007 uses the Word 2007 HTML and CSS engine. Therefore, a solution for Word might be applicable to Outlook 2007.
I am attempting to print emails that contain HTML tables. The tables often contain a width setting that is wider than the 8.5-inch page I need to print to. Additionally, the <td nowrap tag is often included. The result is that text is cut off at the right margin.
If I can override the width and nowrap tags, I should be able to prevent truncation. How can I do this?
The ideal solution would be accomplished solely in Word / Outlook and CSS. VBA is an option, but only if it can be applied automatically. Manually running a macro is not an option.
A: This is not possible because the Microsoft Developer Network (MSDN) states that
*
*media ( screen | print | projection | braille | speech | all )
is not supported in Word 2007 and therefore Outlook 2007.
http://msdn.microsoft.com/en-us/library/aa338201.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Delete an user in Active Directory via C# I'm trying to delete an user in Active Directory via C#.When I attempt to run the following the code,I got an error.
Error Message:
A local error has occurred
Code:
DirectoryEntry ent = new DirectoryEntry("LDAP://192.168.1.99/OU=FIRMA");
ent.Username = "idm\administrator";
ent.Password = "123123QQ";
DirectorySearcher dsrc = new DirectorySearcher(ent);
dsrc.Filter = string.Format("(&(objectCategory=user)(SAMAccountName=adKullaniciadi))");
DirectoryEntry silsunuya = ent.Children.Find("CN=adKullaniciadi","objectClass=person");
ent.Children.Remove(silsunuya);
ent.Close();
silsunuya.Close();
dsrc.Dispose();
A: I have an ASP.Net website running local that our IT team uses to delete AD accounts, and it seems to work ok. I remember when I was developing this application there were a lot of nuances I had to deal with, which can make it painful to figure out what's going on with AD. Here is the code I am using (in VB.Net):
Public Shared Function GetUser(ByVal username As String) As DirectoryEntry
If String.IsNullOrEmpty(username) Then Return Nothing
Dim path As String = ConfigurationManager.ConnectionStrings("ADConnectionString").ConnectionString
Dim ds As New DirectorySearcher(path)
ds.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))"
ds.PropertiesToLoad.Add("sAMAccountName") ' username
ds.PropertiesToLoad.Add("mail") ' e-mail address
ds.PropertiesToLoad.Add("description") ' Bureau ID
ds.PropertiesToLoad.Add("company") ' company name
ds.PropertiesToLoad.Add("givenname") ' first name
ds.PropertiesToLoad.Add("sn") ' last name
ds.PropertiesToLoad.Add("name") ' client name
ds.PropertiesToLoad.Add("cn") ' common name
ds.PropertiesToLoad.Add("dn") ' display name
ds.PropertiesToLoad.Add("pwdLastSet")
ds.SearchScope = SearchScope.Subtree
Dim results As SearchResult = ds.FindOne
If results IsNot Nothing Then
Return New DirectoryEntry(results.Path)
Else
Return Nothing
End If
End Function
Public Shared Sub DeleteUser(ByVal username As String, Optional ByVal useImpersonation As Boolean = False)
Dim user As DirectoryEntry = GetUser(username)
Dim ou As DirectoryEntry = user.Parent
ou.Children.Remove(user)
ou.CommitChanges()
End Sub
Looking at your code, here are some ideas that come to mind:
*
*Try using dsrc.PropertiesToLoad.Add("sAMAccountName")
*Try adding a call to ent.CommitChanges()
*Can you verify the path and credentials are correct, say, using a command-line AD query tool?
*Can you determine specifically what line the error occurs on?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to retrieve users given user_level in rails Here is two models: user and user_level. User has_many user_levels and user-level belongs to user.
class user < ActiveRecord::Base
has_many :user_level
end
class UserLevel < ActiveRecord::Base
belongs_to :user
end
UserLevel.find_by_role('sales') will retrieve all record (w/ user_id) of role sales. How to retrieve user email given user_level with role 'sales'?
Thanks.
A: User.joins(:user_levels).where(:user_levels => { :role => "sales"}).select("email")
or
UserLevel.joins(:user).where(:role => "sales").select("email")
update
UserLevel.find_by_role("sales").users
A: You may have the associations backwards and actually want:
class User < ActiveRecord::Base
belongs_to :user_level
end
class UserLevel < ActiveRecord::Base
has_many :users
end
Then:
@users = UserLevel.find_by_role('sales').users
You can then iterate over the @user collection and use the email within the iterations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I configure the Airbrake gem to log all Rails exceptions in both development and production environments? I have found it difficult to send exceptions of my Rails 3 app via the Airbrake gem. At first I thought there was an Airbrake configuration error on my part, but after trial and error and reading the documentation (https://github.com/thoughtbot/airbrake#readme) very closely, I found out that Airbrake does not report errors when an app is running in the development environment. It does report errors when the app is running in the production environment.
Is there a flag to generate an Airbrake configuration file that automatically includes the development environment in the list of environments in which notifications should not be sent?
Currently I am executing the command listed in the README
script/rails generate airbrake --api-key your_key_here
A: Straightforward.
config.consider_all_requests_local = false
instead of
config.consider_all_requests_local = true
in your config/environments/development.rb. In my case, like I suspect in many others, it was just a temporary change so I can "test" Airbrake's notify_airbrake.
You do need config.development_environments = [] in airbrake.rb
A: Not sure about a config options, but you can explicitly send notifications to Airbrake from a controller using
notify_airbrake(exception)
So to do this in development, you could catch all errors in your application_controller, send a notification and then handle the errors as before. Take a look at rescue_from to get started. This is how I'm doing this to get notifications from my staging environment (or, to be exact, any environment other than development and test).
class ApplicationController < ActionController::Base
rescue_from Exception, :with => :render_error
private
def render_error(exception)
render :file => "#{Rails.root}/public/500.html", :layout => false, :status => 500
logger.error(exception)
notify_airbrake(exception) unless Rails.env.development? || Rails.env.test?
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: "Unhover" CSS-animated DIV on iPhone I have the following HTML:
<div class="gallery" id="gallery-tl" title="<strong>My Title</strong>">
<div class="slides" id="slides-tl">
<img src="img/project-tl-01.png" alt="Shot">
<img src="img/project-tl-02.png" alt="Shot">
<img src="img/project-tl-03.png" alt="Shot">
<img src="img/project-tl-04.png" alt="Shot">
<img src="img/project-tl-05.png" alt="Shot">
</div>
<small class="next" id="next-tl">next image…</small>
<div class="gallery-nav clearfix">
<span class="launch">description</span>
<ol class="" id="nav-tl"></ol>
</div>
</div
which I would like to animate with the jQuery Cycle Plugin. The div.gallery is again a slide in another cycle gallery.
The small.next is the trigger for the next: parameter in Cycle and should be positioned absolutely over the img, faded in and out with CSS opacity on :hover.
Now with the iPhone, once touched, the :hover status won't go away so the images remain shaded.
Somebody been through this and knows what to do?
A: I haven't tried this but you could try to capture the touchend event and remove the hover state when it triggers like so
$("small.next").bind('touchend', function(event){
$(this).removeClass('hover');
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Google maps: zoom in/out with panning to specific point like in maps.google.com context menu I have a project with google maps. I want to emulate maps.google.com context menu with Zoom in and Zoom out actions.
The google.maps.Map.setZoom() is zooming map to the center point but in maps.google.com when you right click at the specific point and select Zoom In/Out action, map is panning so that this specific point stays at the same place.
For example, if I right click on the point in the left-top corner and select Zoom in in context menu, then this pont stays under cursor after zoom and doesn't go out of the map border.
Is there an easy way to implement this feature?
A: You could handle it with markers.
I don't know if it's the most efficient way.
So you add a marker where your current mouse position is (you can track your mouse cursor, right? Haven't done anything last time with it)
Then you set the map centre to that marker (i know, that there is a function for it) and just delete the marker.
Edit: oh sorry, i guess i misunderstood your problem. Cuz that would be the same as double clicking a point right?
So you want to have the distance mouse<->top and mouse<->left on the sceen stays as it is with the point under it, but one stage more zoomed in/out?
A: An equivalent problem was asked and answered at: Zoom toward mouse (eg. Google maps).
My approach to the problem is along the same lines, except that my map pixel coordinates are all calculated relative to the centre of the map (rather than top-left corner):
*
*Determine the pixel offset of your Specific Point relative to the Center of the map. The Map Rectangle dimensions in pixels can be obtained something like map.getDiv().getClientRects()[0] and the Center is just the center of the rectangle.
*Calculate what the new pixel offset of the Specific Point will be after zoom in/out. For a Google Maps zoom in all pixel offsets are doubled (for a single zoom step) so if your Specific Point was [30, 40] from the Centre, it will be [60, 80] from the Map Centre after a normal zoom in (or it will be [15, 20] after a normal zoom out.)
*Calculate how much you need to adjust the Map Center after zoom, so the Specific Point is back where it began. In the above example, after zoom in we would need to map.panBy(-30, -40), alternatively after zoom out we would need to map.panBy(15, 20).
*Apply the normal map.setZoom(zoom) followed by calculated map.panBy(dX, dY) to recenter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using setTexture for animating in Cocos2d? Let's say that I got 120 image files in my project. And I want to animate a sprite with all of them.
I was thinking about this method:
CCSprite *temp = [CCSprite spriteWithFile:@"TheNextSprite.png"];
[sprite setTexture:[temp texture]];
The above code will run like once every 0.03 seconds.
sprite is my animated CCSprite.
temp is simply a temporary CCSprite initialized with the image file for the next animation frame, so I can take its texture later.
Is that way efficient? I heard that I could use CCAnimate with a CCSpriteBatchNode, but this is only for one single sprite. Plus I got 120 (big) frames - they won't fit in a 2048x2048 texture canvas.
A: Have a look at the CCAnimation, CCAnimate and CCSpriteFrame classes.
Sprite frames are what you are trying to mimic, a 'piece' of a texture to which a sprite is mapped. They are best used when combined with spritesheets, not all of the sprites in the animation need to be in the same sprite sheet.
CCAnimation allows you to create an animation out of a sequence of such frames.
And CCAnimate allows you to run that animation as an action:
[node runAction:[CCAnimate actionWithAnimation:animationInstance restoreOriginal:NO]];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7562172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.