text
stringlengths
8
267k
meta
dict
Q: jquery ui: Is there a way to distinguish a 'real' event from an api call? I am using tabs from jquery ui where a select-callback is included, working as expected. At one point of the script I need to do a select-method call that also triggers the callback which is not wanted at that point. What I am looking for is some difference in the event-parameter of the callback which could be used in an if-clause to prevent the contents from the callback to be executed.. I tried stopPropagating, but then the default tab functions are not executed either (the classes are not reset) I hope someone understands what I am looking for :) thanks in advance A: To distinguish a real event from a programmatically generated one you should check for event.originalEvent wich is undefined if the event is generated programmatically for example: <button id='my'>Click me</button> <button id='my2'>Click the other</button> $('#my2').click(function(){ $('#my').click(); }); $('#my').click(function(event){ if (event.originalEvent === undefined){ alert('computer'); }else{ alert('human'); } }); fiddle here: http://jsfiddle.net/uqNHd/
{ "language": "en", "url": "https://stackoverflow.com/questions/7569921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: T4MVC and testing with MvcContrib.TestHelpers issues with static linked content I'm trying to write some tests around some code previously written before I start mucking with it. I'm running into issues where the controller method references some of the static variables that T4MVC makes for images and links. It is actually the same problem as my previous question here, but it's not in a constructor. The issue is code like this: if (User.IsInRole("Rate Admin") || User.IsInRole("Administrator")) { _ratesViewData.ActionLinks = new List<CustomActionLink> { new CustomActionLink("Edit", editPath + Resources.DelimeterHyphen, Links.Content.Images.openwhite_gif), new CustomActionLink("Delete", statusPath + Resources.DelimeterHyphen, Links.Content.Images.openwhite_gif) }; } The problem is the Links.Content.Images.openwhite_gif, down in T4MVC generated code it calls VirtualPathUtility.ToAbsolute from the static method ProcessVirtualPath. I can't seem to mock ProcessVirtualPath or the VirtualPathUtility. Now a comment above ProcessVirtualPath says it is called through a delegate to allow it to be replaced for unit testing. The delegate is: public static Func<string, string> ProcessVirtualPath = ProcessVirtualPathDefault; How do I replace that is being called for ProcessVirtualPath to allow for unit testing. I don't care if it really gets a valid path, I just don't want it to blow up. Can I do that from my test method? With out changing code to test if it's in debug in a non test project? Also a related question is what is best practice for a piece of code like above? Where should one have code for permissions based conditions? Or even the actionlinks. I'm not sure why they are in a viewdata model. OK I did get this to work with code mentioned in comment. T4MVCHelpers.ProcessVirtualPath = (s) => "~/Content/Images"; BUT only when the test is ran individually, any test that needs this will fail if it is ran with another test that uses the TestControllerBuilder class and doesn't set it. Why? A: Maybe I'm not fully understanding the question, but why can't you just set T4MVCHelpers.ProcessVirtualPath to some other method? A: I was able to get this to work if I set the ProcessVirtualPath delegate in a static constructor on my test class. public class BaseTest { static BaseTest() { T4MVCHelpers.ProcessVirtualPath = s => s.TrimStart('~'); } // TEST CODE }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to scale text's size along with TextBox's size in the WPF? When I resize Window of the WPF application, all textboxes are also resized. The problem is that size of the text in the textboxes doesn't change. How can I achieve scaling the size of the text along with the size of the textboxes? Edit: Actually, it is scaling, but I want to make text bigger. So, the height of the font should be close to height of the textbox. How this can be achieved? A: maybe something like this will help <Viewbox> <TextBox/> </Viewbox> Just play with the maring property of the TextBox to get what you want A: I Think You Can Use This Code:\ In SizeChange Event In TextBox private void TextBox_SizeChanged(object sender, SizeChangedEventArgs e) { Size n = e.NewSize; Size p = e.PreviousSize; double l = n.Width / p.Width; if (l!=double.PositiveInfinity) { textbox1.FontSize = textbox1.FontSize * l; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JFormattedTextField to format percent numbers? I would like to format a float number as a percent-value with JFormattedTextField that allows inputs from 0 to 100 percent (converted to 0.0f-1.0f), always shows the percent sign and disallows any invalid characters. Now I have experimented a bit with NumberFormat.getPercentInstance() and the NumberFormatter attributes but without success. Is there a way to create a JFormattedTextField that obeys to these rules with the standard classes? Or do I have to implement my own NumberFormatter? That's what I have so far (no way to input 100%, entering a 0 breaks it completly): public class MaskFormatterTest { public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Test"); frame.setLayout(new BorderLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); NumberFormat format = NumberFormat.getPercentInstance(); NumberFormatter formatter = new NumberFormatter(format); formatter.setMaximum(1.0f); formatter.setMinimum(0.0f); formatter.setAllowsInvalid(false); formatter.setOverwriteMode(true); JFormattedTextField tf = new JFormattedTextField(formatter); tf.setColumns(20); tf.setValue(0.56f); frame.add(tf); frame.pack(); frame.setVisible(true); } } A: Ok, I've made it. The solution is far from simple, but at least it does exactly what I want. Except for returning doubles instead of floats. One major limitation is that it does not allow fraction digits, but for now I can live with that. import java.awt.BorderLayout; import java.text.NumberFormat; import java.text.ParseException; import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultFormatterFactory; import javax.swing.text.DocumentFilter; import javax.swing.text.NavigationFilter; import javax.swing.text.NumberFormatter; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.Position.Bias; public class JPercentField extends JComponent { private static final double MIN_VALUE = 0.0d; private static final double MAX_VALUE = 1.0d; private static final double STEP_SIZE = 0.01d; private static final long serialVersionUID = -779235114254706347L; private JSpinner spinner; public JPercentField() { initComponents(); initLayout(); spinner.setValue(MIN_VALUE); } private void initComponents() { SpinnerNumberModel model = new SpinnerNumberModel(MIN_VALUE, MIN_VALUE, MAX_VALUE, STEP_SIZE); spinner = new JSpinner(model); initSpinnerTextField(); } private void initSpinnerTextField() { DocumentFilter digitOnlyFilter = new PercentDocumentFilter(getMaximumDigits()); NavigationFilter navigationFilter = new BlockLastCharacterNavigationFilter(getTextField()); getTextField().setFormatterFactory( new DefaultFormatterFactory(new PercentNumberFormatter(createPercentFormat(), navigationFilter, digitOnlyFilter))); getTextField().setColumns(6); } private int getMaximumDigits() { return Integer.toString((int) MAX_VALUE * 100).length(); } private JFormattedTextField getTextField() { JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor) spinner.getEditor(); JFormattedTextField textField = jsEditor.getTextField(); return textField; } private NumberFormat createPercentFormat() { NumberFormat format = NumberFormat.getPercentInstance(); format.setGroupingUsed(false); format.setMaximumIntegerDigits(getMaximumDigits()); format.setMaximumFractionDigits(0); return format; } private void initLayout() { setLayout(new BorderLayout()); add(spinner, BorderLayout.CENTER); } public double getPercent() { return (Double) spinner.getValue(); } public void setPercent(double percent) { spinner.setValue(percent); } private static class PercentNumberFormatter extends NumberFormatter { private static final long serialVersionUID = -1172071312046039349L; private final NavigationFilter navigationFilter; private final DocumentFilter digitOnlyFilter; private PercentNumberFormatter(NumberFormat format, NavigationFilter navigationFilter, DocumentFilter digitOnlyFilter) { super(format); this.navigationFilter = navigationFilter; this.digitOnlyFilter = digitOnlyFilter; } @Override protected NavigationFilter getNavigationFilter() { return navigationFilter; } @Override protected DocumentFilter getDocumentFilter() { return digitOnlyFilter; } @Override public Class<?> getValueClass() { return Double.class; } @Override public Object stringToValue(String text) throws ParseException { Double value = (Double) super.stringToValue(text); return Math.max(MIN_VALUE, Math.min(MAX_VALUE, value)); } } /** * NavigationFilter that avoids navigating beyond the percent sign. */ private static class BlockLastCharacterNavigationFilter extends NavigationFilter { private JFormattedTextField textField; private BlockLastCharacterNavigationFilter(JFormattedTextField textField) { this.textField = textField; } @Override public void setDot(FilterBypass fb, int dot, Bias bias) { super.setDot(fb, correctDot(fb, dot), bias); } @Override public void moveDot(FilterBypass fb, int dot, Bias bias) { super.moveDot(fb, correctDot(fb, dot), bias); } private int correctDot(FilterBypass fb, int dot) { // Avoid selecting the percent sign int lastDot = Math.max(0, textField.getText().length() - 1); return dot > lastDot ? lastDot : dot; } } private static class PercentDocumentFilter extends DocumentFilter { private int maxiumDigits; public PercentDocumentFilter(int maxiumDigits) { super(); this.maxiumDigits = maxiumDigits; } @Override public void insertString(FilterBypass fb, int offset, String text, AttributeSet attrs) throws BadLocationException { // Mapping an insert as a replace without removing replace(fb, offset, 0, text, attrs); } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { // Mapping a remove as a replace without inserting replace(fb, offset, length, "", SimpleAttributeSet.EMPTY); } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { int replaceLength = correctReplaceLength(fb, offset, length); String cleanInput = truncateInputString(fb, filterDigits(text), replaceLength); super.replace(fb, offset, replaceLength, cleanInput, attrs); } /** * Removes all non-digit characters */ private String filterDigits(String text) throws BadLocationException { StringBuilder sb = new StringBuilder(text); for (int i = 0, n = sb.length(); i < n; i++) { if (!Character.isDigit(text.charAt(i))) { sb.deleteCharAt(i); } } return sb.toString(); } /** * Removes all characters with which the resulting text would exceed the maximum number of digits */ private String truncateInputString(FilterBypass fb, String filterDigits, int replaceLength) { StringBuilder sb = new StringBuilder(filterDigits); int currentTextLength = fb.getDocument().getLength() - replaceLength - 1; for (int i = 0; i < sb.length() && currentTextLength + sb.length() > maxiumDigits; i++) { sb.deleteCharAt(i); } return sb.toString(); } private int correctReplaceLength(FilterBypass fb, int offset, int length) { if (offset + length >= fb.getDocument().getLength()) { // Don't delete the percent sign return offset + length - fb.getDocument().getLength(); } return length; } } } A: 1) consider using JSpinner instead of JFormattedTextField because there you can set SpinnerNumberModel for initial values from API Integer value = new Integer(50); Integer min = new Integer(0); Integer max = new Integer(100); Integer step = new Integer(1); and with simple hack for JSpinner (with SpinnerNumberModel) it doesn't allows another input as Digits, otherwise is there possible input any of Chars 2) for JFormattedTextField you have to implements * *DocumentListener *Document and of both cases for JFormattedTextField you have to write workaround for catch if value is less or more than required range ... EDIT: . . not true at all, :-) you are so far from ... simple wrong :-), there is small mistake with your result, please look at this code import java.awt.BorderLayout; import java.text.NumberFormat; import javax.swing.*; import javax.swing.text.*; public class TestDigitsOnlySpinner { public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame("enter digit"); JSpinner jspinner = makeDigitsOnlySpinnerUsingDocumentFilter(); frame.getContentPane().add(jspinner, BorderLayout.CENTER); frame.getContentPane().add(new JButton("just another widget"), BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } private JSpinner makeDigitsOnlySpinnerUsingDocumentFilter() { JSpinner spinner = new JSpinner(new SpinnerNumberModel()); JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor) spinner.getEditor(); JFormattedTextField textField = jsEditor.getTextField(); final DocumentFilter digitOnlyFilter = new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { if (stringContainsOnlyDigits(string)) { super.insertString(fb, offset, string, attr); } } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { super.remove(fb, offset, length); } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if (stringContainsOnlyDigits(text)) { super.replace(fb, offset, length, text, attrs); } } private boolean stringContainsOnlyDigits(String text) { for (int i = 0; i < text.length(); i++) { if (!Character.isDigit(text.charAt(i))) { return false; } } return true; } }; /*NumberFormat format = NumberFormat.getIntegerInstance(); format.setGroupingUsed(false);// or add the group chars to the filter NumberFormat format = NumberFormat.getInstance();*/ NumberFormat format = NumberFormat.getPercentInstance(); format.setGroupingUsed(false); format.setGroupingUsed(true);// or add the group chars to the filter format.setMaximumIntegerDigits(10); format.setMaximumFractionDigits(2); format.setMinimumFractionDigits(5); textField.setFormatterFactory(new DefaultFormatterFactory(new InternationalFormatter(format) { private static final long serialVersionUID = 1L; @Override protected DocumentFilter getDocumentFilter() { return digitOnlyFilter; } })); return spinner; } }); } } A: Imho https://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html gives a pretty good example (see section "Specifying Formatters and Using Formatter Factories"). The key is to use a Percent Format to display values and a custom NumberFormatter to edit values. This approach also allows the use of fraction digits. // create a format for displaying percentages (with %-sign) NumberFormat percentDisplayFormat = NumberFormat.getPercentInstance(); // create a format for editing percentages (without %-sign) NumberFormat percentEditFormat = NumberFormat.getNumberInstance(); // create a formatter for editing percentages - input will be transformed to percentages (eg. 50 -> 0.5) NumberFormatter percentEditFormatter = new NumberFormatter(percentEditFormat) { private static final long serialVersionUID = 1L; @Override public String valueToString(Object o) throws ParseException { Number number = (Number) o; if (number != null) { double d = number.doubleValue() * 100.0; number = new Double(d); } return super.valueToString(number); } @Override public Object stringToValue(String s) throws ParseException { Number number = (Number) super.stringToValue(s); if (number != null) { double d = number.doubleValue() / 100.0; number = new Double(d); } return number; } }; // set allowed range percentEditFormatter.setMinimum(0D); percentEditFormatter.setMaximum(100D); // create JFormattedTextField JFormattedTextField field = new JFormattedTextField( new DefaultFormatterFactory( new NumberFormatter(percentDisplayFormat), new NumberFormatter(percentDisplayFormat), percentEditFormatter));
{ "language": "en", "url": "https://stackoverflow.com/questions/7569929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to use php to make a request to another server and get its response? For instance user.php -> make a post request to a server http://www.exampe.com, example.com redirects to user.php and puts some post parameters as well to user.php. I want a function in php to do that? Anyone with a solution for me? I cannot use ajax for this. A: Yes, you can achieve such functionality using cURL from PHP. Check out the examples in the PHP documentation. A: For simple requests file_get_contents() will do the trick. For more complex requirements, you van use cURL, a simple example (returning both headers and resonse body): <?php function curlPull($url) { $cPtr = curl_init(); curl_setopt_array($cPtr, array(CURLOPT_URL => $url, CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true)); return curl_exec($cPtr); } print_r( curlPull('http://www.example.com') ); ?> cURL allows for many more options to be tweaked, take a look at curl_setopt A: I'll speculate that eventually such questions as * *Is remote access feasible withOUT cURL? and *Are asynchronous requests possible? will arise. While stackoverflow already abounds in explorations of these, I'll recommend http://www.ibm.com/developerworks/web/library/os-php-multitask/
{ "language": "en", "url": "https://stackoverflow.com/questions/7569931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Database schema of messaging application In my messaging application, The features I want to provide are: * *Sending a message to multiple people *Receiving message sent to a user *Showing message in groups divided by the users, Like in facebook message *But when a user will send a message to multiple people, It will not be a group message but those messages will go in groups divided by users My database schema is like this This schema is able to provide all the functions above but getting the message out from this kind of schema in groups of users is very complex. Can anyone suggest me some better schema?? The unnamed table is of receivers mapping, forgot to write the name in jpg. :( A: What is wrong with one table? message_id timestamp to from subject body attachment_pointer origin ... I'll probably get thrashed for it but... hmm...good point Messages message_id timestamp subject body attachment MessageReference mr_id message_id to from edit: Also found these: Messaging system database schema thread messaging system database schema design How should I setup my database schema for a messaging system complete with attachments? Database schema for messaging to multiple users A: Hi you can use a joining table. This is very simple architecture which lot of giants are using like YouTube, Reddit etc. Here is a video explaining how only 2 queries will be bringing your app to live.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Pop navigation controller and select tab? Hi guys I have a navcontroller inside a tabbar. When I select a button inside the root view controller I push another view controller. In it I take some user input and have a finish button. My problem is that when the user selects this button I want to go straight to another tab, but at the same time I want to pop to the root view controller in the current tab, so that the next time the user presses the tab he/she will go to its original state. Any ideas? A: after pop the navigation controller call the setSelectedIndex: on your tab bar controller instance. and you can also handle your tab bar controller delegates in your app delegate - - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController here you can pop your navigation controller to root.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to add window android.view.ViewRoot$W@44da9bc0 -- permission denied for this window type I have prefer this post for example but I got the error at adding viewgroup into the windowmanager object, I have used the same class for the Service as posted into the question with no change where I can mistake I didn't gettting it WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); wm.addView(mView, params); // here when I add view to the WindowManger here is my manifest file <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.searce.testoverlay" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="7" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="TestOverlayActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:enabled="true" android:name=".HUD"></service> </application> </manifest> error 09-27 18:49:23.561: ERROR/AndroidRuntime(653): Uncaught handler: thread main exiting due to uncaught exception 09-27 18:49:23.571: ERROR/AndroidRuntime(653): java.lang.RuntimeException: Unable to create service com.searce.testoverlay.HUD: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRoot$W@44da9bc0 -- permission denied for this window type 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2790) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at android.app.ActivityThread.access$3200(ActivityThread.java:119) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1917) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at android.os.Handler.dispatchMessage(Handler.java:99) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at android.os.Looper.loop(Looper.java:123) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at android.app.ActivityThread.main(ActivityThread.java:4363) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at java.lang.reflect.Method.invokeNative(Native Method) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at java.lang.reflect.Method.invoke(Method.java:521) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at dalvik.system.NativeStart.main(Native Method) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): Caused by: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRoot$W@44da9bc0 -- permission denied for this window type 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at android.view.ViewRoot.setView(ViewRoot.java:492) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at com.searce.testoverlay.HUD.onCreate(HUD.java:41) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2780) 09-27 18:49:23.571: ERROR/AndroidRuntime(653): ... 10 more A: Following ceph3us answer to add an Alert Dialog, this worked fine final AlertDialog dialog = dialogBuilder.create(); final Window dialogWindow = dialog.getWindow(); final WindowManager.LayoutParams dialogWindowAttributes = dialogWindow.getAttributes(); // Set fixed width (280dp) and WRAP_CONTENT height final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialogWindowAttributes); lp.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 280, getResources().getDisplayMetrics()); lp.height = WindowManager.LayoutParams.WRAP_CONTENT; dialogWindow.setAttributes(lp); // Set to TYPE_SYSTEM_ALERT so that the Service can display it if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { dialogWindow.setType(WindowManager.LayoutParams.TYPE_TOAST); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { dialogWindow.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY); } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { dialogWindow.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); } dialog.show(); But using TYPE_SYSTEM_ALERT might trigger Google takedown policy of apps using dangerous permissions. Make sure you have a valid justification in case google requires it. A: Try using this permission in AndroidManifest. android.permission.SYSTEM_ALERT_WINDOW on API >= 23 see A: "@ceph3us do you know how to achieve it for >=M? ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW}..." * *SYSTEM_ALERT_WINDOW PERMISSION on API >= 23 (Draw over other apps etc): * *no longer appears in App's Permissions screen. *it doesn't even appear in the strangely confusing new "All permissions" screen *Calling Activity.requestPermissions() with this permission, * *will not show any dialog for the user to Allow/Deny. *instead, the Activity.onRequestPermissionsResult() callback will be called immediately with a denied flag. Solution: If the app targets API level 23 or higher, the app user must explicitly grant this permission to the app through a permission management screen. The app requests the user's approval by sending an intent with action ACTION_MANAGE_OVERLAY_PERMISSION. The app can check whether it has this authorization by calling Settings.canDrawOverlays() example code: /** code to post/handler request for permission */ public final static int REQUEST_CODE = -1010101; *(see edit II)* public void checkDrawOverlayPermission() { /** check if we already have permission to draw over other apps */ if (!Settings.canDrawOverlays(Context)) { /** if not construct intent to request permission */ Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); /** request permission via start activity for result */ startActivityForResult(intent, REQUEST_CODE); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { /** check if received result code is equal our requested code for draw permission */ if (requestCode == REQUEST_CODE) { / ** if so check once again if we have permission */ if (Settings.canDrawOverlays(this)) { // continue here - permission was granted } } } "And how can the user disable this permission ? It doesn't show in the permissions in settings->apps->"MyApp"->permissions. Also...any explanation as to why this permission is different from the others in the way we request for it? – Anonymous Feb 12 at 21:01" There are a couple of permissions that don't behave like normal and dangerous permissions. SYSTEM_ALERT_WINDOW and WRITE_SETTINGS are particularly sensitive, so most apps should not use them. If an app needs one of these permissions, it must declare the permission in the manifest, and send an intent requesting the user's authorization. The system responds to the intent by showing a detailed management screen to the user. Special Permissions edit II: I used this code in an Activity extending FragmentActivity and I got Exception java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode because request code used is not in the range of 0.. 65535. You might consider changing your request code to an appropriate value. – mtsahakis as it sais: request code must be in the range of 0.. 65535. this is becaus: * *integer in java is represented by 32 bits *you are allowed to use lower 16 bits for requestCode *other bits are used in request processing so for example: integer value: 5463 ///hi 16 bits // | // lo 16 bits // as binary string will look like: 0000 0000 0000 0000 0001 0101 0101 0111 simple use code in given range edit III: for apps targeting AOSP API 26 (android oreo / 8+ ) Apps that use the SYSTEM_ALERT_WINDOW permission can no longer use the following window types to display alert windows above other apps and system windows: TYPE_PHONE TYPE_PRIORITY_PHONE TYPE_SYSTEM_ALERT TYPE_SYSTEM_OVERLAY TYPE_SYSTEM_ERROR Instead, apps must use a new window type called TYPE_APPLICATION_OVERLAY. TYPE_APPLICATION_OVERLAY Window type: Application overlay windows are displayed above all activity windows (types between FIRST_APPLICATION_WINDOW and LAST_APPLICATION_WINDOW) but below critical system windows like the status bar or IME. The system may change the position, size, or visibility of these windows at anytime to reduce visual clutter to the user and also manage resources. Requires SYSTEM_ALERT_WINDOW permission. The system will adjust the importance of processes with this window type to reduce the chance of the low-memory-killer killing them. In multi-user systems shows only on the owning user’s screen. WindowManager.LayoutParams wLp = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY : WindowManager.LayoutParams.TYPE_PHONE; Window.setAttributes(WindowManager.LayoutParams) A: You can change your target SDK to 22 or less, then it also works on API 23. Change it in Gradle.Build.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "82" }
Q: Creating a closure I want to create a closure (function generator) to raise a number to a power, without using a specific Clojure library to accomplish this task. Right now, I can do this with loop .. recur. (defn exp1 [in-num in-exp-multi] (loop [num in-num exp-multi in-exp-multi] (if (> exp-multi 1) (recur (* num in-num) (- exp-multi 1)) num))) I have tried using partial to raise the power, but am still stuck on the construct needed to repeat multiplying a number by itself some number of times. So, I am looking for an example of generating a function and applying it x number of times. Edit: The example was simply to solve a problem using loop .. recur. My desire is to solve this with a closure. A: I can't tell from your question precisely what you're asking for, but maybe this? (defn powers-of [exponent] (iterate #(* % exponent) 1)) (defn nth-power-of [exponent] (partial nth (powers-of exponent))) ((nth-power-of 5) 2) ;; returns 25 I think iterate is what you're looking for based on your description; it creates a lazy seq of the function applied over and over to the seed. A: This returns a closure over both arguments - (defn exp1 [in-num in-exp-multi] (fn [] (loop [num in-num exp-multi in-exp-multi] (if (> exp-multi 1) (recur (* num in-num) (- exp-multi 1)) num))))
{ "language": "en", "url": "https://stackoverflow.com/questions/7569939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: cancan & many_to_many associations I'm trying to write a rule for many_to_many association. Because of the association table some results are duplicated. The code in my ability is: I have many Users that have many Groups and i want to show all Post that their author belongs to a group the same as the current_user's group. can :read, Post, :user => { :group => { :id => user.groups.collect { |g| g.id } } } I took the generated SQL from the log and ran it in MySql query builder. The duplications appear at the SQL level. How can i get rid of the duplicated results ?! UPDATE 1: The generated SQL: SELECT posts.* FROM posts INNER JOIN users ON users.id = posts.user_id INNER JOIN groups_users ON groups_users.user_id = users.id INNER JOIN groups ON groups.id = groups_users.group_id WHERE (groups.id IN (1, 2)) LIMIT 30 OFFSET 0 i updated my post to include the generated SQL. the problem is that if a user belongs to 2 groups than i get duplicated results. isn't there a way to "distinct" the results ? A: You could try using the uniq Array method after you've returned the group IDs. A: Instead of: can :read, Post, :user => { :group => { :id => user.groups.collect { |g| g.id } } } Try: can :read, Post, :user => {:group => { :id => user.groups.map(&:id).uniq } } A: I decided to use a named scope in order to get DISTINCT results for my query. I added this to post.rb: named_scope :unique_posts, :select => "DISTINCT 'posts'.*" Now i get distinct results when i call @posts.unique_posts
{ "language": "en", "url": "https://stackoverflow.com/questions/7569945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how important is it to declare the correct variable type If I have a number only between 1 & 10 is it overkill declare it as int or should you use short, Long, sbyte? int x = 5; or sbyte x = 5; A: int is handled faster on 32 bit processors, since its size is equal to CPU register size. If you don't have additional requirements (the need to conserve memory, for example), use int. A: Without more context I would say just use an int. Overkill only matters when you have space constraints or it overly complicates what you're trying to do. A: Not really unless your are tying to get minuscule amounts of performance and memory footprint out of your application. However I would suggest using the correct type if not for readability purposes and also so that if the value increases above it's allocated type size then this potential bug will be caught at compile time. A: Call a dog a dog and a salesman a salesman. Declaring your variables in the right type is fundamental for code readability and accuracy. Now, for your example, if you are sure it's only from one to 10, you can use sByte. I would, however, use int. We should not overcomplicate, whenever we can. Also, as well noticed by @ElRonnoco, if you are planning to execute calculations, you might get an overflow error when dealing with small numeric types so you should stick to int for most things. A: Simplicity in your code is an important feature for long term maintainability. Unless optimization is vitally important such as in super high speed applications (games where instant reactions are critical), don't waste time worrying over a few bytes that would make it harder for the next guy to understand. A: When in doubt, don't optimize. Over optimization in the early stages of a code base is usually a bad idea and leads to abstraction leakage, bad versatility of the code base and hard to debug problems. Stick with the most common types in the type system and whenever you discover that the type only needs to be short or uint, you can always change type later on. It's easier to start out wide and narrow the types down than the other way around and before you have a working code base that integrates with 3rd party systems and such, it's impossible to know exactly where the boundaries in your code needs to be drawn.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with style on GWT Designer I'm trying to create a login view with GWT Designer. I have the styles using twitter bootstrap. I have this structure I have this result This padding and margin are killing me, I have all css with padding and border set to 0 but it makes no difference...and I have also set those properties on GWT Designer to 0. I'm running the application directly with Eclipse, I'm not compiling it yet. Thanks in advance for any help. I just test on tomcat, same thing A: I have used my HTML inside HTMLPanel and changed the inputs for the corresponding on GWT
{ "language": "en", "url": "https://stackoverflow.com/questions/7569951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set setMaxMapTaskFailuresPercent in hadoop's new api? Before, you could set max failures percent by using: JobConf.setMaxMapTaskFailuresPercent(int) but now, that's obsolete. job.getConfiguration().set("mapred.max.map.failures.percent", "100"); doesn't seem to work as well. What is the proper way of doing this in new hadoop api? A: On 1.0.2, list of supported options are given in http://hadoop.apache.org/common/docs/r1.0.2/mapred-default.html, this you can pass through as a java system property through java -DoptionName=value when running the map reduce job. Also to set them via the command line, see http://hadoop.apache.org/common/docs/r1.0.2/mapred_tutorial.html#Job+Configuration A: If you want to quickly find the correct names for the options for hadoop's new api, use this link: http://pydoop.sourceforge.net/docs/examples/intro.html#hadoop-0-21-0-notes .
{ "language": "en", "url": "https://stackoverflow.com/questions/7569959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET MVC 3 multilingual website with Mustache templates Was just wondering what the best approach is when creating a multi-lingual website that uses Mustache templates (or any other templating library). If for example you had the following template: <table class="tablesorter zebra-striped"> <thead> <tr> <td>Name</td> <td>Description</td> <td>Comments</td> </tr> </thead> <tbody> {{#list}} <tr> <td>{{Name}}</td> <td>{{Description}}</td> <td>{{Comments}}</td> </tr> {{/list}} </tbody> </table> What would be the best way to display langauge specific text for the table headings ('Name', 'Description', 'Comments'). Render on the server maybe? A: Too much information for a SO answer, so I will refer you to Scott Hanselman's blog post on the topic. A: I would with Mustache if you want a clean platform neutral solution. The Hanselman approach is for .Net only.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sharedobject don't remember data? I have this code for sharedobject: var mySharedObject = SharedObject.getLocal("republicofcode"); mySharedObject.data.clientID = my_vars.clientID; mySharedObject.data.question = my_vars.question; mySharedObject.data.answer = my_vars.answer; mySharedObject.flush(); Next time when I try this code: var mySharedObject = SharedObject.getLocal("republicofcode"); Variable mySharedObject.data.clientID is undefined. I don't know why sharedobject don't remember data? A: Can you try just a basic .fla to test the SharedObject functionality? import flash.net.SharedObject; var so:SharedObject = SharedObject.getLocal('so'); // Run once, then comment out this next line and run again. so.data.me = 'your special data'; trace( so.data.me ); At least we can verify if this is working or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: schema and table design with auto_increment field that is not a key I've an invoice number, this number is associated to a special document. This document has an id, formed by a progressive number and the current year, like this 222-2011 223-2011 224-2011 ... every year the progressive number restart from 1 1-2012 2-2012 3-2012 In the first place I thought to make a table with invoice_n, prog_n, year. prog_n is AUTO_INCREMENT and every year I'll reset it. But you cant use an AUTO_INCREMENT field that isn't a key. Anyway I'm going to reset the counter, and this is not so recommendable... I can't change the id format, I have to use that rule. Can I have an efficient design in some way? the environment is a classic LAMP many thanks! A: You can have a separate id column with auto_increment in your invoices table, and a trigger which fills in prog_n with the following formula : prog_n = id - select max(id) from invoices where year = current_year - 1 This way, your prog_n resets automatically each year and you don't need to do it manually. However, it might be a performance issue if you insert a lot of invoices in your table, but I don't think that will happen in practice. A: Expanding on @Marius answer, I'd use a trigger to have MySQL set the invoicenumber automatically like so: DELIMITER $$ CREATE TRIGGER bi_invoices_each BEFORE INSERT ON invoices FOR EACH ROW BEGIN DECLARE lastest_invoice_number VARCHAR(20); DECLARE numberpart INTEGER; -- find lastest invoicenumber in the current year. SELECT COALESCE(max(invoicenumber),0) INTO lastest_invoice_number FROM invoice WHERE invoice_date >= MAKEDATE(YEAR(NEW.invoice_date) ,1) AND invoice_date < MAKEDATE(YEAR(NEW.invoice_date)+1,1); -- extract the part before the '-' SET numberpart = SUBSTRING_INDEX(lastest_invoice_number,'-',1) SET NEW.invoicenumber = CONCAT(numberpart+1,'-',YEAR(NEW.invoice_date)); END $$ DELIMITER ; Note that you cannot access an auto-incrementing id in a before trigger; Only in the after trigger can you do this, but there you cannot change any values, so a little trickery is required. More trickery was used to make sure we use invoice_date as is in the select query so that an index on that field can be used. See: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_makedate
{ "language": "en", "url": "https://stackoverflow.com/questions/7569972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Forking an Apache License v2 open source project and copyright notices I'm planning to fork an open-source project which is licensed under Apache License v2. Most of the existing sources have a copyright notice in the heade, Copyright bla bla, Inc. If I change some these sources in my fork (even if only marginally), what happens to the copyright? Will it become a joined copyright notice like "Copyright bla bla, Inc and Thomas"? A: Disclaimer: I'm not a lawyer, just a software developer. This is just my own opinion, in each concrete case if you need legal help you must talk to a legal team on your behalf. If I change some these sources in my fork (even if only marginally), what happens to the copyright? The copyright remains for it's code. If you remove the code, there is no copyright any longer. If you modify the code, it's like you already assume, there is copyright for those lines of code, and copyright for the new lines of code. Will it become a joined copyright notice like "Copyright bla bla, Inc and Thomas"? If there is a notice per file: If you don't change the file, keep it as-is including the copyright header. If you make changes to the file, normally the new copyright is put on top of the file, then making it visible that this is based on the previous code and then the original license plate follows. Most licenses require that you do not change the original copyright/license notice, this is important otherwise you normally loose the rights to make use of the software (e.g. fork it). The important part is that it's clear which code falls under which copyright, so you have it documented on your own as well. With the method described, you know which files you have modified (and which files remain unmodified). Use version control software so you can follow any changes. A good article, even if GPL does not apply for your fork, is: Maintaining Permissive-Licensed Files in a GPL-Licensed Project: Guidelines for Developers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: What encryption method should I use on iOS Android Apps: AES128 or 3DES I have been given the choice by a client of AES128 or 3DES encryption. I have to roll it out on both iOS and Android. Which will be easier to do? Are there libraries for both iOS and Android? Full or Partial answer would be great (i.e. if you only know about one platform) A: Prefer AES128 over 3DES. 3DES provides an effective key size of 112 bits, while AES 128 uses 128 bits of key space. http://en.wikipedia.org/wiki/Aes128 http://en.wikipedia.org/wiki/Triple_DES A: Please read this article in its entirety, and feel free to come back to post further comments or new questions. Cryptographic Right Answers In particular, the very first question answered is: Encrypting data: Use AES in CTR (Counter) mode, and append an HMAC. AES is about as standard as you can get, and has done a good job of resisting cryptologic attacks over the past decade. Using CTR mode avoids the weakness of ECB mode, the complex (and bug-prone) process of padding and unpadding of partial blocks (or ciphertext stealing), and vastly reduces the risk of side channel attacks thanks to the fact that the data being input to AES is not sensitive. However, because CTR mode is malleable, you should always add an HMAC to confirm that the encrypted data has not been tampered with. And the very next question answered is: AES key length: Use 256-bit AES keys. Theoretically speaking, 128-bit AES keys should be enough for the forseeable future; but for most applications the increased cost of using 256-bit keys instead of 128-bit keys is insignificant, and the increased key length provides a margin of security in case a side channel attack leaks some but not all of the key bits. [EDIT 1] Also, the fact that you've applied a "public-key-encryption" tag to your question implies that your understanding of cryptography could be better. Please also read chapter 5 of Security Engineering (PDF) by Ross Anderson; it's free and very accessible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to unload the files loaded by the "require" statement in rails I have bunch of classes files = ["payment_type","payment_type_ticket_mapping","price_modifier_ticket_delta_mapping","user","revenue_type","revenue_type_group","tax","tax_type","punch"] files.each {|file| require file } that are required to fulfill the requirement of Marshal.load but when I run the rsepc they give me the following error /spec/factories.rb:6: undefined method `admin_login_url' for #<ActionView::Base:0xb62e0228> (ActionView::TemplateError) When I remove that reuire statement it works fine but that statement is necessary for the functionality of Marshal.load how to unload the loaded classes by require statement after the work is done. A: I have resolved that problem using the config.cache_classes = true in the environment. A: To unload a file just remove all its definitions, and then remove the file name from the loaded file list $", like the following: $".grep(/#{file}/).each { |f| $".delete(f) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sharepoint 2010: Programmatically access a documents metadata via a link Is it possible to (in code) access the metadata of a document stored in a library via a link to that document? A: Get SPFile object using the SPWeb.GetFile method, then use the Item property of that object to get access to the ListItem accompanying the file. using(SPSite site = new SPSite(link)) { using(SPWeb web = site.OpenWeb()) { SPFile file = web.GetFile(link); SPListItem item = file.Item; object fieldValue = item["some field"]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE7 & IE6 CSS bug I have a problem with our website at www.eat.vn. The site is fine in Firefox, Chrome, IE8 & IE9 and Safari, but in IE6 and IE7 we have a problem with a main design element. Please see the attached image and you will understand that the stacking effect on the tabs is not what I wanted. I have tried to work around this bug, but can't manage to find a solution which does not mess up anything in the other browsers. Any help would be much appreciated! A: I don't have IE6 or IE7 to hand to test this, so I'm shooting in the dark somewhat. My guess is that the issue is related to the container element for the tabs (<div id="steps">). This has a style of float:left;, which I don't believe is necessary; it doesn't need to be floated since it doesn't have any other elements next to it. However this float may be causing the IE6/7 bug; it looks as if this element has decided that it should only be as wide as one of the tabs inside it, which is then causing the tabs to wrap beneath each other. I would therefore suggest taking the float:left away from this container element, and see if that helps. (The tab elements inside it should still be floated, of course)
{ "language": "en", "url": "https://stackoverflow.com/questions/7569995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: matplotlib, rectangular plot in polar axes Is it possible to have a standard rectangular (aka Cartesian) plot, but displayed on a polar set of axes? I just want the masking appearance of the grey border provided by the polar() function, but I do not want to convert my coordinates to polar, and use polar(). A: If you just want to be able to call two arrays in rectangular coordinates, while plotting on a polar grid, this will give you what you need. Here, x and y are your arrays that, in rectangular, would give you an x=y line. It returns the same trend line but on in polar coordinates. If you require more of a mask, that actually limits some of the data being presented, then insert a line in the for loop that says something like: for r < 5.0: or whatever your criteria is for the mask. from math import cos, sin, atan2, sqrt import matplotlib.pyplot as plt plt.clf() width, height = matplotlib.rcParams['figure.figsize'] size = min(width, height) # make a square figure fig = figure(figsize=(size, size)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c') x = range(10) y = range(10) r = [] phi = [] for ii in range(len(x)): r.append(sqrt(x[ii]**2.+y[ii]**2.)) phi.append(atan2(y[ii],x[ii])) ax.scatter(phi,r) show()
{ "language": "en", "url": "https://stackoverflow.com/questions/7569997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android View.Gone doesn't works I have a problem with a textview in android. I made programatically a tablelayout, and i made 9 tablerows in a for (while i have data... make more tablerows). I have 8 columns with data, thats ok. But i have 3 columns that i want to put invisible, because i want data from that textviews but i dont want to see them in my layout. Here i put my code, i dont know why textview.setVisibility(View.GONE) doesn't works.. I put view.gone and in my table appears a black space in my layout (my table background color is black), any help? here is the code public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TableLayout tl = (TableLayout) findViewById(R.id.tabla1); tl.setStretchAllColumns(true); tl.setShrinkAllColumns(true); //------------------------------------------------------ //seteo la fila para el Titulo TableRow rowTitulo = new TableRow(this); rowTitulo.setGravity(Gravity.CENTER_HORIZONTAL); TextView titulo = new TextView(this); titulo.setText("Operativa SHAMAN"); titulo.setTextColor(Color.GREEN); titulo.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); titulo.setGravity(Gravity.CENTER); titulo.setTypeface(Typeface.SERIF, Typeface.BOLD); titulo.setVisibility(4); TableRow.LayoutParams params = new TableRow.LayoutParams(); params.span = 8; rowTitulo.addView(titulo, params); tl.addView(rowTitulo); //-------------------------------------------------------- //seteo los titulos de los campos TableRow rowCampos = new TableRow(this); TextView codServ = new TextView(this); TextView codEnt = new TextView(this); TextView incid = new TextView(this); TextView sint = new TextView(this); TextView codLoc = new TextView(this); TextView numMovil = new TextView(this); TextView sexEdad = new TextView(this); TextView estMovil = new TextView(this); codServ.setTextColor(Color.BLACK); codServ.setText("GR"); codServ.setGravity(Gravity.CENTER); rowCampos.addView(codServ); codEnt.setTextColor(Color.BLACK); codEnt.setText("Entidad"); codEnt.setGravity(Gravity.CENTER); rowCampos.addView(codEnt); incid.setTextColor(Color.BLACK); incid.setText("Inc"); incid.setGravity(Gravity.CENTER); rowCampos.addView(incid); sint.setTextColor(Color.BLACK); sint.setText("Síntomas"); sint.setGravity(Gravity.CENTER); rowCampos.addView(sint); codLoc.setTextColor(Color.BLACK); codLoc.setText("Loc"); codLoc.setGravity(Gravity.CENTER); rowCampos.addView(codLoc); numMovil.setTextColor(Color.BLACK); numMovil.setText("Movil"); numMovil.setGravity(Gravity.CENTER); rowCampos.addView(numMovil); sexEdad.setTextColor(Color.BLACK); sexEdad.setText("SE"); sexEdad.setGravity(Gravity.CENTER); rowCampos.addView(sexEdad); estMovil.setTextColor(Color.BLACK); estMovil.setText("EST"); estMovil.setGravity(Gravity.CENTER); rowCampos.addView(estMovil); tl.addView(rowCampos); //-------------------------------------------------------- //Paso a tv2 el string que me devuelve el webService, y lo spliteo en un array por el parametro $ //que me separa al string por incidente tv2 = resultado.toString(); String [] vecDatos = TextUtils.split(tv2, "\\$"); //voy llenando la tabla con los datos for (int i=0; i <=(vecDatos.length)- 1; i++) { //Spliteo cada elemento del array que contiene los incidentes, asi obtengo cada campo por separado String fila = vecDatos[i].toString(); String [] inc = TextUtils.split(fila, "\\^"); TableRow tr = new TableRow(this); aInt = Integer.parseInt(inc[0]); tr.setId(aInt); tr.setOnClickListener(this); tr.setLayoutParams(new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); //------------------------------------------------- //seteo el campo Grado TextView grado = new TextView(this); grado.setId(200+i); int colorInt = Color.parseColor(inc[1]); grado.setGravity(Gravity.CENTER); grado.setText(inc[2]); grado.setBackgroundColor(colorInt); grado.setTextColor(Color.BLACK); grado.setWidth(10); View v = new View(this); v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1)); v.setBackgroundColor(Color.rgb(0, 0, 0)); tl.addView(v); tr.addView(grado); //---------------------------------------------------------------- //seteo el campo entidad TextView entidad = new TextView(this); entidad.setId(300+i); entidad.setText(inc[3]); entidad.setGravity(Gravity.CENTER); entidad.setTextColor(Color.BLACK); tr.addView(entidad); //------------------------------------------------------------------- //seteo el campo numero de incidente TextView numInc = new TextView(this); numInc.setId(400+i); numInc.setText(inc[4]); numInc.setGravity(Gravity.CENTER); numInc.setTextColor(Color.BLACK); tr.addView(numInc); //------------------------------------------------------------------- //seteo el campo sintomas TextView sintomas = new TextView(this); sintomas.setId(500+i); //hago funcion para que no me tire error si un sintoma no tiene datos o si //tiene menos de 10 caracteres y no lo puedo cortar con el substring de 10 que hago if (inc[5].equals("")) { sintomas.setText("Sin Diag"); } int toChr = 10; if (inc[5].length() < 10) toChr = inc[5].length(); String strSint = inc[5].substring(0,toChr); sintomas.setGravity(Gravity.CENTER); sintomas.setText(strSint); sintomas.setTextColor(Color.BLACK); tr.addView(sintomas); //------------------------------------------------------------------- //seteo el campo localidad TextView localidad = new TextView(this); localidad.setId(600+i); int colorInt2 = Color.parseColor(inc[6]); localidad.setText(inc[7]); localidad.setBackgroundColor(colorInt2); localidad.setGravity(Gravity.CENTER); localidad.setTextColor(Color.BLACK); tr.addView(localidad); //------------------------------------------------------------------- //seteo el campo movil TextView movil = new TextView(this); movil.setId(700+i); String strMovil = inc[8]; //hago funcion para que si el campo tiene una A, va en blanco, si tiene una P, en celeste String [] vecMovil = TextUtils.split(strMovil, "\\|"); if (vecMovil[1].equals("A")) { movil.setTextColor(Color.BLACK); movil.setText(vecMovil[0]); } else { movil.setTextColor(Color.CYAN); movil.setText(vecMovil[0]); } movil.setGravity(Gravity.CENTER); tr.addView(movil); //------------------------------------------------------------------- //seteo el campo Sexo y Edad (juntos) TextView sexoEdad = new TextView(this); sexoEdad.setId(800+i); String sexo = inc[9]; String edad = inc[10].toString(); String strEdadSexo = sexo.concat(edad); sexoEdad.setGravity(Gravity.CENTER); sexoEdad.setText(strEdadSexo); sexoEdad.setTextColor(Color.BLACK); tr.addView(sexoEdad); //------------------------------------------------------------------- TextView est = new TextView(this); est.setId(900+i); est.setText(inc[11]); est.setGravity(Gravity.CENTER); est.setTextColor(Color.BLACK); tr.addView(est); //------------------------------------------------------------------- TextView domicilio = new TextView(this); domicilio.setId(1000+aInt); domicilio.setText(inc[12]); // tr.addView(domicilio); //hago el campo domicilio hidden, esta el textview pero no me ocupa el layout // Agrego el tablerow al tablelayout //------------------------------------------------------------------- TextView latitud = new TextView(this); //latitud = (TextView) findViewById(1100+aInt); latitud.setId(1100+aInt); latitud.setVisibility(View.GONE); latitud.setText(inc[13]); tr.addView(latitud); //------------------------------------------------------------------- TextView longitud = new TextView(this); longitud.setId(1200+aInt); longitud.setVisibility(View.GONE); longitud.setText(inc[14]); // tr.addView(longitud); //------------------------------------------------------------------- tl.addView(tr); I have a tablelayout in my main.xml, but all the other textviews that i add with programatically tablerows are not, cause i am creating them while im having data. I bring data from a webservice, that brings me a string that i split in an array and then i put the arrays information into textviews of each tablerow. A: Use View.INVISIBLE longitud.setVisibility(View.INVISIBLE); This link may also help you out. I am not sure but you may also have to set Color to Transparent (I know buttons have this property not sure about textviews.) longitub.setBackground(Color.TRANSPARENT); //it may be .setBackgroundColor EDIT: To reference in code TextView longitub = (TextView) findByViewid(R.id.longitub); //For this to work you will have to have the textview with the name longitub //in your xml To declare in XML <TextView android:layout_width="fill_parent" //other properties in here > There are also properties in the XML you can use such as android:textColor="@android:color/transparent" A: The code might be missing, but where are you defining the height, width and position of this view? And I don't know what kind of data you want to store, but wouldn't an ArrayList be easier and cleaner to implement?
{ "language": "es", "url": "https://stackoverflow.com/questions/7570002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Algorithm to multiply 64-bit numbers using 32-bit unsigned integers I have 64-bit numbers (63 bits + sign bit), represented as two's complement numbers, stored in two unsigned 32-bit integers. struct Long { uint32 high; uint32 low; } How can I implement a multiplication algorithm, using just 32-bit numbers, and check that the result fits in 63-bits? I want to return an error code indicating overflow if the result doesn't fit. A: Generally you need 2*n bits to store the product of two n bit numbers (largest result is (2^n)^2 = 2^(2*n)), so my best idea is to split up the number into four 16-bit parts, multiply them one by one and add them together. 16 multiplications all in all, but error checking is trivial. A: Have a look at the 'longlong.h' header file in the GNU MP library. I believe that a version of this header is also in the GNU C source. The macro: smul_ppmm is defined in terms of the unsigned double-word product: umul_ppmm. This gives you 32x32=>64 bit multiplication, which you might be able to use to implement 64x64=>128 bit multiplication.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Control Scaling Problem in Windows 7 I have some custom user controls in my .net winforms program that do not display correctly when the user has selected larger text size. This setting: My controls look like this, Instead of like this, The bill to area and ship to area are both custom controls. I don't know if this is contributing to the problem but I do have code in each to help scale the phone/fax areas to stretch nicely, like this code from the bill to control, Private Sub panFaxPhone_Resize(sender As Object, e As System.EventArgs) Handles panFaxPhone.Resize panFax.Width = (panFaxPhone.Width / 2) - 1 panPhone.Width = (panFaxPhone.Width / 2) - 1 panFax.Left = panFaxPhone.Width - panFax.Width End Sub How can I get my controls to size correctly while still respecting the users choice for larger text (I don't want to just set the AutoScaleMode to None) ? Update: After playing with this for a long time it seems to be a problem with anchors in the child controls. See this below image, the inner black box is the control with its border turned on, the text boxes (like name) are anchored left and right and should stretch to fill the control, but don't. A: It just plain seems like the default control scaling just isn't working with the anchors. I don't know why, and can't explain it. But I did find a work around. See below code I added to the control. If you can provide an explanation, I would appreciate it. Private ChildControlScale As Double = 0 Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. ChildControlScale = txtAddress.Width / Me.Width End Sub Protected Overrides Sub ScaleControl(factor As System.Drawing.SizeF, specified As System.Windows.Forms.BoundsSpecified) MyBase.ScaleControl(factor, specified) If ChildControlScale <> 0 Then For Each ctrl As Control In Me.Controls ctrl.Width = Me.Width * ChildControlScale Next End If End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7570013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Subtract SQL DATETIME from datetime.now() in Python I have a DATETIME field in SQL. Its content is: 2012-08-26 13:00:00 I want to know how much time has passed from that date until now. In Python 2.7, it's easy: import time,datetime start = datetime.datetime.strptime('2012-08-26 13:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.datetime.now() delta = start - end print delta But I have a web server running Python 2.4. In Python 2.4 strptime is not in the datetime module. I can't figure out how to accomplish the same thing in 2.4. A: time.strptime is in Python 2.4. It returns a time tuple, which can be then converted to a datetime as shown below. start = time.strptime('2012-08-26 13:00:00', '%Y-%m-%d %H:%M:%S') start = datetime.datetime(*start[:6]) A: in python 2.4, the strptime() function is located in the time module.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Hibernate/JPA persistence.xml leads to SAXParseException when deploying to Jetty as WAR I'm having trouble getting an application running on Jetty. If I run the app using the maven jetty plugin i.e. mvn jetty:run It all runs fine. If I package the app as a war and try to deploy to a Jetty server manually I get the exception org.xml.sax.SAXParseException: cvc-complex-type.3.1: Value '2.0' of attribute 'version' of element 'persistence' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'. It I try and deploy to Jetty using mvn jetty:run-war I get the same error. The hibernate/JPA dependancies my app is using are <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.7.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.7.Final</version> <exclusions> <exclusion> <groupId>cglib</groupId> <artifactId>cglib</artifactId> </exclusion> <exclusion> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.1.0.Final</version> <exclusions> <exclusion> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> </exclusion> <exclusion> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency> I'm confused why it works when running with jetty:run and not when deployed as a war. I've tried various versions of both Jetty 7 and 8 with no luck. Thanks. Can anyone spot anything wrong with what I'm trying? EDIT: Heres the persistence.xml <?xml version="1.0" encoding="UTF-8" standalone="no"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/> <property name="hibernate.connection.charSet" value="UTF-8"/> </properties> </persistence-unit> </persistence> A: Do you have older (before JPA2 compatibility) version of hibernate in your classpath before 2.0 compatible libraries? It can also come via some dependency. A: If you're using maven and the open-jpa maven plugin, be aware to put in the correct version If your using this one <plugin> <groupId>org.apache.openjpa</groupId> <artifactId>openjpa-maven-plugin</artifactId> <version>2.2.0</version> <configuration> <includes>**/entities/*.class,**/entities/masterdata/*.class</includes> <excludes>**/entities/*Enum.class</excludes> <addDefaultConstructor>true</addDefaultConstructor> <enforcePropertyRestrictions>true</enforcePropertyRestrictions> </configuration> <executions> <execution> <id>enhancer</id> <phase>process-classes</phase> <goals> <goal>enhance</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.apache.openjpa</groupId> <artifactId>openjpa</artifactId> <!-- set the version to be the same as the level in your runtime --> <version>1.2.0</version> </dependency> </dependencies> this will lead to the version error. it should be: <plugin> <groupId>org.apache.openjpa</groupId> <artifactId>openjpa-maven-plugin</artifactId> <version>2.2.0</version> <configuration> <includes>**/entities/*.class,**/entities/masterdata/*.class</includes> <excludes>**/entities/*Enum.class</excludes> <addDefaultConstructor>true</addDefaultConstructor> <enforcePropertyRestrictions>true</enforcePropertyRestrictions> </configuration> <executions> <execution> <id>enhancer</id> <phase>process-classes</phase> <goals> <goal>enhance</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.apache.openjpa</groupId> <artifactId>openjpa</artifactId> <!-- set the version to be the same as the level in your runtime --> <version>2.2.0*</version> </dependency> </dependencies>
{ "language": "en", "url": "https://stackoverflow.com/questions/7570017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get a hold on a nested span How can I get a hold on the h2 span element? div#content div.view-content div.view-row-item h2 span { ... is not working... A: If you're using FireBug, you can right-click the span tag and 'copy css path' and that will give you the complete path to the element starting from 'html' A: You're missing an s in div.view-row-item, it should be: div#content div.view-content div.views-row-item h2 span { A: In your example you've missed an 's' you need: div#content div.view-content div.views-row-item h2 span viewS-row-item
{ "language": "en", "url": "https://stackoverflow.com/questions/7570021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Random select value in array and next apply to jQuery function I have this function that returns a random color, but I want to apply it to jQuery .animate() function. How can I do that? var colors = ["rgb(120,25,25)", "rgb(50,100,130)", "rgb(30,95,45)", "rgb(55,30,90)"]; function randomBackground() { return colors[Math.floor(Math.random() * messages.length)]; } $("#menu").animate({background: randomBackground()}); A: You could do: var colors = ["rgb(120,25,25)", "rgb(50,100,130)", "rgb(30,95,45)", "rgb(55,30,90)"]; function randomBackground() { return colors[Math.floor(Math.random() * colors.length)]; //use colors.length, not messages.length } var bgcolor = randomBackground(); $("#menu").animate({background: bgcolor }); A: sorry for you but if you read the jQuery documentation : All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable. that meens you cannot do the background color change using animate()
{ "language": "en", "url": "https://stackoverflow.com/questions/7570025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hibernate entity modification/deletion invalidates query cache involing same entity name? I read from some blogs that The timestamp cache keeps track of the last update timestamp for each table (this timestamp is updated for any table modification). If query caching is on, there is exactly one timestamp cache and it is utilized by all query cache instances. Any time the query cache is checked for a query, the timestamp cache is checked for all tables in the query. If the timestamp of the last update on a table is greater than the time the query results were cached, then the entry is removed and the lookup is a miss. Let's say I loaded entity using get() method and saved it by calling saveOrUpdate() (OR) I deleted the entity by calling delete(). In all these cases timestamp cache keeps track of the table that has been modified and let query cache invalidate it's any cached query results of those tables? Thank you! A: Yes, that's what is meant by the blog entry you pasted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ErrorException: Catchable Fatal Error: Object of class could not be converted to string - Caused by dropdown menu but why? I have the following code, which retrieves the page slugs from the database which are needed to then create a related sub page: $builder->add('subtocontentoptions', 'entity', array( 'class' => 'ShoutAdminBundle:Content', 'property' => 'slug', 'query_builder' => function($repository) { return $repository->createQueryBuilder('p') ->where('p.mainpage = :main') ->setParameter('main', '1') ->orderBy('p.created', 'ASC'); } )); The code works, as it displays a drop down menu of all the parent pages I have. However, when I go to save the data to the database, I am given the following error: ErrorException: Catchable Fatal Error: Object of class Shout\AdminBundle\Entity\Content could not be converted to string in C:\wamp\www\vendor\doctrine-dbal\lib\Doctrine\DBAL\Statement.php line 131 I have checked the contents of the Content entity file, and here is the variable being declared: /** * @var integer $subtocontentoptions * * @ORM\Column(name="SubToContentOptions", type="integer", nullable=false) */ private $subtocontentoptions; And lower down the Content entity file: /** * Set subtocontentoptions * * @param integer $subtocontentoptions */ public function setSubtocontentoptions($subtocontentoptions) { $this->subtocontentoptions = $subtocontentoptions; } /** * Get subtocontentoptions * * @return integer */ public function getSubtocontentoptions() { return $this->subtocontentoptions; } The rest of the code does work, once this drop down has been taken out. I'm not sure why the drop down is causing this error? Thanks A: Was having the same issue with a sf2/doctrine2 project, implementing the __toString method resolved this issue for me : public function __toString() { return strval($this->id); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Convert Excel macro to C#? I have an Excel file (.xlsm) with a macro in it. I want to upload this Excel file onto a server and have C# do it's work on it instead of the VBA macro. The macro looks pretty simple, but I do not understand it well enough to convert it to C#. Below is the macro code: Sub publishpages() 'calculate how many iterations x = 0 Sheets("pagegen").Select Range("n1").Select Range("n1").Copy numberOfPages = ActiveCell.Value 'step through and select each sample For x = 0 To numberOfPages Sheets("listsample").Select Range("A2").Select ActiveCell.Offset(x, 0).Range("A1").Select Selection.Copy Sheets("pagegen").Select Range("l1").Select ActiveSheet.Paste 'name folder and filename Sheets("pagegen").Select Range("ac2").Select Range("ac2").Copy foldername = ActiveCell.Value 'publish pages Range("d3:q80").Select Application.CutCopyMode = False Selection.Copy ActiveWorkbook.PublishObjects.Add(xlSourceRange, "C:\Temp\" & foldername, "pagegen", "$d$3:$q$80", xlHtmlStatic, "sampleweb11 current_22", "").Publish (True) Next x End Sub Because I plan to run this on a server, I am looking for a managed library so I do not have to install Office on the server. This is what I am looking at and it even has Linq support: http://epplus.codeplex.com Any idea on how to start this? A: Here's the refactored code: Option Explicit Sub publishpages() Dim x As Long, numberOfPages As Long Dim folderName As String numberOfPages = Sheets("pagegen").Range("n1").Value For x = 0 To numberOfPages Sheets("pagegen").Range("l1") = Sheets("listsample").Range("A2").Offset(x, 0).Range("A1") folderName = Sheets("pagegen").Range("ac2") ActiveWorkbook.PublishObjects.Add(xlSourceRange, "C:\Temp\" & folderName, "pagegen", "$d$3:$q$80", xlHtmlStatic, "sampleweb11 current_22", "").Publish (True) Next x End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7570038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Search into a database using a form with various options I have an .asp page and I am using VBscript. basically I have a database with country, partner type and phone columns. I know how to load these into a recordset and display them into an .asp page. I am using a dropdown for Partner Type and Country, and I am using a label for the phone. Now what I am trying to do is that when a user selects a partner type, the information related to that partner type will show. I really dont know from where to start :/ I am not askign for someone to do all this for me, but i need some tips or maybe online tutorials. Thanks A: As you pointed out it is not easy to answer because the question is so wide. I'll try to make a simplified code example and then you surely can fill in the remaining bits. <% dim country dim partnerType dim phone country = request("country") partnerType = request("partnerType") dim phone = request("phone") 'Get more information from database Set objConnect = Server.CreateObject("ADODB.Connection") objConnect.ConnectionTimeout = 580 objConnect.Open "myConnectionString" set objRS = Server.CreateObject("ADODB.Recordset") objRS .Open "select * from yourTable", objConnect, , , adCmdText while not objRS.EOF response.write "found record in database" loop %> <html> <body> <form id="myForm"> <label>Country</label><select name="country"><option value="se">Sweden</option></select> <label>PartnerType</label><select name="partnerType" onChange="PtypeChanged();"><option value="1">Reseller</option><option value="2">International</option></select> <input type="text" name="phone" value="" /> </form> <script> function PtypeChanged(){ document.getElementById("myForm").submit(); } </script> </body> </html> A: sounds like you're looking to create dependent dropdown lists. There's an example with a demo here: http://www.aspkey.net/aspkey/_articles/asp/showarticle.asp?id=100
{ "language": "en", "url": "https://stackoverflow.com/questions/7570041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing an array of strings from managed C# to unmanaged function using P-Invoke Is it possible to pass a string array from managed C# to an unmanaged function using P-Invoke? This works fine: [DllImport("LibraryName.dll")] private static extern void Function_Name(string message); While this: [DllImport("LibraryName.dll")] private static extern void Function_Name(string[] message); fails with Unhandled exception: System.NotSupportedException: NotSupportedException I have tried using MarshalAs with no luck ([MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)] String[] dataToLoadArr) Is it possible to pass string arrays this way? A: [DllImport(Library)] private static extern IntPtr clCreateProgramWithSource(Context context, cl_uint count, [In] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 1)] string[] strings, [In] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.SysUInt, SizeParamIndex = 1)] IntPtr[] lengths, out ErrorCode errcodeRet); public static Program CreateProgramWithSource(Context context, cl_uint count, string[] strings, IntPtr[] lengths, out ErrorCode errcodeRet) This works fine in my OpenCL library, OpenCL.NET (http://openclnet.codeplex.com/SourceControl/changeset/view/94246#1251571). Note that I am passing in the count using SizeParamIndex as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Mysql Query is searching for column name instead of value What's wrong with this query? SELECT `category`, ( SELECT `name` FROM `city_names` WHERE `city_code`=`units`.`city_code` )as `cityName`, `email` FROM `units` WHERE ( SELECT COUNT(*) FROM `pesquisaRH` WHERE `unit_code` = `units`.`unit_code` )=0 AND ( (`category` LIKE `%central%`) OR (`category` LIKE `%DPM%`) OR (`category` LIKE `%DPC%`) OR (`category` LIKE `%DIC%`) ) It returns me this error: #1054 - Coluna '%central%' desconhecida em 'where clause' It seems to be searching for the patterns in the column name instead of its value. I want to find the units that didn't answer a questionary (the ondes that count 0 when searching the "pesquisaRH" table) AND have one of the four specifyed patterns in their category names (%central%, %DPM%, %DPC% or %DIC%); and then, return their category, the name of the city they're located and their email. A: `%central%` should be '%central%' `%DPM%` should be '%DPM%' ... and so on. You're using the wrong kind of quote!
{ "language": "en", "url": "https://stackoverflow.com/questions/7570046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generic mapper instead of having numerous individual mappers I am using ASP.NET MVC 3 with Razor and Autofac for dependency injection. I am thinking of creating a generic mapper. Currently I am using AutoMapper for the mapping between my domain and view model. It can be any mapping framework, but I am using AutoMapper . Here is my IMapper interface: public interface IMapper { object Map(object source, Type sourceType, Type destinationType); } I then have an IBankMapper interface that implements this IMapper interface. The reason why I did it like this is because I can have many different mappers. Using dependency injection I can know what instance I can inject. So for IBankMapper I will inject BankMapper, ICategoryMapper I will inject CategoryMapper. IBankMapper interface: public interface IBankMapper : IMapper { } BankMapper class: public class BankMapper : IBankMapper { static BankMapper() { Mapper.CreateMap<Bank, EditBankViewModel>(); Mapper.CreateMap<EditBankViewModel, Bank>(); } public object Map(object source, Type sourceType, Type destinationType) { return Mapper.Map(source, sourceType, destinationType); } } As the program grows so will the mapper classes. Is there a way that I can create a generic mapper, one that can be used in the whole application? Is this possible? A: There is absolutely no need for you to create any mapper classes at all. All you need to do is be sure that you call Mapper.CreateMap at the beginning of your application. You can then use Mapper.Map to do your mapping. Typically, I create a static class with a single method to handle the creation of my Maps. It looks something like: public static class Transformers { public static void Register() { Mapper.CreateMap<Bank, EditBankViewModel>(); Mapper.CreateMap<EditBankViewModel, Bank>(); Mapper.CreateMap<Account, EditAccountViewModel>(); Mapper.CreateMap<EditAccountViewModel, Account>(); // And so on. You can break them up into private methods // if you have too many. } } I then call that method inside Global.asax do ensure that it runs when necessary. In any other spot in my application, I'm free to call Mapper.Map for any of the configured mappings: protected void Application_Start() { Transformers.Register(); } A: It looks like you are creating these interfaces to be able to mock AutoMapper in your unit tests. You can simply use IMappingEngine from AutoMapper for this purpose. Your classes would have a dependency on IMappingEngine which would be injected. IMappingEngine has the same methods as the static class Mapper to map your objects. In your composition root you would configure the mapper and register the mapping engine with the DI container. Something like this: // composition root: Mapper.CreateMap<Bank, EditBankViewModel>(); Mapper.CreateMap<EditBankViewModel, Bank>(); builder.Register(Mapper.Engine); // your classes: class YourClass { public YourClass(IMappingEngine mappingEngine) { } } A: As Daniel said, Automapper is already a generic mapper. If you're worried about the direct dependency to automapper in your code, you can hide it behind a little facade, e.g.: public interface IMapper { TDestination Map<TSource, TDestination>(TSource source); } public class MyMapper :IMapper { public TDestination Map<TSource, TDestination>(TSource source) { AutoMapper.Mapper.CreateMap<TSource, TDestination>(); return AutoMapper.Mapper.Map<TSource, TDestination>(source); } } This can also help you to model the mapper as an injectable dependency
{ "language": "en", "url": "https://stackoverflow.com/questions/7570047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Initializing several ivars of the same type with same object? So, this is pretty standard memory management, from what I understand: ClassName *temp=[[ClassName alloc] init]; self.ivar=temp; [temp release]; This is to avoid the memory leak created by just doing this: self.ivar=[[ClassName alloc] init]; Cool. But, suppose I have several ivars that are based ClassName? Is this okay: ClassName *temp=[[ClassName alloc] init]; self.ivar=temp; self.othervar=temp; self.anothervar=temp; [temp release]; Would they all be manipulating the same object, ultimately, even though I want them to have different instances of ClassName? I assume that the outcome of this might depend on if the ivars were created as retain vs copy? Suppose they are set to retain, would this be okay? A: Would they all be manipulating the same object, ultimately, even though I want them to have different instances of ClassName? the default expectation is "yes, they would reference the same object because this is a reference counted system." I assume that the outcome of this might depend on if the ivars were created as retain vs copy? not might, but entirely. if the property is declared copy and the type adopts NSCopying, that should be all that is needed. if you implement the setters (what are often synthesized properties) yourself, you must copy in your implementations. Suppose they are set to retain, would this be okay? then they would all refer to the same instance. whether that is the correct semantic for your program depends on how you need it to behave. in this example, you stated "I want them to have different instances of ClassName" so you would either need to create an unique instance for every destination (either directly or via copy, if ClassName adopts NSCopying). A: If the properties are all retain then you will be storing the same instance three times, as you assume. If you want different instances, and you want to use retain, then you need to create three different instances. copy will create a copy, but then it will do this every time you set anything to the property, which may not be your desired behaviour. A: In your example all objects will point/manipulate same object instance unless they are copy/mutableCopy or any other type that conforms to NSCopying protocol. retain will have no affect other than incrementing retainCount of an already allocated object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Help with Selenium Webdriver download? I have Selenium IDE and i want to install Selenium Webdriver. 1) Can anyone tell me where can i download selenium webdriver. i don't see any link available in the documentation. 2)Can i use selenium webdriver with PHPUnit? I see some materials saying php is not supported in selenium 2 however there are some download links available for phpbindings for webdriver what is this exactly? 3)If i have Selenium webdriver do i still need selenium server to run test cases in different browsers? I would appreciate your answers... A: I completely agree with you. They have a ton of documentation, but they do a horrible job of explaining what you actually need. It took me about 2 days to put all the pieces together. You will need a few things... If you are running tests with C#, download NUnit, C# client drivers. Create a class library project in Visual Studio and reference the dlls (assemblies) for NUnit (for appropriate dotnet version) and the C# client drivers. Compile your class library. It should create a dll inside of the bin\Debug directory. Then go into NUnit, create a project, and then open your assembly in that bin\Debug directory. That should get you started. If you're developing using Java, download JUnit (not NUnit) and then download the Java Client Drivers, and use Eclipse instead of Visual Studio. You can launch JUnit right from Eclipse. I've only tried NUnit and JUnit before. But I'm sure PHPUnit can also be launched from Eclipse (educated guess). There seems to be the most documentation for Java and Python.. from experience, but I've been doing everything in .NET and I haven't had anything I couldn't solve. The Unit Testing software isn't required, but the code the format add-ins for Firefox Selenium IDE will build the code for NUnit (C#) or JUnit (Java), etc... so most use those tools. If you want to get some boilerplate code, go into Selenium IDE and turn on experimental features under options. Then export your C# code (or Java code) from the format menu after you've recorded your commands. It won't all convert 100%, so be aware of that. Just google from there to get questions answered. One thing to watch out for... clickAndWait commands won't convert to click and wait in the code. You will either need to do an implicit wait or a thread.sleep wait after certain commands before you'll be able to access the next element if you're waiting for an action to occur. You will also want to turn on native events so you can fire certain JavaScript events. Your fire events won't work if the driver doesn't have this turned on. The WebDriver driver. If you have any other questions, let me know. A: You can download Selenium server as well as client driver from the following: http://code.google.com/p/selenium/downloads/list You can download "php-webdriver-bindings-0.9.0.zip" from the following source: http://code.google.com/p/php-webdriver-bindings/downloads/detail?name=php-webdriver-bindings-0.9.0.zip A: In C# context: Now the better way of including packages in C# project is using nuGet. nuGet is packaging utility which when executed from its powershell command window, quickly downloads the dll files and links them to project. Below link details on how to use nUGet to install packages of selenium webdriver, selenium support and nUnit. How to invoke/run different type of web driver browser using remote webdriver in C#
{ "language": "en", "url": "https://stackoverflow.com/questions/7570054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to rotate view to landscape mode in block-based animation My application contains a Tab Bar Controller and Navigation controller. Its totally in Portrait mode. Now I have a table view in 2nd tab, clicking on each row of table view will push another view controller which will show a graphical chart, now I want this chart to be in landscape mode where as the rest of application is in portrait mode. I came to know that we have to rotate the view on our own, now my question is how to rotate this new view in landscape mode. I put some UIView animations in viewWillAppear function, but I want the block-based animation to rotate this view to landscape for me and when I go back it rotate back portrait mode. Thanks in advance ! A: Check the device orientation and make the rotation depends on it: [UIView animateWithDuration:0.5f animations:^{ myView.transform = CGAffineTransformMakeRotation(-M_PI * 0.5); } ];
{ "language": "en", "url": "https://stackoverflow.com/questions/7570055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Servlet and serial port We need to develop centralized device management based on java. So Could you tell me how to write servlet to read serial port from client with usb token? A: Not easily. In order to access resources on the client outside of the protected "sandbox" in the browser you will have to do it using a signed applet that communicates with the serial port and then back to the server (through some servlet interface like a web-service, for instance) Alternatively, you can write a "real" client application that you would have to distribute and run on the client machine. This application would, in turn, communicate with the serial port and with the server through some communication method. This could also be a servlet-based communication like a web-service. Point is, this has very little to do with servlets as a servlet executes on the server and has nothing to do with the client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recover unconnected tables from ibdata1 I'm encountering data loss of mysql, below is the steps: 1.I converted Table_A from MyISAM to InnoDB (with innodb_file_per_table OFF), saw the ibdata1 size increased; 2.Turned ON innodb_file_per_table; 3.Converted Table_A to MyISAM back, ibdata1 didn't shrink; 4.Converted Table_A to InnoDB, got Table_A.ibd file; Now I lost the Table_A.ibd file, and want to find data back from the ibdata1 file. I turn OFF innodb_file_per_table and tried to create the same Table_A with InnoDB format, it fails, and tell me that TABLE_A already exists, and I can't find the table from the schema. I've searched whole internet and didn't find anything helpful, please help! A: Goodle Percona data recovery toolkit. You need to: * *Split ibdata1 into pages (page_parser) *Fetch records from InnoDB dictionary - tables SYS_TABLES and SYS_INDEXES *Find index_id of your table from SYS_* tables *Fetch records from pages with index_id of your table (constraints_parser tool). UPDATE: Data recovery toolkit moved to GitHub
{ "language": "en", "url": "https://stackoverflow.com/questions/7570064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# code to execute code in another application domain? I have a program that executes for 24 hours, then restarts. How can I shift main() from into a separate application domain, which is torn down and refreshed every 24 hours, in order to completely eliminate any potential memory leaks? A: I've created a class that allows you to execute code in a separate application domain which would allow you to dispose the application domain and recreate it: Executing Code in a Separate Application Domain Using C# A: You had me right up until you said: in order to completely eliminate any potential memory leaks? If you want to run code in another app domain then there are plenty of resources on how to do this, for example Executing Code in Another Application Domain (C# and Visual Basic). The basic principle is to create a class that inherits from MarshalByRefObject. You then create your new app domain and instruct it to create an instance of that object - this object is then your "entry point" into your app domain: AppDomain newAppDomain = AppDomain.CreateDomain("NewApplicationDomain"); ProxyObject proxy = (ProxyObject)newAppDomain.CreateInstanceAndUnwrap("MyAssembly", "MyNamespace.MyProxy"); However in C# there isn't really any such thing as a "memory leak", at best you just have objects which are inadvertantly kept in scope. If this is the case then an app domain is just overkill - all you really need to do is remove references to managed objects that are no longer needed and the Garbage Collector will tidy them up for you. If you have a true memory leak in unmanaged code an app domain won't help you either. Unmanaged types aren't bounded by app domains and so any unmanaged memory allocated "inside" the app domain won't be freed when the app domain is destroyed. In this case you would be better off using separate processes instead. A: You can't. A process is isolated and independent and you can't transfer a thread from one process into another process. What you could do, however, if you absolutely can't fix the memory leaks internally, is create a watchdog program which launches the app whenever it stops running, and set up your app to only be run in single execution mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: In C#, how can I access an object's objects when bracket notation doesn't work? I have an object of objects, and I'm not sure how to access the values. Here's a picture from the VS debugger: the object in question is bounds. I'd like to get the value 7, 14, 157 and 174 like so: bounds[0] //Should equal 7 bounds[3] //Should equal 174 Obviously this won't work because it's not an array but an object of objects. Could you explain the correct way to access the numeric values nested inside the bounds object? Thank you! A: You need to cast bounds from object to object[], get the value from the array, then cast it to double. object[] array = (object[])bounds; object value = array[0]; double number = (double)value; or one line double value = (double)((object[])bounds)[0]; If you put your numbers in an array of double in the first place, then you can avoid all the casting. double[] bounds = new double[x]; ... populate array double value = bounds[0]; Also, "bracket notation" is know as indexers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Magento - Upload file during registration I want every user, that registers on my Magento instance, to upload a certificate that shows me that he registered a business. I already added the fields in the template. But how can I fetch the file and save the filename / contents in the customer record? Is there a way to extend the functionality in the Controllers? A: This is actually even easier: Just make sure you set these parameters on your config.xml: 'attributes' => array( 'prooffile' => array( 'type' => 'text', 'input' => 'file', 'label' => 'Proof file', 'visible' => true, 'required' => false, 'position' => 100, "user_defined" => false, ), This adds a nice editor in your admin backend. A: The way I did this: I added the file field to the registration form: <li class="fields"> <div class="field"> <div class="input-box"> <label for="prooffile"><?php echo $this->__('Proof of business registration') ?><span class="required">*</span></label><br /> <input type="file" name="prooffile" id="prooffile" title="<?php echo $this->__('Proof of business registration') ?>" class="required-entry input-text" /> </div> </div> </li> Also, make sure that you set the form enctype to "multipart/form-data". After that, I created a class that subscribes to the "user-register-success" Event. Magento has a very solid Event/Observer mechanism built in. To do this, you have to have a custom module. In the modules etc/config.xml, add these lines for the event listener: <events> <customer_register_success> <!-- The name of the Event --> <observers> <customfields> <!-- Your module name --> <type>singleton</type> <class>customfields/observer</class> <!-- The class name, that holds your callback function --> <method>handle_file_upload</method> </customfields> </observers> </customer_register_success> </events> This registers an event handler for the event customer_register_success. Make sure that you create a file Observer.php in your modules Model folder: Model/Observer.php: <?php class Komola_Customfields_Model_Observer { public function __construct() { } public function handle_file_upload($observer) { $customer = $observer->getCustomer(); if (isset($_FILES['prooffile']['name']) && $_FILES['prooffile']['name'] != "") { $uploader = new Varien_File_Uploader("prooffile"); $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png', 'pdf')); $uploader->setAllowRenameFiles(false); $uploader->setFilesDispersion(false); $path = Mage::getBaseDir("media") . DS . "customer" . DS; $logoName = $customer->getId() . "." . pathinfo($_FILES['prooffile']['name'], PATHINFO_EXTENSION); $uploader->save($path, $logoName); $customer->setProoffile($logoName); $customer->save(); } } } This takes the uploaded file, and saves the file in the folder media/customer (make sure to create this folder and to make it writable!). It also saves the file name in a custom customer attribute. A: In the module installer file, create the attribute like this, and it will appear in the customer backend. An extra part is needed for newer version of Magento (not sure from when exactly, but it is true as of Magento Community Edition 1.6 and up). The "used_in_forms" key cannot be in the array passed to the addAttribute call directly (won't work). It probably contain the names of the forms from which the customer model will accept the values and not ignore them when being saved. Known values are at this question's answers: Can no longer add registration fields in Magento 1.4.2.0 (The answer by Folker Schellenberg) I think it is the name of the controller and action that rendered the form. This name is also the main layout handle name of the page (eg: customer_account_edit). It should be noted that the customer form in the front-end is HTML-based. It doesn't dynamically render inputs from the attributes like the backend forms. This means that if these attributes should be input by the user, the template needs to be amended to contain the proper input tags as well (and the proper value added in the used_in_forms array). $attributeCode = "uploaded_file"; $attributeLabel = "Uploaded file"; $installer->addAttribute('customer', $attributeCode, array( 'type' => 'text', 'input' => 'file', 'label' => $attributeLabel, 'global' => true, 'visible' => true, 'required' => false, 'user_defined' => false )); // For newer versions of Magento, otherwise won't show up. $eavConfig = Mage::getSingleton('eav/config'); $attribute = $eavConfig->getAttribute('customer', $attributeCode); $attribute->setData('used_in_forms', array('customer_account_create', 'adminhtml_customer')); $attribute->setData('sort_order', 200); $attribute->save(); Another possible type is 'image' which renders exactly as 'file' except it shows the image in a preview box (a small one). Maybe good for customer photo ? Also, noteworthy is that is this specific for the customer form (the class that handles this type of attribute is: Mage_Adminhtml_Block_Customer_Form_Element_File and Mage_Adminhtml_Block_Customer_Form_Element_Image), so this won't work in a product attribute without custom work. Hope this helps !
{ "language": "en", "url": "https://stackoverflow.com/questions/7570078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the alternative to putting UIWebView inside UIScrollView I have gotten UIWebView inside UIScrollView to work, so far anyways, and I have just seen mention on Apple's site that doing so is not advised. So OK, what's the alternative? I need to display web pages, and I need them to be scrollable, such that if the user swipes leftward then an entirely different page appears coming in from the right. And a reverse situation with swiping rightward. How is that done without putting UIWebView inside UIScrollView? Thanks. A: Well, you need the UIWebView, which has indeed many features of a UIScrollView, to be able to scroll not only up and down, but also to left and right. Also, scrolling with two fingers is a no-go, for scrollable elements within a web page, such as textareas can only be scrolled with two fingers. Three fingers is also not so good because that's not convenient for people with thick fingers... So my suggestion is that you add a UIGestureRecognizer to your UIWebView and look out for a swipe gesture. Then handle the switching of pages accordingly with animations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Replace Text Inside Tag with No Attributes I'm looking to replace the text inside a <nobr> but I can't figure out how. It would be easy if I could do: $('nobr:contains("Due")').replace('Due Date'); but there's another <nobr> that has the word "Due" in it and I don't want that affected. What's the simplest way to find the <nobr> that's exactly equal to "Due" and replace it with "Due Date"? A: You could filter all the nobr elements to eliminate any whose text is not equal to "Due": $("nobr").filter(function() { return $(this).text() === "Due"; }).text("Due Date"); Here's a working example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is my AJAX content already crawlable? I have build a site based on Ajax navigation. I have build it that way, that whenever someone without javascript visits my site, the nav links, which usually load content via Ajax, are acting like normal links and the user can browse through the pages as usual. Since, Google bot doesn't run javascript, it should theoretically be able to go through all links and corresponding sites as usual, right? Since they are valid links with the href tag pointed to the corresponding site. Now I was wondering if thats sufficient or if I need to implant this method from Google too to make sure Google sees all my content? Thanks for your insights and excuse my poor English! A: If you can navigate your site by showing source (ctrl-u in chrome), google can also crawl your site. Yes, its that simple
{ "language": "en", "url": "https://stackoverflow.com/questions/7570083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove the strange border from shadow in Firefox? See this fiddle in Firefox http://jsfiddle.net/qwbpZ/4/ On hover you will see this grey line It's fine in Google Chrome but this grey border is appearing in other browsers. How can I solve this? CSS a, a:visited {color:#fff} .btn { display: inline-block; -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; -webkit-box-shadow: 0 9px 0 #000000, 0 13px 0 rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 9px 0 #000000, 0 13px 0 rgba(0, 0, 0, 0.1); box-shadow: 0 9px 0 #000000, 0 13px 0 rgba(0, 0, 0, 0.1); -webkit-transition: -webkit-box-shadow .2s ease-in-out; -moz-transition: -moz-box-shadow .2s ease-in-out; -o-transition: -o-box-shadow .2s ease-in-out; transition: box-shadow .2s ease-in-out; padding: 0px; background: black; /* see ? */ } .btn span { display: inline-block; padding: 22px 22px 11px; font-family: Arial, sans-serif; line-height: 1; text-shadow: 0 -1px 1px rgba(19,65,88,.8); background: #2e2e2e; -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; -webkit-box-shadow: inset 0 -1px 1px rgba(255,255,255,.15); -moz-box-shadow: inset 0 -1px 1px rgba(255,255,255,.15); box-shadow: inset 0 -1px 1px rgba(255,255,255,.15); -webkit-transition: -webkit-transform .2s ease-in-out; -moz-transition: -moz-transform .2s ease-in-out; -o-transition: -o-transform .2s ease-in-out; transition: transform .2s ease-in-out; color: #FFF; font-size: 32px; border: 0 } .btn:hover { -webkit-box-shadow: 0 8px 0 #000, 0 12px 10px rgba(0,0,0,.3); -moz-box-shadow: 0 8px 0 #000, 0 12px 10px rgba(0,0,0,.3); box-shadow: 0 8px 0 #000, 0 12px 10px rgba(0,0,0,.3); } .btn:hover span { -webkit-transform: translate(0, -4px); -moz-transform: translate(0, -4px); -o-transform: translate(0, -4px); transform: translate(0, -4px); } .btn:active { -webkit-box-shadow: 0 8px 0 #000, 0 12px 10px rgba(0,0,0,.3); -moz-box-shadow: 0 8px 0 #000, 0 12px 10px rgba(0,0,0,.3); box-shadow: 0 8px 0 #000, 0 12px 10px rgba(0,0,0,.3); -webkit-transition: -webkit-box-shadow .2s ease-in-out; -moz-transition: -moz-box-shadow .2s ease-in-out; -o-transition: -o-box-shadow .2s ease-in-out; transition: box-shadow .2s ease-in-out; } .btn:active span { -webkit-transform: translate(0, 0px); -moz-transform: translate(0, 0px); -o-transform: translate(0, 0px); transform: translate(0, 0px); } A: It seems, that there is no perfect solution: this antiialiased pixels between shadow and border-radius are sticky as hell. So, I came up with the following two solutions: * *Use an extra pseudo-element, that would underlay the problem place: http://jsfiddle.net/kizu/qwbpZ/5/ *Add more extra black shadows (normal and inset): http://jsfiddle.net/kizu/qwbpZ/6/ — I've added here two, but there are still some pixels visible, if you'd add another two it'd be almost ok. Sad, but these are not universal solutions and I couldn't find a proper way to fix the bug itself. A: try this: -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; A: Quick fix: apply bottom and sides 1px black border to button. Fixed button: http://jsfiddle.net/FJGeZ/2/ Notice box-shadow y-axis distance is less by 1px to compensate 1px bottom border, plus inner span with negative margins to overlap parent border. Isolated bug here: http://jsfiddle.net/AkZE6/
{ "language": "en", "url": "https://stackoverflow.com/questions/7570089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: ASP.NET MVC view state Can anyone explain me how view state is handled in ASP.NET MVC 3. I know that in MVC view state is not there. But just wanted to know how exactly is the data handled from one page to another page. For eg.: I have two view in my classes "Create" -> creates a new person and "Index" -> displays the list of person in "Person" modal. So when I create a new peson using HttPost and then in this post method i go to index view. So here how the data is been handled as View state is not there. Please help me out. Thansk in advance!!!! A: When you click submit the data is pushed into the form object of the request just like any other normal form submit. It looks for a matching action to handle the request, and finds the one with your person model. It invokes the default data model binder, which attempts to match up form data to object properties. The action is invoked with the result of the model binder. I would strongly suggest picking up a good book on the subject, also please review your existing questions and consider accepting any correct provided answers. A: In Post or Get Request Every input object like textbox that is in the Form tag, post or get to the action in controller that specified in action attribute in form tag like action="demo_form: <form action="controller/actionName" method="get"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> <input type="submit" value="Submit"> </form> the name of property is name of your input name and the value of property is text that you typed in the input .in controller you have specified an action like "actionName" that has input object that this object have property name like your input name in the view.mvc maps property value of request to the same property name of object in your action input parameter
{ "language": "en", "url": "https://stackoverflow.com/questions/7570098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Manage static Resources in spring mvc I am building an application with Spring MVC and jquery for UI. The UI developer is designing the pages using jQuery without using any server (as it is not required). The pages are integrated by developers in the application. The issue here is that the UI designer is using relative directory path and to integrate these pages, paths need to be prefixed with spring resource path. Even the JS and CSS files are referring to images with relative directory path. Every time the UI is update same process is repeated for integration. What I want to know is there any better approach in this case so that * *the relative path used by ui developer doesn't needs to be changed every time for integration. *The spring static resource loading can still be used. <mvc:resources mapping="/res/**" location="/resources/" /> *The path reference in any js or css file can also work without any changes in it. I do not want to do anything which tightly couple it with a server. Please help. A: lookup util:constant in the spring documentation and see if that is helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to do single-sign-on (SSO) between two web apps, PHP and Java EE? I have an existing Java EE web application running on GlassFish 3.1. Sign in works fine through the jdbcRealm configured in GlassFish 3.1. Someone on another team is developing a separate web application in PHP, the boss doesn't want the user of the apps to have to sign in twice. That is, when they are signed in to the Java web app and they click a link that takes them to the PHP app, they should already be signed in to that app as well. (And vice-versa.) Not sure how to implement this. I was thinking that I could generate a long random key (a token) that gets generated on log in of either app, and passed around in every web request for either app to identify a logged in user, but that doesn't seem safe. I need pointers in the right direction. A: You said I was thinking that I could generate a long random key (a token) that gets generated on log in of either app, and passed around in every web request for either app to identify a logged in user, but that doesn't seem safe. But that's essentially how sessions work. Your best bet is to generate a unique login identifier (as you said) store it in a database or memory cache accessible by both apps and find a way to save it such that both web apps can retrieve it. If both apps are on same root domain, you can use a cookie with path set to / so both apps can access it. If both apps are going to be on different root domain then it will be a little more tricky. As for security regarding the identifier token being passed around, you could regenerate the identifier on each request, which guards against cookie jacking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Dynamic modal height with SimpleModal I'm using SimpleModal to display a modal whose height needs to change in response to a dropdown list change in the modal that repopulates a portion of a dialog. The problem I'm running into is that SimpleModal doesn't resize the height of the modal when the selection changes. I've seen other posts on SO related to this but none of them seem to have a conclusive answer or are not directly related to my scenario (we're supporting IE 7 and 8). Any guidance on this would be most appreciated! A: This will help: $.modal(data, { minWidth: 400, onShow: function(dialog){ //изменение размеров контейнера по размеру контена dialog.container.css({"height":"auto","width":"auto"}); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7570102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use System::Net::Mail in console application How i can use this >> System::Net::Mail; namespace in c++ console application? Maybe im asking fool question but im new in cpp please help A: see msdn static void CreateTestMessage2( String^ server ) { String^ to = L"jane@contoso.com"; String^ from = L"ben@contoso.com"; MailMessage^ message = gcnew MailMessage( from,to ); message->Subject = L"Using the new SMTP client."; message->Body = L"Using this new feature, you can send an e-mail message from an application very easily."; SmtpClient^ client = gcnew SmtpClient( server ); // Credentials are necessary if the server requires the client // to authenticate before it will send e-mail on the client's behalf. client->UseDefaultCredentials = true; client->Send( message ); client->~SmtpClient(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Apache Logs: Count top 10 URLs by bytes served I have an Apache log format file. Example string: fj5020.inktomisearch.com - - [01/Oct/2006:06:35:59 -0700] "GET /example/When/200x/2005/04/27/A380 HTTP/1.0" 200 4776 "-" "Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)" where 4776 is served page size in bytes. I'd like to output top 10 URLs by served traffic. I'm stuck with the problem of summing all sizes of each unique page (the size of a page can also be variable). Any ideas how to do it in Bash or/and AWK? A: does this work for you? awk '{a[$7]+=$10}END{for(x in a)print x, a[x]}' yourLogfile|sort -r -n -k2|head -n10 A: Lots of ways to do it. Here's one. total=0 last_site= while read site size ; do if [ "$site" != "$last_site" ] ; then [ ! -z "$last_site" ] && printf '%s %d\n' "$last_site" $total total=0 last_site="$site" fi let total+=$size done < <(awk '{print $1, $10}' log | sort) printf '%s %d\n' "$last_site" $total
{ "language": "en", "url": "https://stackoverflow.com/questions/7570112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why isn't my tests working for this form? In Firefox, if I try to submit a post without a title, I get: 1 error prohibited this post from being saved. But when I run my test. It's a different story. My Post model has validates_presence_of :title. My test looks like: require 'spec_helper' describe 'Users' do it 'registered users should not be able to post without a title', :js => true do user = Factory(:user) visit new_post_path current_path.should eq(new_post_path) fill_in 'post[markdown_description]', :with => 'Bar' click_on 'Submit your post' page.should have_content('error') end end By the way, I am using Selenium (:js => true), because my submit button is actually an anchor link with some JS. Basically, when the link is clicked, JS triggers the form to be submitted. Rspec returns: Running: spec/requests/users_spec.rb F Failures: 1) Users registered users should be able to post Failure/Error: page.should have_content('error') expected there to be content "error" in "" # ./spec/requests/users_spec.rb:13:in `block (2 levels) in <top (required)>' Finished in 7.9 seconds 1 example, 1 failure Failed examples: rspec ./spec/requests/users_spec.rb:4 # Users registered users should be able to post A: The request may not make it to the controller action if you have before_filters. Check the log to make sure that the correct parameters are posting and that the action is not redirecting. Another option is to include this in your spec: click_on 'Submit your post' save_and_open_page which opens the current page in the browser so you can see what is actually being rendered.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why do I need to define custom constructor? If I have a class, let's say, extended from DialogFragment and define custom constructor for it, why should I define a default one? If I wouldn't I get the error message if runtime change occurs. A: I suspect the problem is that in Java, the compiler creates a parameterless constructor for you unless you specify one yourself. If something within Android requires a parameterless constructor, then either you need to not declare any constructors yourself or you need to explicitly declare a parameterless one. From section 8.8.9 of the Java Language Spec: If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided: * *If the class being declared is the primordial class Object, then the default constructor has an empty body. *Otherwise, the default constructor takes no parameters and simply invokes the superclass constructor with no arguments. Does that make things clear? I don't know enough about Android to know why you need a parameterless constructor, but presumably it's so that instances can be created via reflection without specifying any arguments for constructor parameters. A: Constructors may contain code that is run when the object is created. It is sort of like setup code that you want done so the object is ready for what it's supposed to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Putting image tags into php Hello im using page nation which is amazing but now im trying to print off there avaratar im using this code echo "<IMG SRC=\"$list['avatar']\" WIDTH=\"268\" HEIGHT=\"176\" BORDER=\"0\" ALT=\"\" \/>";; but im getting this error Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in test.php on line 64 A: Try echo "<IMG SRC=\"".$list['avatar']."\" WIDTH=\"268\" HEIGHT=\"176\" BORDER=\"0\" ALT=\"\" />"; instead, or you could use this one, too echo "<IMG SRC=\"{$list['avatar']}\" WIDTH=\"268\" HEIGHT=\"176\" BORDER=\"0\" ALT=\"\" />"; or better and readable ones: echo '<IMG SRC="'.$list['avatar'].'" WIDTH="268" HEIGHT="176" BORDER="0" ALT="" />'; echo '<IMG SRC="', $list['avatar'], '" WIDTH="268" HEIGHT="176" BORDER="0" ALT="" />'; A: I prefer this echo "<IMG SRC=\"$list[avatar]\" WIDTH=\"268\" HEIGHT=\"176\" BORDER=\"0\" ALT=\"\" />"; eliminate de braces surrounding the variable and the single quotes for the array key A: Try changing it to: echo "<IMG SRC=\"{$list['avatar']}\" WIDTH=\"268\" HEIGHT=\"176\" BORDER=\"0\" ALT=\"\" />"; ...or, less confusingly: echo '<IMG SRC="'.$list['avatar'].'" WIDTH="268" HEIGHT="176" BORDER="0" ALT="" />'; A: this should work : echo '<IMG SRC="'.$list['avatar'].'" WIDTH="268" HEIGHT="176" BORDER="0" ALT="" />'; A: to avoid all thet mess ?><IMG SRC="<?=$list['avatar']?> " WIDTH="268" HEIGHT="176" BORDER="0" ALT="" /><?php and don't post your usual "parse error" comment here. but check your other PHP syntax issue somewhere else A: Try it like this: echo '<IMG SRC="'.$list['avatar'].'" WIDTH="268" HEIGHT="176" BORDER="0" ALT="" />';
{ "language": "en", "url": "https://stackoverflow.com/questions/7570121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to omit some objects from the index with Hibernate Search? We want to enable fulltext search on a Hibernate database for only some objectes of a specific entity. Is there a way to prevent hibernate search from indexing some instances of this entity? We do not want to filter the search results, we just want some instances to not be indexed at all. An example: We have a database with employees, both active and retired. We don't need to be able to search retired employees. We're a very old IT company, founded in 1695, therefor we have about 2 million retired employees that we are very fond of, but don't want to index, only the 10 active ones. Is there a way we can tell Hibernate Search to only index employees where retired = false? Regards, Jochen A: You'll need a PreUpdateEventListener, in this listener inspect the entity and determine if you want to add it to the lucene index. This code not guaranteed to work, but hopefully you'll get the idea. public class LuceneUpdateListener implements PreUpdateEventListener { protected FSDirectory directory; // = path to lucene index public boolean onPreUpdate(PreUpdateEvent event) { if (event.getEntity() instanceof Employee ) { try { Employee employee = (Employee) event.getEntity(); //Remove on update remove((Employee) event.getEntity(), (Long) event.getId(), directory); //Add it back if this instance should be indexed try { if (employee.shouldBeIndexed()) { add((Employee) event.getEntity(), (Long) event.getId(), directory); } } catch (Exception e) { } } catch (Exception e) { throw new CallbackException(e.getMessage()); } } } return false; } protected synchronized void add(Employee employee, Id employeeId, FSDirectory directory) { try{ IndexWriter writer = new IndexWriter(directory, new StandardAnalyzer(), false); Document d = LuceneDocumentFactory.makeDocument(employee); writer.addDocument(d); writer.close(); directory.close(); } catch(Exception e) { } } protected synchronized void remove(Long id, FSDirectory directory) throws IOException { try { IndexReader ir = IndexReader.open(directory); ir.deleteDocuments(new Term("id", id.toString())); ir.close(); } catch(Exception e) { } } public FSDirectory getDirectory() { return directory; } public void setDirectory(FSDirectory directory) { this.directory = directory; } } In order to index these objects outside of a hibernate event you can extract the logic out of this class, and process your employees in batch. Also don't forget to register your listener. A: I don't think that you should work with the IndexReader directly in your event listener. You should instead extend (or write a new version) of the existing FullTextIndexEventListener and inspect your entity in the callback method and depending on the retired field call or not call processWork. If you want to use Hibernate Search 4 (together with Hibernate Core 4) you will also need a custom HibernateSearchIntegrator. This solution will work, but should be considered an interim solution until HSEARCH-471 is implemented.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: parent object specific layouts I'm developing a rails app with a model consisting of items that belong to companies. There are multiple users for this system and I want any user who logs in and looks for a specific item (belonging to a company) to see the company logo and letter head etc. as background. i.e. each item knows his layout via the company parent object association, item belongs_to company What do you suggest is the best and most elegant approach for modeling this in rails? Cheers, A: How customizable do you want the layouts? At the high end, I suggest using the Liquid template library. It enables you and your integrators to safely change any aspect of the layout on a per company basis. Flow: If the company has a liquid template stored in your system, then use it. Otherwise use a default template. The other ways of doing things where you enable individual uploads of logo, letter head, plus css (to enable the right fonts for the company), etc etc, quickly becomes limiting. Sooner rather than later, a company will insist on yet another change for their view and you'll need to add it. Instead, just make it all flexible by enabling per-company templates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best strategy for automating multiple builds from a single white-label xcode project? I'm researching the best approach to automating our build process. I've got my own ideas (through experience on a previous non-iOS project) but need good arguments for and against various possibilities. Objective: A single xcode project with a single target (think white-label) needs to be built in 1..N different flavours (concrete brandings) with minimum user interaction and minimum technical knowledge. For AdHoc and/or AppStore. Essentially, that will mean specifying per build; a folder containing Icons + Splashscreen, a bundle containing brand specific resources and (presumably?) the Info.plist, specifying appname, bundle-id, etc. Issues that need to be respected or clarified; * *Manual build of a single brand via Idiot-Proof GUI (choose a git branch/tag, specify a certain brand, configure the app e.g. IAP-enabled, server-domainname, etc - will be written to the info.plist) *In previous manual tests, setting the executable name in the plist didn't work? Sorry, have forgotten the exact problem.. perhaps was only an Xcode Debug buildconfig problem, not relevant to a distribution build? *Code-Signing?!? Can the profile be specified on-the-fly? Some brands need to be built with the customer's own profile. My personal feeling: Hudson or CruiseControl + Xcode plugin. There seems to be plenty of documentation around for an Xcode solution and I've seen this in action on a Flex project I worked on, with almost exactly the same white-label/branding requirements. Of course that was using Ant script though and there was NO behavioral config to respect. That's my only uncertainty here... I suspect it would have to be hardcoded somewhere, but that's not the answer that's going to please some people. There is a wish to be able to specify the various app-config settings (server url, is function Foo supported, is the view X displayed, etc, etc) via a GUI form, when building manually. I'm not sure how easy it would be to shoehorn that into a typical Hudson or CC config? And hence one suggestion that has been made is to write an OSX app for building our clients. The theory being, nice clean non-tech UI for entering all the necessary meta data & app setting and a big shiny green button labelled "Build". But personally I'm skeptical that this approach is any more flexible or easier to implement than a classic CI solution. So the question is basically, what's preferable; a classic server based, version control integrated, CI approach or a custom OSX utility? Whichever we go for it'll almost certainly be a requirement to get it up and running in 2 or 3 days (definately less than one week). A: IMHO you can resolve all issues using different targets of XCode. Every target will share the code but it could: * *be signing with diferent profiles *use diferent plist: this implies having different names.. *use diferent brand images. You only have to name the image with the same name and select the correct target in file inspector. *Build with one click in XCode. I hope this helps A: An extremely later reply, but the approach I would take would be to create the white label IPA, and then create a script to: 1. Unzip it (change the .ipa file extension to .zip). 2. Change assets. Update the info.plist (using Plistbuddy command) Zip it again. Resign the code. See this script as a starting point: https://gist.github.com/catmac/1682965 A: Very late answer. But I would go with different .xcconfig files and multiple schemes. The scheme names could be a combination of target/brand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Repository Pattern and MVC help I'm new to C# and ASP.NET MVC and i'm trying to understand the repository pattern. I've read a whole lot of articles, but I just don't understand how to use it. I'm currently using LINQ to SQL to access my SQL Server 2005 database and for testing purposes I created two tables. I have an Employees table and an EmployeeContacts table. The pk of both tables is UserName. Employees * *UserName *LastName *FirstName *Position *Email *Status *HireDate EmployeeContacts * *UserName *Contact1 *Contact1Phone *Contact1Relationship There is a one to one relationship between the two tables. An employee can be added, updated, and deleted and so can the data in the EmployeeContacts table. So would I create a base repository to be used by both entities or should I create a repository for each entity separately? If anybody would be willing to show me some code that would be great. So far, I have this Employee repository. I also have one for EmployeeContacts. namespace MvcDirectoryLINQ.Models { public class EmployeeRepository { private TestDB_DataDataContext db = new TestDB_DataDataContext(); private UserName u = new UserName(); // // Query Methods public IQueryable<Employee> FindAllEmployees() { return db.Employees; } public IQueryable<Employee> FindRecentEmployees() { DateTime myDate = DateTime.Today.AddMonths(-6); return from empl in db.Employees where empl.HireDate >= myDate orderby empl.HireDate select empl; } public Employee GetEmployee(string UserName) { return db.Employees.SingleOrDefault(d => d.UserName == UserName); } // // Insert/Delete Methods public void Add(Employee employee) { // get the UserName which is created from the email employee.UserName = u.ReturnUserName(employee.Email); //Insert the new employee into the database db.Employees.InsertOnSubmit(employee); db.EmployeeContacts.InsertOnSubmit(employee.EmployeeContact); } public void Delete(Employee employee) { db.EmployeeContacts.DeleteOnSubmit(employee.EmployeeContact); db.Employees.DeleteOnSubmit(employee); } // // Persistence public void Save() { db.SubmitChanges(); } } } I have a class for an EmployeeFormViewModel: namespace MvcDirectoryLINQ.Models { public class EmployeeFormViewModel { //Properties public Employee Employee { get; private set; } public EmployeeContact EmployeeContact { get; private set; } //Constructor public EmployeeFormViewModel(Employee employee, EmployeeContact employeeContact) { Employee = employee; EmployeeContact = employeeContact; } } } Code for EmployeeController: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(string UserName, FormCollection formValues) { Employee employee = employeeRepository.GetEmployee(UserName); EmployeeContact employeecontact = employeecontactRepository.GetContact(UserName); try { UpdateModel(employee); UpdateModel(employeecontact); employeecontactRepository.Save(); employeeRepository.Save(); return RedirectToAction("Details", new { UserName = employee.UserName }); } catch { foreach (var issue in employee.GetRuleViolations()) { ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage); } return View(new EmployeeFormViewModel(employee, attendingID)); } } In my View, i inherit from @model MvcDirectoryLINQ.Models.EmployeeFormViewModel. My Employee data saves correctly but the EmployeeContacts don't and I have no idea why. Am I implementing the repository pattern correctly? A: So would I create a base repository to be used by both entities or should I create a repository for each entity separately? The general rule when using the repository pattern is that there should be one repository class per each primary entity type. Can the EmployeeContacts live independently of any Employee? If so, they should have their own repository. Are them always related to an Employee? If so, manage them by using the Employee repository itself. A: The main goal when using the Repository Pattern (as far as I understand it) is to decouple your application from using a specific Data Access Layer. You haven't done that here because you create I can see that your EmployeeRepository class does not implement an interface. You really want to have something like EmployeeRepository : IEmployeeRepository Then, in your Controller code, you can pass around an IEmployeeRepository instead of working concretely with your EmployeeRepository. This will give you two benefits: * *Should you ever need to switch the backend code, you only need to make another class that implements the interface. *When you go to test your Controllers, you can pass around a so called mock object that implements the interface instead of hitting the actual database, which slows your tests down and also breaks Unit Testing. Another thing I noticed is that you spin up a DataContext inside your repository. If you wanted to make changes to multiple different types of objects you would therefore have multiple DataContexts open, which I don't think is what you want, since your changes won't be transactional. You may want to look into the Unit of Work Pattern for a solution. When learning about a pattern, try to figure out the main benefit first before trying to implement it. In some cases it may not make sense. Please let me know if you would like me to elaborate on anything. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to place different JQuery codes in one line? How can I put this in one line? $("#welcome").delay(100).fadeIn('slow').delay(100).$("#slogan").slideDown(1000); The following code works: $("#welcome").delay(100).fadeIn('slow').delay(100); but not if I place the slogan code after it. A: Use callback function of delay() $("#welcome").delay(100).fadeIn('slow').delay(100, function(){ $("#slogan").slideDown(1000); }); A: $.("#slogan") is not a method which you can chain after the rest of the methods...so no, this would not work. I guess what you want is to use a callback function like so: $("#welcome").delay(100).fadeIn('slow').delay(100, function(){ $("#slogan").slideDown(1000); }); What this does is, call the slideDown for #slogan after the delay on #welcome is finished. A: by adding a anonymous function after the delay like this: $("#welcome").delay(100).fadeIn('slow').delay(100, function() {$("#slogan").slideDown(1000) }); A: The effects functions all take a callback optional argument: $("#welcome").delay(100).fadeIn('slow', function() {$("#slogan").delay(100).slideDown(1000);}); A: You can't append a second selector like that. If #slogan is a child of #welcome you can use $("#welcome").delay(100).fadeIn('slow').delay(100).children("#slogan").slideDown(1000); though. A: If slogan is a descenedant of welcome you could do: $("#welcome").delay(100).fadeIn('slow').delay(100).find("#slogan").slideDown(1000);
{ "language": "en", "url": "https://stackoverflow.com/questions/7570137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best way to store/set configuration settings for a C# application? I have some values that I want to be able to set, and the application to load them from some kind of file. The only concept I can think of, is a simple txt file, that might have the following lines: DatabaseName = "DB1/test" DatabasePassword = "password" Development = "true" but im thinking it should be in some kind of config file? Plus reading a txt file for these values isnt exactly tidy code. It would be nice if i could get the database name by just saying in my application: configfile.DatabaseName Thanks, Paul A: .NET has a configuration platform built into it. Just add an app.config file to your project and use the ConfigurationManager library to access the values. A: You really should be using the built in Application Settings You can directly access simple settings using the ConfigurationManager ConfigurationManager.AppSettings["MySetting"] = "SomeStuff"; var mySetting = ConfigurationManager.AppSettings["MySetting"]; There is also direct access to your Connection Strings using the ConfigurationManager var conn = ConfigurationManager.ConnectionStrings["DevSqlServer"]; All this is stored in XML files, and by default your *.config files. To Answer Doomsknight's question from the comments Configuration settings can be done a number of ways, but by default, they are stored in two places. Application Level Settings are stored in a configuration file. For executable programs this file is located in the same directory as the .exe and is named after the assembly, or executable. Example: MyAssembly.config, Another.Assembly.config For web applications, the settings are stored in the web.config file (usually) located in the root directory of the web application. These are applied hierarchically and one can be located at each directory level of the Web Application. Example: MySite\web.config, MySite\SubDirectory\web.config User Scoped Settings are stored in the user profile Example: C:\Documents and Settings\USERNAME\Local Settings\Application Data\ApplicationName Connection Strings are stored in the <connectionStrings></connectionStrings> section in your config file. <connectionStrings> <clear /> <add name="Name" providerName="System.Data.ProviderName" connectionString="Valid Connection String;" /> </connectionStrings> These settings can easily be modified directly in the config file, but without writing some code to automatically refresh sections of the config file (which is possible), an application restart is typically needed. I hope this helps out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: A demo page for latest WebSocket protocol I've been searching all over the web for simple page that demos WebSocket. But all the examples I find seem to support an older protocol, failing to work in Firefox 6 and Chrome 14. For example: http://html5demos.com/web-socket I'd just like to see some workable demo somewhere, so I could make sure that it's my code that's failing not the browser-implementation of web socket. A: THE WEBSOCKET SERVER DEMONSTRATION CURRENTLY WORKS WITH FIREFOX 7 BETA AND CHROME DEV (it's at 16 now). NOT FIREFOX 6, WHICH USES AND OLDER VERSION OF THE WEBSOCKET DRAFT PROTOCOL. (Just thought I'd mention that because I'm seeing a lot of server hits from Firefox 6 - must be dissatisfying for those who try it.) Here's the code from the demonstration suggested by Cameron. Not sure if it fits your request for something "simple" exactly. It runs within a frame and the function showResults() that prints sends from the browser and what's received back from the server are sent to another frame. All the source code is available at (demo server changes - check bottom of this blog article for up-to-date link to demo ... demo has a download link). Otherwise, it shouldn't take a huge amount of fiddling to turn this back (as it started) into a single page app. Suggest if you want that, start by pointing showResults() to a div in the same page instead of the other page. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="chrome=1"> <title>HLL Command Center</title> <meta http-equiv="Content-Type" content="text/html; charset="utf-8" /> <meta name="description" content="HTML5 Websockets for the HLL high level logic open source project" /> <meta name="keywords" content="high level logic, hll, open source, artificial intelligence, agents" /> <meta name="author" content="Roger F. Gay" /> <meta name="owner" content="rogerfgay@isr.nu" /> <meta name="copyright" content="%a9 2011 Roger F. Gay" /> <meta name="license" content="Lesser General Public License (LGPL v. 2.1)" /> <meta name="website" content="http://hll.dev.java.net" /> <meta name="permission" content="restricted" /> <meta name="created" content="20110801" /> <meta name="changed" content="20110902" /> <meta name="security" content="public" /> <meta name="generator" content="skill, knowledge, and intelligence" /> <style type="text/css"> body {background-color:Khaki;} </style> <script type="text/javascript"> var websocket; var connected=false; var frameDoc; var appType; function doConnect(wsURIValue) { if (connected) { showResults("<span style='color: red;'>You're already connected!</span>"); } else { if (appType == "Mozilla") { websocket = new MozWebSocket(document.getElementById('wsURI').value); } else { websocket = new WebSocket(document.getElementById('wsURI').value); } websocket.onopen = function(evt) { onOpen(evt) }; websocket.onclose = function(evt) { onClose(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; } } function onOpen(evt) { connected=true; showResults("CONNECTED"); doSend("WebSocket rocks!"); } function onClose(evt) { connected=false; websocket.close(); showResults("DISCONNECTED"); } function doPing () { if (connected) { showResults("Not yet implemented in browser. Sending pseudo-ping message: 'Ping'."); websocket.send('Ping'); } else { showResults("<span style='color: red;'>NOT CONNECTED: No pseudo-ping message sent.</span>"); } } function onMessage(evt) { showResults("<span style='color: blue;'>RESP: " + evt.data + "</span>"); } function onError(evt) { showResults("<span style='color: red;'>ERROR:</span> " + evt.data); } function doSend(message) { if (connected) { websocket.send(message); showResults("SENT: " + message); } else { showResults("<span style='color: red;'>NOT CONNECTED: No message sent.</span>"); } } function doMultiple (message) { for (i=0; i<n_times; i++) { if (connected) { websocket.send(message); showResults("SENT: " + message); } else { showResults("<span style='color: red;'>NOT CONNECTED: No message sent.</span>"); } } } function doClose(message) { if (connected) { showResults("CLOSING"); websocket.close(); connected=false; } else { showResults("<span style='color: red;'>NOT CONNECTED</span>"); } } function showResults(message) { frameDoc.showResults(message); } function init() { if ((frameDoc = parent.results)) { document.getElementById('wsURI').value=wsUri; document.getElementById('message').value=mess; showResults("Frame communication confirmed."); } else { document.getElementById("testit1").innerHTML = "<span style='color:red'>Interframe communication failed for this webpage.</span>"; alert("Problem printing output: This application has been tested with up-to-date versions of Chrome, Firefox, and MSIE. (May 22, 2011)"); return; } if (typeof MozWebSocket != "undefined") { // (window.MozWebSocket) appType = "Mozilla"; } else if (window.WebSocket) { appType = "Chrome"; } else { showResults('<strong style="color: red;">ERROR: This browser does not support WebSockets.</strong>'); return; } } function changeNTimes () { n_times = flowContainer.ntimes.options[document.flowContainer.ntimes.selectedIndex].value; } var wsUri = "ws://isr2.mine.nu/echo"; var mess = "HLL International: " + String.fromCharCode(196,197,214) + " " + String.fromCharCode(945,946,948) + " " + String.fromCharCode(20149,20150,20153) + " " + String.fromCharCode(1490,1513,1488,1458) + " " + String.fromCharCode(286,350,399); var n_times=5; // window.addEventListener("load", init, false); </script> </head> <body onload="init()"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script> <b>Server: </b> <input type='button' onclick="doConnect(document.getElementById('wsURI').value)" value='Open Connection' /> <input type='button' onclick="doClose()" value='Close Connection' /> <input type='button' onclick="doPing()" value='Ping' /><br> <input type='text' style="text-align:left;" size='65' id='wsURI' /><br><br> <span style="background-color:#CCCCCC"> <b><input type="radio" id="encoding" value="text" disabled="true" checked /> text <input type="radio" id="encoding" value="binary" disabled="true" /> binary</b> (binary not yet browser supported) <br><br> </span> <b>Message: </b> <input type='button' onclick="doSend(document.getElementById('message').value)" value='Send Message to Server' /><br> <textarea cols="50" rows="3" maxlength='260' id="message" ></textarea><br><br> <b>Continuation (will be sent if not null): </b><br> <textarea cols="50" rows="3" maxlength='125' id="continued" ></textarea><br><br> <form name="flowContainer"> <input type='button' onclick="doMultiple(document.getElementById('message').value)" value='MultiMessage' /><br> <select name="ntimes" onchange="changeNTimes()"> <option value="5" selected="selected">5</option> <option value="10">10</option> <option value="20">20</option> </select> </form> <div id='testit3' name='testit3' style='color:blue'></div><br><br> <div id='testit1' name='testit1' style='color:green'></div> <script> // You may want to place these lines inside an onload handler CFInstall.check({ mode: "overlay", destination: "http://www.waikiki.com" }); </script> </body> </html> A: Yes. Here's a working demo of the final call version of the websocket protocol: version 8 (hybi-8,9,10 ... 17). (demo server changes ... see blog article below for up-to-date link) There's a blog article about it here: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html NOTE THAT IT USES FIREFOX 7 BETA (NOT 6, which supports and older version of the protocol) or Chrome dev-channel 14 or later. (I guess we were all a bit sleepy. This is the direct, short answer to your question. Also, some of the demo dhtml code is listed above, along with a place to download it if you want.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7570143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: include function xy() of a wordpress plugin I want to build a WordPress admin dashboard widget which should return some information from another plugin. This dashboard widget should read the functions of this plugin here: http://plugins.svn.wordpress.org/wp-document-revisions/trunk/wp-document-revisions.php So my code is: include (WP_PLUGIN_URL.'/wp-document-revisions/wp-document-revisions.php'); $file_type = get_file_type('3'); But this doesn't work. These are the errors: Fatal error: Call to undefined function add_action() in /.../wp-content/plugins/wp-document-revisions/wp-document-revisions.php on line 26 Fatal error: Call to undefined function get_file_type() in /.../wp-content/plugins/dashboard-widget/dashboard-widget.php Can anyone tell me how I have to do this, that I can read the function get_file_type('3')? A: I'm assuming you are navigating straight to your PHP file in the wp-content/plugins/ folder rather than using a stub to create a URL. If this is the case, then you probably forgot to include wp-load.php A: You should not include the plugin file (since the plugin may not be installed or activated). Instead of this you should check if the function exists: if (function_exists('get_file_type')) { $file_type = get_file_type('3'); // rest of the code of the widget } A: It sounds like you are trying to access the PHP file directly, rather than going through WordPress proper. You should create a plugin, and hook into the Dashboard Widgets API. As for implementation with WP Document Revisions, you've got two options. As of version 1.2, get_documents() and get_document_revisions() are two global functions that will be accessible anytime after the plugins_loaded hook. The FAQ has a bit more info, but they basically function like the native get_posts() function. Alternatively, the class should be available globally as $wpdr. So if you wanted, for example, to call get_latest_version( 1 ) it'd be $wpdb->get_latest_version( 1 ). Both assume the plugin's already activated. If you simply include the file, you're going to get an error that you're trying to redeclare the WP_Document_Revisions class. If you do create a dashboard, I'd love to include it in future releases of the plugin!
{ "language": "en", "url": "https://stackoverflow.com/questions/7570146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Object returned from function and copy constructor There is such code: #include <iostream> class A { public: int a; A() : a(0) { std::cout << "Default constructor" << " " << this << std::endl; } A(int a_) : a(a_) { std::cout << "Constructor with param " << a_ << " " << this << std::endl; } A(const A& b) { a = b.a; std::cout << "Copy constructor " << b.a << " to " << a << " " << &b << " -> " << this << std::endl; } A& operator=(const A& b) { a=b.a; std::cout << "Assignment operator " << b.a << " to " << a << " " << &b << " -> " << this << std::endl; } ~A() { std::cout << "Destructor for " << a << " " << this << std::endl; } void show(){ std::cout << "This is: " << this << std::endl; } }; A fun(){ A temp(3); temp.show(); return temp; } int main() { { A ob = fun(); ob.show(); } return 0; } Result: Constructor with param 3 0xbfee79dc This is: 0xbfee79dc This is: 0xbfee79dc Destructor for 3 0xbfee79dc Object ob is initialized by function fun(). Why copy constructor is not called there? I thought that when function returns by value then copy constructor or assignment operator is called. It seems that object constructed in function fun() is not destroyed after execution of function. How can be copy constructor forced to invoke in this case? This was compiled by g++. A: Why copy constructor is not called there? RVO How can be copy constructor forced to invoke in this case? Pass an option to the compiler. For gcc, it is --no-elide-constructors option to disable the RVO A: That is called Named Return Value Optimization and copy elision, and basically means that the compiler has figured out that the copy can be avoided by carefully placing the temporary and the object in the same memory location. By default there would be three objects in that piece of code, temp inside fun, the return value and ob inside main, and as many as two copies, but by carefully placing temp in the same memory location as the returned object inside fun and placing ob in the same memory address the two copies can be optimized away. I wrote about those two optimizations with a couple of pictures to explain what is going on here: * *NRVO *Copy elision
{ "language": "en", "url": "https://stackoverflow.com/questions/7570152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove "Welcome to"... on Drupal's seven theme I'm trying to remove the text "Welcome to" on the Drupal theme seven. I want to keep my site name though as it stands it says "Welcome to Site Name" at the top left. I just want it to say "Site Name". A: this text will be removed automatically once you create a new content (which promoted to front page)... so don't worry about this.... another advanced way is to create your front page and insert the link of you page in "/admin/config/system/site-information" instead of "node" in the "Default front page" section A: I just had to replace the variable $title with $site_name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a nested JSON request with Python A user needs to pass a json object as a part of the request. It would look something like this: {"token" :"ayaljltja", "addresses": [ {'name':'Home','address':'20 Main Street', 'city':'new-york'}, {'name':'work', 'address':'x Street', 'city':'ohio'} ]} I have two problems right now. First, I can't figure out how to test this code by recreating the nested POST. I can successfully POST a dict but posting the list of addresses within the JSON object is messing me up. Simply using cURL, how might I do this? How might I do it with urrlib2? My second issue is then deserializing the JSON POST object on the server side. I guess I just need to see a successful POST to determine the input (and then deserialize it with the json module). Any tips? A: With command line curl, save your JSON to a file, say data.json. Then try: curl -X POST -d @data.json http://your.service.url It's also possible to enter the JSON directly to the -d parameter but (as it sounds like you know already) you have to get your quoting and escaping exactly correct. A: First make sure your JSON is valid. Paste it into the JSONLint web page. Currently your JSON has two issues: * *there is no comma between "token" :"ayaljltja" and "addresses": [...] *a single quote is not a valid way of delimiting a JSON string, replace them all with double quotes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Does Facebook have a maximum number of API connections? If the answer is yes, then what is it? By maximum number of connectioned allowed per application I mean how many instances of the same api/key can be used to get the friends list at any one time, will Facebook block too many requests? EDIT I have been looking at http://developers.facebook.com/ but have not been able to find the answer to my question there. A: From their Policy If you exceed, or plan to exceed, any of the following thresholds please contact us as you may be subject to additional terms: (>5M MAU) or (>100M API calls per day) or (>50M impressions per day). A: The only information I was able to find is something in a forum. http://www.quora.com/Whats-the-Facebook-Open-Graph-API-rate-limit After some testing and discussion with the Facebook platform team, there is no official limit I'm aware of or can find in the documentation. However, I've found 600 calls per 600 seconds, per token & per IP to be about where they stop you. I've also seen some application based rate limiting but don't have any numbers. As a general rule, one call per second should not get rate limited. On the surface this seems very restrictive but remember you can batch certain calls and use the subscription API to get changes. A: You can see how many API requests your users can have a day if you go to your Insights page and click on "Diagnostics". You can also see some other request statistics if you click on "Performance". http://www.facebook.com/insights
{ "language": "en", "url": "https://stackoverflow.com/questions/7570157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Comparison gives different results in Coffeescript/Javascript and Ruby Example: [42] == [42] The result of the comparison gives different results: CS/JS: false Ruby: true On the other hand: 42 == 42 gives the result: CS/JS: true Ruby: true What is the reasoning behind this? A: The other answerers have done a good job of explaining the JavaScript/CoffeeScript equality semantics. (CoffeeScript's == compiles to JavaScript's stricter ===, but that makes no difference in this case.) The Ruby case is more complex: Everything in Ruby is an object, and so every object has a == method which, in principle, could do anything. In the case of arrays, it looks at the other array, checks if it has the same length, and then checks if x == y for each x in itself and y in the other array. If you want to emulate the Ruby behavior, it's quite simple to write a function to do so: deepEquals = (arr1, arr2) -> return false unless arr1.length is arr2.length for i in [0...arr1.length] if arr1[i] instanceof Array and arr2[i] instanceof Array return false unless deepEquals(arr1[i], arr2[i]) else return false if arr1[i] isnt arr2[i] true A: For the Javascript case the comparisons are fundamentally different. Each [42] is a new array and arrays don't compare structurally they simply check to see if they are the same object. So [42] == [42]; // false. Different objects var x = [42]; var y = [42]; x == y; // false. Same check as [42] == [42] x == x; // true. Same object The literal 42 is a primitive type and compares by value. A: In JavaScript, arrays are compared by reference, not by value. [42] and [42] are different entities (albeit clones of one another) and therefore not equal. The fact that 42 is the answer to everything is, unfortunately, not relevant here. A: In JavaScript [42] == [42] says "Are these two arrays the same object?" (no they're not), which is not the same as asking "Do these two arrays contain the same elements?" On the other hand: 42 == 42 "Are these two number primitives equal comparing by value?" (Note: this is an oversimplification of what JavaScript is doing because the == operator will attempt to convert both operands to the same type; contrast with the === operator.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7570164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to declare structures of data that should only be used in a certain context, C++ I'm having a rather general design problem and would like to solve it nicely. I'm writing remote control drivers in an embedded C++ project. There will be two types of remote control: joystick or radio. As I'd like the actual remote controller used to be transparent to an user-programmer, I'm also providing a base class for the two. So I'm going to have: class RemoteControl {}; class JoystickControl : public RemoteControl {}; class RadioControl : public RemoteControl {}; I'd like RemoteContol to just have one public method: RemoteControl.getInput(). This method should return a structure of data in common format, eg. RCInput, so the above method's declaration would be: class RemoteContol { virtual RCInput getInput(); }; Now, what's the best way to implement RCInput to be able to pass it to other classes' objects? I thought an inner class / structure might be a solution, but I never used it yet so can someone please provide an example of implementation and usage? Thanks in advance. EDIT: What I did before was (could be references, this is not important at the moment): typedef struct { int a; int b; } RCInput; class RemoteContol { public: virtual RCInput getInput() { return rcInput; } private: RCInput rcInput; }; But I thought this way I'm allowing users to create their own structures of type RCInput also not related to RemoteControl, so I was looking for a better design. But maybe there isn't any. A: It looks that RCInput is going to be just data, so you can lay it out like that: RCInput.h file class RCInput { public: RCInput(double x, double y, double z); double x() const; double y() const; double z() const; private: double m_x; double m_y; double m_z; }; RCInput.cpp file: RCInput::RCInput(double x, double y, double z) : m_x(x), m_y(y), m_z(z) { } double RCInput::x() const { return m_x; } double RCInput::y() const { return m_y; } double RCInput::z() const { return m_z; } Don't make it a nested class, put it in its own header file. This way the clients which use the inputs do not depend physically on the RemoteControl class header file. In my experience, nested classes are usually an unnecessary complication, they should be best avoided unless really necessary (e.g. iterators in containers). Also, don't yield to the temptation of making RCInput a struct with public data. You will lose all control over data accesses and creation of data, if you do so (no access logging in getters, no data validation in constructor, no place to set a debugger breakpoint). Remember that forward declaring a class/struct means that some other piece of code will need to be changed if you later decide to turn a struct into class, i.e. instead of struct RCInput; you will have to write class RCInput; It's better to make it a class from day 1. If you worry about performance, you can inline the getters. If you want to store RCInput in containers, add a public default constructor. If you want to control who can create RCInput, make the constructor private and declare the creating classes as friends (but that makes storing it in containers difficult).
{ "language": "en", "url": "https://stackoverflow.com/questions/7570165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to map an XML to Java objects by XPaths? Given the XML example: <fooRoot> <bar> <lol>LOLOLOLOL</lol> </bar> <noob> <boon> <thisIsIt></thisIsIt> </boon> </noob> </fooRoot> Which should be mapped to: class MyFoo { String lol; String thisIsIt; Object somethingUnrelated; } Constraints: * *XML should not be transformed, it is provided as a parsed org.w3c.dom.Document object. *Class does not and will not map 1:1 to the XML. *I'm only interested to map specific paths of the XML to specific fields of the object. My dream solution would look like: @XmlMapped class MyFoo { @XmlElement("/fooRoot/bar/lol") String lol; @XmlElement("/noob/boon/thisIsIt") String thisIsIt; @XmlIgnore Object somethingUnrelated; } Does anything likewise exists? What I've found either required a strict 1:1 mapping (e.g. JMX, JAXB) or manual iteration over all fields (e.g. SAX, Commons Digester.) JiBX binding definitions come the nearest to what I'm lokking for. However, this tool is ment to marshall/unmarshall complete hierarchy of Java objects. I only would like to extract parts of an XML document into an existing Java bean at runtime. A: Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group. You can do this with MOXy: @XmlRootElement(name="fooRoot") class MyFoo { @XmlPath("bar/lol/text()") String lol; @XmlElement("noob/boon/thisIsIt/text()") String thisIsIt; @XmlTransient Object somethingUnrelated; } For More Information * *http://blog.bdoughan.com/2010/07/xpath-based-mapping.html *http://blog.bdoughan.com/2010/09/xpath-based-mapping-geocode-example.html *http://blog.bdoughan.com/2011/03/map-to-element-based-on-attribute-value.html *http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html A: Try XStream. It's super easy. Hope it helps! I don't have time now for a full example :) A: One option could be write a custom annotation which will take the XPath expression as input and do the bindings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Downloading files in a webpage I need to make the user able to download a file from my webpage on clicking a link on my website I tried <a href='./image.ext'>Download file</a> By it just opened a new window and i need to right click and select "save page as" What I am expected is ,after clicking my link user must see a dialogue box "save as" as usual...How to do it..Is there any way in HTML to force download by showing such a dialogue Note:Since stackoverflow is not allowing anchor tag,i just typed it as a.Please do not treat it as a mistake A: If you're using an Apache web server, you can use the .htaccess file to force file download for certain file extensions. Add this line to your .htaccess to cause the "Save As" dialog to appear when the link is clicked: AddType application/octet-stream .ext If you wanted the same behaviour for a PDF or AVI, the following lines would do it: AddType application/octet-stream .pdf AddType application/octet-stream .avi A: You can use php to readfile() the file to the user. this tutorial would be helpful for you : http://webdesign.about.com/od/php/ht/force_download.htm A: I know it is lame, but I found a solution here
{ "language": "en", "url": "https://stackoverflow.com/questions/7570178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Please give me some advice on how to evaluate a maximum region which covers all given regions? Suppose I have dozens of geographic regions, which can be defined through the use of the following c/c++ structure: typedef struct tagGEOGRAPHIC_REGION { float fNorthMost; float fSouthMost; float fWestMost; float fEastMost; } GEOGRAPHIC_REGION, *PGEOGRAPHIC_REGION; And I now want to get the maximum region, which will cover all given regions. The function template may look like the following: const GEOGRAPHIC_REGION& GetMaxRegion(const std:vector<GEOGRAPHIC_REGION>& vRegions) { ...... } I can put the four components of GEOGRAPHIC_REGION struct into 4 different float vectors, and then evaluate their respective maximum values. Finally, the four maxium values can be combined to form the maximum region. I think it must be a simple way to do that. Would you please give me some advice? Thank you very much! A: Can't you just iterate over the vector, and get the maximum north, minimum south, etc, with just one loop? A: I suggest something like this as a starting point: * *see it live: http://ideone.com/LQk8U *note that I might have your axis direction guessed wrong (you might need to swap some min/max in that case) Edit fixed according to comment "North is positive, and East is positive" *for a vector, just do std::acummulate(v.begin(), v.end(), v[0]....) In case your scenarios get more complicated, see the Boost Geometry Library . #include <iostream> #include <numeric> struct GEOGRAPHIC_REGION { float fNorthMost; float fSouthMost; float fWestMost; float fEastMost; }; GEOGRAPHIC_REGION combine(const GEOGRAPHIC_REGION& accum, const GEOGRAPHIC_REGION& tocombine) { GEOGRAPHIC_REGION combined = { std::max(accum.fNorthMost, tocombine.fNorthMost), std::min(accum.fSouthMost, tocombine.fSouthMost), std::min(accum.fWestMost, tocombine.fWestMost), std::max(accum.fEastMost, tocombine.fEastMost) }; return combined; } int main() { const GEOGRAPHIC_REGION regions[] = { { 2,-1,-1,1 }, { 1,-2,-1,1 }, { 1,-1,-2,1 }, { 1,-1,-1,2 }, }; GEOGRAPHIC_REGION super = std::accumulate(regions, regions+4, regions[0], combine); std::cout << "{ " << super.fNorthMost << ", " << super.fSouthMost << ", " << super.fWestMost << ", " << super.fEastMost << " }" << std::endl; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Validate and Ajax - resetting validation after fail I have a form using jQuery and the Validation plugin. One element uses Ajax to check if a username is in use. When testing with a username known to be in use, it works correctly and highlights the field stating the username is in use. However, when I change the username to one that is not in use, it never clears the error message and revalidates. $("#frmID").validate({ onkeyup:false, highlight: function(element, errorClass) { $(element).addClass('inputError'); }, unhighlight: function(element, errorClass) { $(element).removeClass('inputError'); }, rules: { username :{ required: true, usernamecheck: true } and then the username check function is: $.validator.addMethod('usernamecheck',function(username) { var result = true; var postURL = compath + "/user.cfc?method=QueryUserExists&amp;returnformat=plain&amp;"; $.ajax({ cache:false, async:false, type: "POST", data: "username=" + username, url: postURL, success: function(msg) { result = (msg=='FALSE')? true : false; } }); return result; },''); I've left out the validation error messages and some other validation for clarity. A: I would try removing your highlight and unhighlight methods and simply specify an errorClass option in your validation setup. Since all you are doing is adding and removing a class you can let the validation framework do this for you. You can see more about the errorClass option here: http://docs.jquery.com/Plugins/Validation/validate#options
{ "language": "en", "url": "https://stackoverflow.com/questions/7570182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unable to use Diazo (plone.app.theming) on Centos I made a webportal on my mac using plone4.1 and Diazo. Now, I'm trying to deploy it on my server (CentOs) where there is yet another site with plone4.0.5 + collectivexdv. When I run the site (in a brand new buildout) with my diazotheme I obtain this lines via shell (instance fg): 2011-09-27 09:32:10 ERROR plone.transformchain Unexpected error whilst trying to apply transform chain Traceback (most recent call last): File "/home/plone/.buildout/eggs/plone.transformchain-1.0-py2.6.egg/plone/transformchain/transformer.py", line 42, in __call__ newResult = handler.transformIterable(result, encoding) File "/home/plone/.buildout/eggs/plone.app.theming-1.0b8-py2.6.egg/plone/app/theming/transform.py", line 205, in transformIterable transform = self.setupTransform() File "/home/plone/.buildout/eggs/plone.app.theming-1.0b8-py2.6.egg/plone/app/theming/transform.py", line 150, in setupTransform xsl_params=xslParams, File "/home/plone/.buildout/eggs/diazo-1.0rc3-py2.6.egg/diazo/compiler.py", line 106, in compile_theme read_network=read_network, File "/home/plone/.buildout/eggs/diazo-1.0rc3-py2.6.egg/diazo/rules.py", line 160, in process_rules rules_doc = fixup_themes(rules_doc) File "/home/plone/.buildout/eggs/diazo-1.0rc3-py2.6.egg/diazo/utils.py", line 49, in __call__ result = self.xslt(*args, **kw) File "xslt.pxi", line 568, in lxml.etree.XSLT.__call__ (src/lxml/lxml.etree.c:120289) XSLTApplyError: xsltValueOf: text copy failed What's the matter? A: I had the exact same problem and it's due an old libxml2/libxslt. Add these lines on your buildout: [buildout] parts = lxml # keep lxml as the first one! ... instance [lxml] recipe = z3c.recipe.staticlxml egg = lxml libxml2-url = ftp://xmlsoft.org/libxml2/libxml2-2.7.8.tar.gz libxslt-url = ftp://xmlsoft.org/libxml2/libxslt-1.1.26.tar.gz static-build = true force = false A: See Plone - XSLTApplyError: xsltValueOf: text copy failed. Probably you have an outdated libxml, as it is always the case with an old distribution like CentOS. Use z3c.recipe.staticlxml. A: It sounds like you might have overly old versions of libxml2 and/or libxslt. I encountered identical problems with libxml2 2.6.26 and libxslt 1.1.17. After upgrading to 2.7.8 and 1.2.26 (respectively) the problems went away. If you can't upgrade the libraries locally, you can move forward quite quickly using the "z3c.recipe.staticlxml" recipe in your buildout: [lxml] recipe = z3c.recipe.staticlxml egg = lxml Just remember to delete any existing lxml egg in the eggs directory (or possibly in your ~/.buildout/eggs cache, depending on how your ~/.buildout/default.cfg it set up) first. A: I just got this to work using Plone 4.2.1 on OS X 10.8 Server but only once I used the unified installer. I bumped up the libxml2 to version 2.8.0. At the time I tried this, libxml2 version 2.9.0 was broken for OS X 10.8.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: CSS z-index not stacking correctly I am having trouble with CSS z-index stacking. HTML: <ul> <li><a href="#">Title 1</a></li> <li class="dropMenu"><a href="#">Title 2</a> <div class="containerDropDown"> <ul class="menu"> <li><a href="#">Lorem ipsum link</a></li> <li><a href="#">Lorem ipsum dolor sit met link amet ipsum link</a></li> <li><a href="#">Dolor sit amet link</a></li> <li><a href="#">Lorem ipsum link</a></li> <li><a href="#">Dolor sit amet link</a></li> <li><a href="#">Lorem ipsum link</a></li> </ul> </div> </li> <li><a href="#">Title 3</a></li> <li><a href="#">Title 4</a></li> <li><a href="#">Title 5</a></li> </ul> CSS: li.dropMenu { z-index:100; } .dropMenu:hover { padding-bottom:9px; border:1px solid #575a5d; border-bottom:0; background-color:#434749; position:relative; -moz-box-shadow:0 0 5px #000; -webkit-box-shadow:0 0 5px #000; box-shadow:0 0 10px #000; z-index:100; } .dropMenu:hover a { padding:0 9px; color:#8f6f4d; } .dropMenu ul { width:198px; left:-999em; padding:16px 0 0 0; border:1px solid #575a5d; background-color:#434749; position:absolute; -moz-box-shadow:0 0 5px #000; -webkit-box-shadow:0 0 5px #000; box-shadow:0 0 5px #000; } .dropMenu:hover ul { /*top:32px;*/ top:10px; left:-1px; z-index:20; } .dropMenu ul li { display:block; width:100%; padding:0; z-index:70; } .dropMenu:hover ul li a, .dropMenu ul li a{ display:block; padding:0 30px 22px 30px; font-size:0.8em; color:#d0cfcb; background:transparent url("/images/background/dropDownMenu-arrow.gif") no-repeat 21px 4px; } I need to get li.dropMenu to have a higher stacking order than its child ul. I tried to change the z-index but with no luck. Does any one know of any solutions? I am trying to create a simple drop down menu but the child UL seems to be always on top of the parent li.dropMenu. I am giving a box-shadow to the child ul but because its always on top the shadow goes over the li.dropMenu A: You need to set a position attribute (other than static) in your CSS for each element you want to use z-index on. A: You need to give the li.dropMenu a position in order for the z-index to work. Try li.dropMenu { z-index:100; position:relative; } More info here: z-index specifies the stack level of a box whose position value is one of absolute, fixed, or relative. http://reference.sitepoint.com/css/z-index A: The problem that you have is that an absolutely-positioned element is placed relative to it's closest ancestor with a non-static (i.e., relative, absolute, fixed) positioning. So your child z-index is applied only within the context of the parent element, not in comparison to it. Solution: place the content of the parent in a sibling of the child: <ul> <li><a href="#">Title 1</a></li> <li class="dropMenu"> <div class="parentItemHolder"><a href="#">Title 2</a></div> <div class="containerDropDown"> <ul class="menu"> <li><a href="#">Lorem ipsum link</a></li> <li><a href="#">Lorem ipsum dolor sit met link amet ipsum link</a></li> <li><a href="#">Dolor sit amet link</a></li> <li><a href="#">Lorem ipsum link</a></li> <li><a href="#">Dolor sit amet link</a></li> <li><a href="#">Lorem ipsum link</a></li> </ul> </div> </li> <li><a href="#">Title 3</a></li> <li><a href="#">Title 4</a></li> <li><a href="#">Title 5</a></li> </ul> With the CSS (note, I've removed some of the original for brevity): .dropMenu { position: relative; } .dropMenu:hover div.parentItemHolder { padding-bottom:9px; border:1px solid #575a5d; border-bottom:0; background-color:#434749; position:relative; -moz-box-shadow:0 0 5px #000; -webkit-box-shadow:0 0 5px #000; box-shadow:0 0 10px #000; z-index:100; } .dropMenu ul { width:198px; display: none; /* using display: none; instead of left: -999em; */ padding:16px 0 0 0; border:1px solid #575a5d; background-color:#434749; -moz-box-shadow:0 0 5px #000; -webkit-box-shadow:0 0 5px #000; box-shadow:0 0 5px #000; } .dropMenu:hover ul { display: block; position: absolute; z-index:20; } A: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). A: start by removing the z-indices then you should be targeting the siblings a and .containerDropDown, or remove .containerDropDown and just use the ul instead. then you just need to add: .dropMenu>a{position:relative;z-index:2} which is much easier than trying to make a child z-index less than parent. made a fiddle: http://jsfiddle.net/filever10/TbJt3/
{ "language": "en", "url": "https://stackoverflow.com/questions/7570186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Make loadingDialog disappear when twitter4J page completes I'm using Twitter4J and a WebView. A circular progress bar (spinner) is displayed in onPageStarted. This dialog is hidden in onPageFinished. The problem is that the spinner never disappears. Adding logging statements to onPageStarted and onPageFinished, this is what I see (name changed): loading url: http://twitter.com/xyz finished loading url: http://twitter.com/xyz loading url: http://mobile.twitter.com/xyz loading url: https://mobile.twitter.com/xyz The last two URLs NEVER callback to onPageFinished. Although I can write an ugly hack to only display the loading dialog when the first URL is loaded, that doesn't solve the problem--then the spinner disappears before the content actually finishes loading. From reading around on StackOverflow I gather that detecting when a WebView has truly finished loading can be problematic, and have not seen a very good solution to that issue. However, I'm just hoping that someone familiar with displaying Twitter feeds in WebViews in Android apps knows how to tell when it finishes loading. I'm really surprised onPageFinished is not getting called correctly, as the page looks fulled loaded. A: I finally found the answer! There are two steps to be added. * *Use the best mobile URL. If you enter a URL that you would use on the desktop, there are several redirects. This slows down the page loading, confuses the webview, and then onPageStarted() and onPageFinished() both run multiple times. To find the mobile URL, simply enter the URL in a browser, let it finish its redirects and loading, then take whatever URL it ends up at and use that in your code. *Use webview.getSettings().setUserAgentString("whatever"). The exact user agent string is irrelevant; you just have to set it, or else the webviews are not loaded properly. Kudos to gid for giving this response at can't open twitter url in android webview (sorry, I don't have enough reputation to upvote him on that thread). As long as I do both these things, it works perfectly--I remove the spinner in onPageFinished and the app acts as a user expects. People who still have trouble with it may try: webview.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); Log.d(TAG, "progress updated to " + newProgress); } }); I didn't have much luck with reliably counting on this eventually reporting progress of 100, but someone else might.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom Additional Cell Actions in Excel 2010 I'd like to extend the MS Excel 2010 by adding some more "Additional Cell Actions". (accessible via cell right-click > Additional Cell Actions). Specifically, I'd like Excel to: * *recognize five-to-eight digit numbers as Part Numbers with action: "Open URL to technical docs" *recognize string "OR ## #####" (# for digit) as Order Reference with actions: "Open spec file" and "Open material file" (both Excel files located at specified paths in the intranet) Now, I have no idea how to program this. I suspect that some XML snippet is needed and probably some VB code too. VB code wouldn't be a problem - I have macros doing those functionalities done for Excel 2003 - but I have no idea where to place it. Please give me some pointers, I've asked Google but can't get the answer, seems that "Additional Actions" is pretty common phrase :) A: This can be achieved by adding a right click event handler to the workbook In the Workbook module add this code Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Dim cBut As CommandBarButton Dim v As Variant On Error Resume Next v = Target ' Remove any previously added menu items Application.CommandBars("Cell").Controls("Open URL to technical docs").Delete Application.CommandBars("Cell").Controls("Open material file").Delete ' save cell value for use by called macro CellValue = v ' If cell matches criteria add menu item and set macro to call on click If IsNumeric(v) Then If v >= 10000 And v <= 99999999 Then Set cBut = Application.CommandBars("Cell").Controls.Add(Temporary:=True) With cBut .Caption = "Open URL to technical docs" .Style = msoButtonCaption .OnAction = "OpenRef" End With End If ElseIf v Like "OR ## #####" Then Set cBut = Application.CommandBars("Cell").Controls.Add(Temporary:=True) With cBut .Caption = "Open material file" .Style = msoButtonCaption .OnAction = "OpenMat" End With End If End Sub In a standard module add this code Public CellValue As Variant ' replace MsgBox code with your logic to open files Sub OpenRef() MsgBox "Open Reference Doc code here for " & CellValue End Sub Sub OpenMat() MsgBox "Open Material File code here for " & CellValue End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7570193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 32-bit dll not working in 64-bit os I created a dll file built (Project:win32 app, ATL and COM object using Visual studio 2008) in 32 bit. In win 7 32 bit OS, After registering my dll i'm getting "ABC" option in context menu(on right click). Now i move to win 7 64 bit OS. Dll loaded successfully, but i'm not getting "ABC" option on right click(in context menu). Can anyone please point me where i went wrong or any suggestions ? Note: Right click on Folder gives "ABC" option. A: A shell extension compiled for 32bit will run only in a 32bit process. The Windows Explorer of a 64bit Windows is a 64bit process, so it requires a 64bit shell extension. If a 32bit application would use the fileopen dialog (on a 64bit Windows), the dialog would require a 32bit shell extension. So it's recommended that you install your extension like that: * *Win32: 32bit Shell Extension *Win64: 64bit and 32bit Shell Extension To do this, you have to give different GUIDS to the 32bit / 64bit shell extension. Hope that makes it a bit more clear. Edit: As Raymond suggested, it seems that you can use the same GUID for both extensions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Indoor tracking (IMU + tags) this is another question about indoor tracking using inertial (smartphone + aceel + gyro) Firstly, I would like to say that I have read almost every post on stackoverflow talking about this subject. And I know that to track a position We will have to integrate TWICE the accel and that is very useless in a real life application because of all the drift errors... But it turned out that I don't need to build a plane or whatever And i don't need to develop an application that have to WORK to be sold or something. I just want to realize a simple Android App that use "theoretical" concept of an Indoor tracking- * *What's the possibilities? *What do we need? Basically my phone is resting on a desk screen facing UP at a known position (0,0) if a push my phone to 2 or 3 meters and then I rotate it and push it again for 2 or 3 meters I the to see after how many meters it becomes to inaccurate an so use a tag tu recalibrate the measurements <--- That's my main question what do I need ? - the angle ? (ok integrating the the gyro) (i don't wanna use the compass) - the accel? (i have) - the velocity ? (integrating the accel) - and the position (double accel integration) The thing that I would like to know is How can I put this number together? Is it the right way to do it? Is there another solution (to resolve my problem, not to track someone really accurately)? I also looked at the theory of the DCM (If I understood correctly, it will give me the orientation of the phone in 6 axes right? But what's the difference about getting the angle from the Accel or the gyro (pitch, roll etc..) ? Thank you A: Your smartphone probably has a 3-axis gyro, a 3-axis magnetometer and a 3-axis accelerometer. This is enough for a good estimation of attitude. Each has its advantages and disadvantages: The accelerometers can measure the gravity force, it gives you the attitude of your phone, but in a horizontal position, you can't know where it's pointing. And it's very sensitive to inertial noise. The gyroscopes are fastest and the most accurate, but its problem is the drift. The magnetometers don't have drift and they aren't sensitive to inertial forces, but are too slow. The combination of the three give you all advantages and no disadvantages. You must read the gyro measure faster as you can (this minimizes the drift) and then use the slow and not as accurate measure of magnetometer and accelerometer to correct them. I leave you some links that may interest you: * *A Guide to using IMU: http://www.starlino.com/imu_guide.html *DCM tutorial: http://www.starlino.com/dcm_tutorial.html I hope I've been helpful and sorry for my bad English. A: With the sensors you have, not considering computational power at this point yet, I know of only one method of position / displacement estimation. This would either involve just optical flow with the onboard camera, or the above with addidional info from fused data from accels / gyros (eg. with a Kalman-Filter) to improve accuracy. I guess OpenCV has all you need (including support for Android), so I'd start there. Start by implementing an attitude-estimator with just accels and gyros. This will drift in yaw-axis (ie. the axis perpendicular to the ground, or rather parallel to gravity vector). This can be done with a Kalman-Filter or other algorithms. This won't be any good for position estimation, as the estimated position will drift tenths of meters away in just a couple of seconds. Then try implementing optical flow with your camera, which is computationally expensive. Actually this alone could be a solution, but with less accuracy than with additional data from an IMU. Good luck. EDIT: I recently found this - it may be helpful to you. If there is not a lot of noise (due to vibration), this would work (I'm on a quadrotor UAV and it unfortunately doesn't work for me).
{ "language": "en", "url": "https://stackoverflow.com/questions/7570202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to configure an Ultra Sonic Sensor in Matlab? I would like to Configure an ultrasonic sensor for triggering purpose in matlab. How to configure the ultrasonic sensor for triggering Video capturing device ? A: you'll have to configure & access your device via the data acquisition toolbox.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Organizing application in layers I’m developing a part of an application, named A. The application I want to plug my DLL into, called application B is in vb 6, and my code is in vb.net. (Application B will in time be converted to vb.net) My main question i, how is the best way for me to organize my code (application A)? I want to split application A into layers (Service, Business, Data access), so it will be easy to integrate application A into B when B is converted to vb.net. I also want to learn about all the topics like layered architecture, patterns, inversion of dependency, entity framework and so on. Although my application (A) is small I want to organize my code in the best way. The application I’m working with (A) is using web services for authenticating users and for sending schema to an organization. The user of application B is selecting a menu point in application B and then some functions in my application A is called. In application A I have an auto generated schema class from an xsd schema. I fill this schema object with data and serialize the object to a memory string (is it a good solution to use memory string, I don’t have to save the data yet), wrap the xml inside a CDATA block and return the CDATA block as a string and assign the CDATA block to a string property of a web service. I am also using Entity framework for database communication (to learn how this is done for the future work with application B). I have two entities in my .edmx, User and Payer. I also want to use the repository pattern (is this a good choice?) to make a façade between the DAL and the BLL. My application has functions for GeneratingSchema (filling the schema object with data), GetSchemaContent, GetSchemaInformation, GenerateCDATABlock, WriteToTextFile, MemoryStreamToString, EncryptData and some functions that uses web services, like SendShema, AuthenticateUser, GetAvalibelServises and so on. I’m not sure where I should put it all? I think I have to have some Interfaces like IRepository, ISchema (contract for the auto generated schema class, how can I do this?) ICryptoManager, IFileManager and so on, and classes that implements the interfaces. My DAL will be the Entity framework. And I want a repository façade in my BLL (IRepository, UserRepository, PayerRepository) and classes for management (like the classes I have mention above) holding functions like WriteToFile, EncryptData ….. Is this a good solution (do I need a service layer, all my GUI is in application B) and how can I organize my layers, interfaces, classes an functions in Visual Studio? Thanks in advance. A: This is one heck of a question, thought I might try to chip away at a few parts for you so there's less for the next guy to answer... For application B (VB6) to call application/assemblies A, I'm going to assume you're exposing the relevant parts of App A as COM Components, using ComVisibleAttributes and similar, much like described in this artcle. I only know of one other way (WCF over COM) but I've never tried it myself. Splitting your solution(s) into various tiers and layers is a very subjective/debatable topic, and will always come down to a combination of personal preference, business requirements, time available, etc. However, regardless of the depth of your tiers and layers, it is good to understand the how and the why. To get you started, here's a couple articles: * *Wikipedia's general overview on "Multitier Architectures" *MSDN's very own "Building an N-Tier Application in .Net" Inversion of Control is also a very good pattern to get into right now, with ever increasing (and brilliant!) resources becoming available to the .Net platform, it's definitely worth infesting some time to learn. Although I haven't explored the full extent of IoC, I do love dependency injection(a type of IoC if I understand correctly though people seem to muddle the IoC/DI terms quite a lot). My personal preference for DI right now is the open source Ninject project, which has plenty of resources online and a reasonable wiki section talking you through the various aspects. There are many more takes on DI and IoC, so I don't want to even attempt to provide you a comprehensive list for fear of being flamed for missing out somebody's favourite. Just have a search, see which you like the look of and have a play with it. Make sure to try a couple if you have the time. Again, the Repository Pattern - often complemented well by the Unit of Work Pattern are also great topics to mull over for hours. I've seen a lot of good examples out on the inter-webs, and as many bad examples. My only advice here is to try it for yourself... see what works for you, develop a version of the patterns that suits you best and try to keep things consistent for maintainability. For organising all these tiers and layers in VS, I recommend trying to keep all your independent tiers/layers in their own Solution Folders (r-click the Solution, Add New Solution Folder), or in some cases (larger projects) there own solutions and preferably an automated build service to update dependent projects with up to date assemblies as required. Again, a broad subject and totally down to personal preference. Just keep an eye out when designing your application for potential upcoming Circular References. So, I'm afraid that doesn't even slightly answer your question, but hopefully provides you with some resources to check out and a few hours of reading. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7570209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASP.NET MVC 3 Razor - Windows Authentication Failing Every Request I've been fighting this issue for far to long. Basically, I'm building a corporate intranet site (first one in MVC 3) and I cannot get any authorization checks to function. Even the basic "Intranet" project type fails to work. Interestingly, the "Welcome domain\username" works fine so I know that it is getting partial AD info. Here is my process for the most basic setup that is failing: Login as domain user on a Windows 7 development workstation Using VS2010 fully patched -> Create New Project -> ASP.NET MVC 3 -> Intranet Application Right Click Project -> Use IIS Express Properties of Project -> Disable Anonymous Access, Enable Windows Authentication Modify web.config to add: <add key="autoFormsAuthentication" value="false" /> Verify web.config contains: <authentication mode="Windows" /> <authorization> <deny users="?" /> </authorization> Modify default HomeController where Group1 and Group2 are verified and working groups in other applications: HomeController using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVC3AuthTest001.Controllers { public class HomeController : Controller { public ActionResult Index() { Boolean isAdmin01 = User.IsInRole("Group1"); Boolean isAdmin02 = User.IsInRole("Group2"); ViewBag.Message = "Welcome to ASP.NET MVC!" + " Admin: " + isAdmin01 + " EACAdmin: " + isAdmin02; return View(); } } } Run the code and the following is displayed: Welcome to ASP.NET MVC! Group1: False Group2: False Both should be true since I am member of both groups. In addition all [Authorize(Roles = @"Group1")] Verifications fail in the main application resulting in empty screens. I would normally assume a network issue, but the same code running in an MVC 2 application works exactly as expected with the groups. Deploying the application to our development server (production configuration, IIS 7 on Win2008 Server) also fails to work as expected. I'm at wit's end... Is there some step that I'm missing? A: I would first take a look at the following: what does Roles.GetRolesForUser() return? This should be Group1 and Group2 but is probably something else. Second, you may want to check that you actually see a WindowsIdentity as the authenticated identity. Check that Thread.CurrentPrincipal.Identity is a WindowsIdentity and not something else.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detecting with Javascript whether a Browser supports Web Open Font Format (Woff) or not i have to detect with JS (jQuery) wether a browser supports Woff and then add a class to the body. Something like this: if(woffIsSupported){ $('body').addClass('modern'); } is this somehow possible? Thank you for your answers. A: There's a function on this post called isFontFaceSupported that checks for support based on browser features (the good way, i.e. not relying on the user agent string). Copy that function and your code can become: if(isFontFaceSupported()) { $('body').addClass('modern'); } Here is the function from the post: /*! * isFontFaceSupported - v0.9 - 12/19/2009 * http://paulirish.com/2009/font-face-feature-detection/ * * Copyright (c) 2009 Paul Irish * MIT license */ var isFontFaceSupported = (function(){ var fontret, fontfaceCheckDelay = 100; // IE supports EOT and has had EOT support since IE 5. // This is a proprietary standard (ATOW) and thus this off-spec, // proprietary test for it is acceptable. if (!(!/*@cc_on@if(@_jscript_version>=5)!@end@*/0)) fontret = true; else { // Create variables for dedicated @font-face test var doc = document, docElement = doc.documentElement, st = doc.createElement('style'), spn = doc.createElement('span'), wid, nwid, body = doc.body, callback, isCallbackCalled; // The following is a font, only containing the - character. Thanks Ethan Dunham. st.textContent = "@font-face{font-family:testfont;src:url(data:font/opentype;base64,T1RUTwALAIAAAwAwQ0ZGIMA92IQAAAVAAAAAyUZGVE1VeVesAAAGLAAAABxHREVGADAABAAABgwAAAAgT1MvMlBHT5sAAAEgAAAAYGNtYXAATQPNAAAD1AAAAUpoZWFk8QMKmwAAALwAAAA2aGhlYQS/BDgAAAD0AAAAJGhtdHgHKQAAAAAGSAAAAAxtYXhwAANQAAAAARgAAAAGbmFtZR8kCUMAAAGAAAACUnBvc3T/uAAyAAAFIAAAACAAAQAAAAEAQVTDUm9fDzz1AAsD6AAAAADHUuOGAAAAAMdS44YAAADzAz8BdgAAAAgAAgAAAAAAAAABAAABdgDzAAkDQQAAAAADPwABAAAAAAAAAAAAAAAAAAAAAwAAUAAAAwAAAAICmgGQAAUAAAK8AooAAACMArwCigAAAd0AMgD6AAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAEZIRAAAQAAgAC0C7v8GAAABdv8NAAAAAQAAAAAAAAAAACAAIAABAAAAFAD2AAEAAAAAAAAAPAB6AAEAAAAAAAEAAgC9AAEAAAAAAAIABwDQAAEAAAAAAAMAEQD8AAEAAAAAAAQAAwEWAAEAAAAAAAUABQEmAAEAAAAAAAYAAgEyAAEAAAAAAA0AAQE5AAEAAAAAABAAAgFBAAEAAAAAABEABwFUAAMAAQQJAAAAeAAAAAMAAQQJAAEABAC3AAMAAQQJAAIADgDAAAMAAQQJAAMAIgDYAAMAAQQJAAQABgEOAAMAAQQJAAUACgEaAAMAAQQJAAYABAEsAAMAAQQJAA0AAgE1AAMAAQQJABAABAE7AAMAAQQJABEADgFEAEcAZQBuAGUAcgBhAHQAZQBkACAAaQBuACAAMgAwADAAOQAgAGIAeQAgAEYAbwBuAHQATABhAGIAIABTAHQAdQBkAGkAbwAuACAAQwBvAHAAeQByAGkAZwBoAHQAIABpAG4AZgBvACAAcABlAG4AZABpAG4AZwAuAABHZW5lcmF0ZWQgaW4gMjAwOSBieSBGb250TGFiIFN0dWRpby4gQ29weXJpZ2h0IGluZm8gcGVuZGluZy4AAFAASQAAUEkAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAAEYATwBOAFQATABBAEIAOgBPAFQARgBFAFgAUABPAFIAVAAARk9OVExBQjpPVEZFWFBPUlQAAFAASQAgAABQSSAAADEALgAwADAAMAAAMS4wMDAAAFAASQAAUEkAACAAACAAAFAASQAAUEkAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAAAAAAAADAAAAAwAAABwAAQAAAAAARAADAAEAAAAcAAQAKAAAAAYABAABAAIAIAAt//8AAAAgAC3////h/9UAAQAAAAAAAAAAAQYAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAA/7UAMgAAAAAAAAAAAAAAAAAAAAAAAAAAAQAEBAABAQEDUEkAAQIAAQAu+BAA+BsB+BwC+B0D+BgEWQwDi/eH+dP4CgUcAIwPHAAAEBwAkREcAB4cAKsSAAMCAAEAPQA/AEFHZW5lcmF0ZWQgaW4gMjAwOSBieSBGb250TGFiIFN0dWRpby4gQ29weXJpZ2h0IGluZm8gcGVuZGluZy5QSVBJAAAAAAEADgADAQECAxQODvb3h/cXAfeHBPnT9xf90wYO+IgU+WoVHgoDliX/DAmLDAr3Fwr3FwwMHgoG/wwSAAAAAAEAAAAOAAAAGAAAAAAAAgABAAEAAgABAAQAAAACAAAAAAABAAAAAMbULpkAAAAAx1KUiQAAAADHUpSJAfQAAAH0AAADQQAA)}"; doc.getElementsByTagName('head')[0].appendChild(st); spn.setAttribute('style','font:99px _,serif;position:absolute;visibility:hidden'); if (!body){ body = docElement.appendChild(doc.createElement('fontface')); } // the data-uri'd font only has the - character spn.innerHTML = '-------'; spn.id = 'fonttest'; body.appendChild(spn); wid = spn.offsetWidth; spn.style.font = '99px testfont,_,serif'; // needed for the CSSFontFaceRule false positives (ff3, chrome, op9) fontret = wid !== spn.offsetWidth; var delayedCheck = function(){ if (isCallbackCalled) return; fontret = wid !== spn.offsetWidth; callback && (isCallbackCalled = true) && callback(fontret); } addEventListener('load',delayedCheck,false); setTimeout(delayedCheck,fontfaceCheckDelay); } function ret(){ return fontret || wid !== spn.offsetWidth; }; // allow for a callback ret.ready = function(fn){ (isCallbackCalled || fontret) ? fn(fontret) : (callback = fn); } return ret; })(); A: Because it's hard to test that I'm using just the browser detection: //test ie 6, 7, 8 var div = document.createElement("div"); div.innerHTML = "<!--[if lte IE 8]><i></i><![endif]-->"; var isIe8orLower = !!div.getElementsByTagName("i").length; if (!isIe8orLower && !navigator.userAgent.match(/Opera Mini/i)) { $('body').addClass('modern'); } It matches the usage: http://caniuse.com/#feat=woff
{ "language": "en", "url": "https://stackoverflow.com/questions/7570211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: OpenGL ES stencil operations In reference to the problem diskussed in article OpenGL clipping a new question arises. I am implementing the clipping for a node based 2D scene graph. Whenever the clipping boxes are axis aligned I am using the glScissor like proposed in OpenGL clipping. I have sucessfully implemented node clipping of boxes that are axis aligned. It turns out that each node has to intersect it's clipping rectangle with the ones of it's ancestors that use clipping. (That is necessary in case of siblings that are overlapping with the clipping box of an ancestor). The mechanism of intersecting non axis aligned rectangles has to be implemented using the stencil buffer. I started implementing the proposed solution in OpenGL clipping but am having problems with chidrens having clip rects overlaping with theyr ancestors ones. Right now stencil clipping works perfect with only one clipping box. But in case of a child or grand child that intersects with an ancestor the algorith fails, because the intersection of the 2 involved rectangles would be needed here (like in the axis aligned version) as mask and not the full rectangle of the child. I have thought out the following algorithm: The topmost node writes starts with a counter value of 1 and draws it's clipping rectangle filled with 1s into the stencil buffer and renders it's children stencil-testing against 1. Each sibling that also has clipping turned on draws it's bounding rectangle by adding 1 to the stencil buffer and then testing against 2 and so on. Now when a siblings clipping rect overlaps with an ancestors one,the region where they overlap will be filled with 2s, giving perfect clipping when testing against 2. This algorithm can be extended to a maximum of 255 nested clipping nodes. Here comes my questions: How do I perform rendering to the stencil buffer in a way that instead of 1s being writing,1s are added to the current stencil buffer value, whenever rendering is performed. This is my code I use to prepare for rendering to the stencil buffer: glEnable(GL_STENCIL_TEST); glStencilFunc(GL_ALWAYS, ref, mask); glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); I am looking for a setup that will increase the stencil buffers current value by the value of ref instead of writing ref into the buffer. Can someone help me out? A: glStencilFunc(GL_ALWAYS, ref, mask); says that: * *the first argument says that the stencil comparison test always succeeds *the second and third are hence ignored, but in principle would set a constant to compare the value coming from the stencil buffer to and which of the bits are used for comparison glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); has the effect that: * *when the stencil test fails, the new value replaces the old (per the first argument) *when the depth test fails but the stencil test passes, the new value replaces the old (per the second argument) *when the stencil and depth test both pass, the new value replaces the old (per the third argument) So you're setting things up so that everything you try to draw will pass the stencil test, and in any case its value will be copied into the stencil buffer whether it passes the test or not. Probably what you want to do is to change your arguments to glStencilOp so that you perform a GL_INCR on pixels that pass. So in your stencil buffer you'll end up with a '1' anywhere touched by a single polygon, a '2' anywhere that you drew two successive polygons, a '3' anywhere you drew 3, etc. When drawing the user-visible stuff you can then use something like glStencilFunc set to GL_GEQUAL and to compare incoming values to '1', '2', '3' or whatever. If you prefer not to keep track of how many levels deep you are, supposing you have one clip area drawn into the stencil, you can modify it to the next clip area by: * *drawing all new geometry with GL_INCR; this'll result in a stencil buffer where all pixels that were in both areas have a value of '2' and all pixels that were in only one area have a value of '1' *draw a full screen polygon, to pass only with stencil fund GL_GREATER and reference value 0, with GL_DECR. Result is '0' everywhere that was never painted or was painted only once, '1' everywhere that was painted twice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Git restore file date creation after clone on windows I have my remote repository on win server 2003 and after cloninig project from etalon all dates of file creation became dates of cloning. This is OK, but I need to restore dates of creation for files as dates of the first file commit. As I know there is some ways to use post-* scripts such as post-receive. Main idea: * *receive files by git clone/pull *post-receive script modifyes file attributes (created/updated) according to the first file commit date for created and last file commit date for updated. Any ideas how to write it (may be another way)? A: Since you're in Windows, this python script may help: for each file applies the timestamp of the most recent commit where the file was modified: * *Core functionality, with --help, debug messages. Can be run anywhere within the work tree *Full-fledged beast, with lots of options. Supports any repository layout. Below is a really bare-bones version of the script. For actual usage I strongly suggest one of the more robust versions above: #!/usr/bin/env python # Bare-bones version. Current dir must be top-level of work tree. # Usage: git-restore-mtime-bare [pathspecs...] # By default update all files # Example: to only update only the README and files in ./doc: # git-restore-mtime-bare README doc import subprocess, shlex import sys, os.path filelist = set() for path in (sys.argv[1:] or [os.path.curdir]): if os.path.isfile(path) or os.path.islink(path): filelist.add(os.path.relpath(path)) elif os.path.isdir(path): for root, subdirs, files in os.walk(path): if '.git' in subdirs: subdirs.remove('.git') for file in files: filelist.add(os.path.relpath(os.path.join(root, file))) mtime = 0 gitobj = subprocess.Popen(shlex.split('git whatchanged --pretty=%at'), stdout=subprocess.PIPE) for line in gitobj.stdout: line = line.strip() if not line: continue if line.startswith(':'): file = line.split('\t')[-1] if file in filelist: filelist.remove(file) #print mtime, file os.utime(file, (mtime, mtime)) else: mtime = long(line) # All files done? if not filelist: break A: Python3 version, File must be run on same git directory: #!/usr/bin/env python # Bare-bones version. Current dir must be top-level of work tree. # Usage: git-restore-mtime-bare [pathspecs...] # By default update all files # Example: to only update only the README and files in ./doc: # git-restore-mtime-bare README doc import subprocess, shlex import sys, os.path filelist = set() for path in (sys.argv[1:] or [os.path.curdir]): if os.path.isfile(path) or os.path.islink(path): filelist.add(os.path.relpath(path)) elif os.path.isdir(path): for root, subdirs, files in os.walk(path): if '.git' in subdirs: subdirs.remove('.git') for file in files: filelist.add(os.path.relpath(os.path.join(root, file))) mtime = 0 gitobj = subprocess.Popen(shlex.split('git whatchanged --pretty=%at'), stdout=subprocess.PIPE) for line in gitobj.stdout: line = line.decode('ascii').strip() if not line: continue if line.startswith(':'): file = os.path.normpath(line.split('\t')[-1]) if file in filelist: filelist.remove(file) #print mtime, file os.utime(file, (mtime, mtime)) else: mtime = int(line) # All files done? if not filelist: break A: Line: file = line.split('\t')[-1] should be changed: file = os.path.normpath(line.split('\t')[-1]) Because if you clone repository from linux to windows it will be different path separators and condition if file in filelist wil not work
{ "language": "en", "url": "https://stackoverflow.com/questions/7570217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there any reason to write a database column between square brackets? I am maintaining a database created by another person in SQL Server. In one table I found a column whose name is between square brackets. The name of the field is desc and it is stored in the table as [desc]. The other fields are stored without square brackets. Is there any special reason/convention behind this choice? The applications built on top of the Database are developed either in C# or VB.NET. Thanks A: The brackets (or other identifiers in other database engines) are just an explicit way of telling the query engine that this term is an identifier for an object in the database. Common reasons include: * *Object names which contain spaces would otherwise fail to parse as part of the query unless they're wrapped in brackets. *Object names which are reserved words can fail to parse (or, worse, correctly parse and do unexpected things). (I suppose it's also possible that there may be an ever-so-slight performance improvement since the engine doesn't need to try to identify what that item means, it's been explicitly told that it's an object. It still needs to validate that, of course, but it may be a small help in the inner workings.) A: If your names contains either a reserved word (such as SELECT) or spaces, then you need to surround the name with []. In your example, you have [desc], which is short for DESCENDING. A: For example if you have a field that is a keyword e.g [Date] or [Select] or in this case [desc]
{ "language": "en", "url": "https://stackoverflow.com/questions/7570219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I access private constants in class attributes in VB.Net? I have an API that I created and currently utilize successfully in C#. I am trying to create an example of interacting with the API in VB.NET (so that the QA without C# experience can still utilize it for creating automated tests). In C# I do the following [TestingForm(FormName= "Land Lines", CaseType= _caseType , Application= ApplicationNameCodes.WinRDECode, HasActions= true)] public class LandLines : RDEMainForm { // .. Irrelevant Code .. // private const string _caseType = "Land Lines"; } As someone with zero VB.Net experience, I created the following to try and mimic it <TestingForm(Application:=ApplicationNames.WinRDE, FormName:=FORM_NAME, CaseType:=CASE_TYPE, HasActions:=True, IncludeBaseClassActions:=False)> Public Class Permits Inherits TestingBase #Region "Constants" Private Const FORM_NAME As String = "Permits" 'Display name for the test class (in the editor) Private Const CASE_TYPE As String = "permits" 'Unique code for this test class, used when reading/saving test plans #End Region End Class This gives me a compile time error because it claims that FORM_NAME and CASE_TYPE is not defined, even though the class has it defined inside. How can I use the defined constants inside the class in the class attributes? A: I'm actually quite surprised that the C# example compiles (but I checked it indeed does). In VB.Net that type of access (a private member outside the type even in an attribute) is simply not legal. Instead you need to make it Friend and qualify it's access <TestingForm(Application:=ApplicationNames.WinRDE, FormName:=Permits.FORM_NAME, CaseType:=Permits.CASE_TYPE, HasActions:=True, IncludeBaseClassActions:=False)> Public Class Permits Inherits TestingBase Friend Const FORM_NAME As String = "Permits" 'Display name for the test class (in the editor) FriendConst CASE_TYPE As String = "permits" 'Unique code for this test class, used when reading/saving test plans End Class
{ "language": "en", "url": "https://stackoverflow.com/questions/7570221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to guess the nationality of a person from the surname? What approach can I use to predict the nationality of a person from the surname? I have a huge list of texts and surnames of authors. I would like to identify which texts have been written by latin-language speakers and which texts have been written by native english speakers, in order to study if certain writing style patterns are different in one group compared to the other. I have looked in google and in pubmed for a database of surnames, but I could not find any accessible for free. Another approach is to use some regexs, for example ".*ez" to identify some hispanic surnames such as 'rodriguez', but it doesn't get me very far. Do you have any suggestion? Since I will manually revise all the associations after making the prediction, I don't need a great accuracy, but any help or idea will be welcome. A: I don't think you can do this with any degree of reliability. A Rodriguez may well have a Spanish origin name, but could well have been born and brought up anywhere. They could be second generation British, and never have had Spanish spoken around them, and so come into the category of Native English speaker. A: If Actual authors then maybe you can spider amazon and check their 'Author information' details? I don't think you can guess. E.g. Irish last names - there are an estimated 80,000,000 people with Irish heritage however on 4.5 million of these live in Ireland/went through Irish education. A: There is no meaningful way to do this. There is no reason why people with hispanic names cannot be native english speakers. If you are going to revise it anyway, why not use the data you have? A: Assuming you are intending on doing a programmatic comparison of the texts, you have to manually categorize the texts. Incorrect guesses would likely lead you to build a broken algorithm for textual analysis. This will be especially problematic with machine learning, such as artificial neural networks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Access Session in WCF service from WebHttpBinding I'm using WCF service (via WebGet attribute). I'm trying to access Session from WCF service, but HttpContext.Current is null I added AspNetCompatibilityRequirements and edited web.config but I still cannot access session. Is it possible to use WebGet and Session together? Thank you! A: Yes, it is possible. If you edit the web.config: <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> </system.serviceModel> and add the AspNetCompatiblityRequirements, the HttpContext.Current should be available. Check everything once again, maybe you've put the attribute in the wrong place (the interface instead of the class?). A: A RESTfull service with a session? See excellent discussion here: Can you help me understand this? "Common REST Mistakes: Sessions are irrelevant" http://javadialog.blogspot.co.uk/2009/06/common-rest-mistakes.html (point 6) and http://www.peej.co.uk/articles/no-sessions.html Quote from Paul Prescod: Sessions are irrelevant. There should be no need for a client to "login" or "start a connection." HTTP authentication is done automatically on every message. Client applications are consumers of resources, not services. Therefore there is nothing to log in to! Let's say that you are booking a flight on a REST web service. You don't create a new "session" connection to the service. Rather you ask the "itinerary creator object" to create you a new itinerary. You can start filling in the blanks but then get some totally different component elsewhere on the web to fill in some other blanks. There is no session so there is no problem of migrating session state between clients. There is also no issue of "session affinity" in the server (though there are still load balancing issues to continue).
{ "language": "en", "url": "https://stackoverflow.com/questions/7570235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: MVC 3 routing help with dynamic route Im trying to do something like this: routes.MapRoute("Product", "{product}/{id}", new { action = "Product", controller = "Home", product = UrlParameter.Optional, id = UrlParameter.Optional }); It gives me error when im trying to load page 404 i think, Im trying to make the url look like this: www.tables.com/productName/ID . How can i do it without adding a strong type word like this: routes.MapRoute("Product", "Products/{product}/{id}", ... ) rest of the routes: routes.MapRoute("Product", "{product}/{id}", new { action = "Product", controller = "Home", product = UrlParameter.Optional, id = UrlParameter.Optional }); routes.MapRoute("Category", "Category/{category}/{template}", new { action = "Index", controller = "Category", category = UrlParameter.Optional, template = UrlParameter.Optional }); routes.MapRoute("Profile", "Profile/{fullName}", new { action = "Index", controller = "Profile", fullName = UrlParameter.Optional }); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); thanks. A: Your problem is that the Product route will match everything not starting with Category or Profile. I would place the product route just before the default route and use a IRouteConstraint such that it doesn't match non products. Code sample: routes.MapRoute("Category", "Category/{category}/{template}", new { action = "Index", controller = "Category", category = UrlParameter.Optional, template = UrlParameter.Optional }); routes.MapRoute("Profile", "Profile/{fullName}", new { action = "Index", controller = "Profile", fullName = UrlParameter.Optional }); routes.MapRoute("Product", "{product}/{id}", new { action = "Product", controller = "Home", product = UrlParameter.Optional, id = UrlParameter.Optional }, new { product = new ProductRouteConstraint() }); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); And the route constraint: public class ProductRouteConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (routeDirection == RouteDirection.IncomingRequest && parameterName.ToLowerInvariant() == "product") { var productName = values[parameterName] as string; if (productName == null) return false; var productId = values["id"] as string; if (productId == null) returns false; return ProductCatalogue.HasProductById(productId); } return false; } } The ProductCatalogue should obviously be replaced with however you lookup products in your system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Linkify text - Spannable Text in Single Text View - As like Twitter tweet I have a textView and text like "This is the Simple Text with KeyWord and the Link to browse" in the above text i want to make.. clicking on the Link goes to open that URL AND clicking on that KeyWord open a new Activity in my application also, There is an click event for the Whole TextView even. Please help me finding a solution. Thank You, MKJParekh A: I have used the same thing which I answered here in This Question For that I have used this LinkEnabledTextView and that become easy for me to do the task. A: What you can do is create a Custom ClickableSpan as below, class MyCustomSpannable extends ClickableSpan { String Url; public MyCustomSpannable(String Url) { this.Url = Url; } @Override public void updateDrawState(TextPaint ds) { // Customize your Text Look if required ds.setColor(Color.YELLOW); ds.setFakeBoldText(true); ds.setStrikeThruText(true); ds.setTypeface(Typeface.SERIF); ds.setUnderlineText(true); ds.setShadowLayer(10, 1, 1, Color.WHITE); ds.setTextSize(15); } @Override public void onClick(View widget) { } public String getUrl() { return Url; } } And the use its onClick() for opening an Activity or URL. I am adding a demo for loading a URL in WebView. String text = "http://www.google.co.in/"; SpannableStringBuilder stringBuilder = new SpannableStringBuilder(text); MyCustomSpannable customSpannable = new MyCustomSpannable( "http://www.google.co.in/"){ @Override public void onClick(View widget) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(customSpannable.getUrl())); startActivity(intent); } }; stringBuilder.setSpan(customSpannable, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); textView.setText( stringBuilder, BufferType.SPANNABLE ); textView.setMovementMethod(LinkMovementMethod.getInstance()); A: Generate your TextView in the following manner: TextView t3 = (TextView) findViewById(R.id.text3); t3.setText(Html.fromHtml("This is the Simple Text with <a href=\'http://www.google.com\'>Keyword</a> and the <a href='startActivityFromLink://some_info'>Link</a> to browse")); t3.setMovementMethod(LinkMovementMethod.getInstance()); Specify your activity the following way: <activity android:name=".TestActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <data android:scheme="startActivityFromLink" /> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> I think it should work. Might require some tweaking. I did not get the time to test it. Let me know if it works. A: Make Keyword and The link into different TextViews. Then set the TextView.onClickListener() after you do this. This is the easiest way, and more logic way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Apple Push APNS Sometimes not arriving I have an app which is already on the app store, I also have a server that sends push notification to the iphone. My problem is that sometimes, the notification does not arrive to the iphone, and this only happened after there was no apns communication to the apple push server after 2 or 3 hours, but after timeout, it would start working again. it was really random. At first i though the problem was a timeout, then i tried to print out the return value of my ssl_wrap.send() functions, and it did return the length of the strings that was supposed to be sent, meaning, Apple APNS received all my json strings. it is just not broadcasting them to the client phone. I need to keep firing the apns server until it timeouts before making the push notification work again, this is not right. Any ideas? class PushSender: def __init__(self): _sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) _sock.settimeout(2) self.ssl_sock = ssl.wrap_socket( _sock, certfile = theCertfile ) self.ssl_sock.settimeout(1) self.ssl_sock.connect( theHost ) self.counter = 0 self.lastPush = time() def reset(self): Log("Reset APNS"); self.ssl_sock.close() _sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) _sock.settimeout(2) self.ssl_sock = ssl.wrap_socket( _sock, certfile = theCertfile ) self.ssl_sock.settimeout(1) self.ssl_sock.connect( theHost ) self.counter = self.counter + 1; self.lastPush = time() def send(self,token, message, badge, sound): #Log("INIT APNS") payload = {} aps = {} aps["alert"] = str(message) aps["badge"] = badge aps["sound"] = str(sound) payload["aps"] = aps if time() - self.lastPush> 60*30 : # 30 minutes idle reconnect self.reset() try: #Log("Making Message APNS") tokenh = binascii.unhexlify(token) payloadstr = json.dumps(payload, separators=(',',':')) payloadLen = len(payloadstr) fmt = "!cH32sH%ds" % payloadLen command = '\x00' msg = struct.pack(fmt, command, 32, tokenh, payloadLen, payloadstr) except: Log("APNS Data Error " +token+" " +message); return; try: #Log(msg) sent = 0; while sent < len(msg): msg2 = msg[sent:]; justSent = self.ssl_sock.write( msg2 ) #Log(str(len(msg)) + " " + str(justSent)) sent += justSent if justSent==0 : raise socket.error(0,"Send failed") except socket.error, err: Log( "APNS Error: "+str(self.counter)+" "+ str(err) ) self.reset() if self.counter<=2 : self.send(token,message,badge,sound) Log( "APNS DONE"+ str(self.counter)) self.counter = 0; self.lastPush = time()
{ "language": "en", "url": "https://stackoverflow.com/questions/7570242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Resize parent view if subview changes size I'm new to Cocoa and I'm programming a custom InspectorView. A parent view (InspectorView) contains several subviews (InspectorCategories). If I uncollapse a category (subview) I have to resize/relayout my parents view? I found out that this is not possible through autoresize masks - Is this correct? I tried it with resizeSubviewsWithOldSize in my parents view but this gets not called while resizing the subview. How can I achieve this behavior? A: There are two parts to accomplish what I think you want: (a) In the parent view, override the sizeThatFits: method so that it computes a new size that fits around the resized subview. (b) In the subview, override the setFrame: method and after the frame size is changed, it calls [self.superview sizeToFit] to resize the superview, perhaps like this: -(void)setFrame:(CGRect)newFrame { [super setFrame:newFrame]; [self.superview sizeToFit]; } A: No, it is not possible to do through autoresizing masks. Autoresizing mask defines how the view is resized when its superview changes bounds. The subview should let its superview know what size it needs, for example through a delegate call. The superview then should resize itself and the subview.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I render page in IE9 as IE8? I am trying to render a page in IE9 as IE8, as I am seeing some strange rendering in IE9 which I am not sure how to sort out at the moment. I am using this meta tag: <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"> But I am still seeing the rendering issue in IE9, which I don't see in IE8. You should be able to see the issue in IE9 on this page here. The rounded corner blocks generated by a plugin aren't rendering properly. I am wondering if anyone has any suggestions as to what else I can try? A: If you want the exact behaviour of an IE version there is no substitute to using that version. Tools like IETester will let you install and run several versions side-by-side or an even more accurate (but less convenient) method is to use a virtual machine with an image for different versions of IE. You could also try looking at the plugin itself. Perhaps it's using browser sniffing or IE conditional comments to detect the IE version. As a general rule though if you have to resort to X-UA-Compatible you're probably doing something wrong. It's a nasty hack for a nasty browser and in the long run you would be better off designing around it (or leave the rounded corners stuff to the browsers that support it natively).
{ "language": "en", "url": "https://stackoverflow.com/questions/7570250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handle a link in the Android browser/webview to start directly an application I want my application to be opened from a link, by following the directions of Make a link in the Android browser start up my app?. Well, it works fine (most of the time.... this is the reason I am asking for help). My html link is <a href="intent:#Intent;action=com.mark.MY_ACTION;end">Open Application</a> My intent filter is in the form <intent-filter> <action android:name="com.mark.MY_ACTION"/> <category android:name="android.intent.category.DEFAULT"> <category android:name="android.intent.category.BROWSABLE"> </intent-filter> So far so good (I hope). It works fine from m-o-s-t of the browsers. To test the above I wrote a demo activity final WebView webview = new WebView(this); setContentView(webview); webview.loadUrl("http://www.myhomepage.com/"); The page http://www.myhomepage.com/ has some custom links/hrefs (including the inent one). Pressing regular links opens me a browser with those links, but pressing my "special link" (the intnet one) opens a 404 page Web page not available intent:#Intent;action=com.mark.MY_ACTION;end might be temporarily down.... While Diane mentioned in The above link, They allow you to direct the launch to only your app without the user having the option of instead going to the browser or any other app. A: your Intent Filter is some same as mentioned by Diana <activity android:name=".AntonWorld" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <data android:scheme="anton" /> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> So yours should be like: <intent-filter> <data android:scheme="com.mark.MY_ACTION"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> </intent-filter> Did not test if android.intent.category.VIEW is required. Let me know if it works. A: Try my simple trick: public boolean shouldOverrideUrlLoading(WebView view, String url) { if(url.startsWith("classRegister:")) { Intent MnRegister = new Intent(getApplicationContext(), register.class); startActivity(MnRegister); } view.loadUrl(url); return true; } and my html link: <a href="classRegister:true">Go to register.java</a> or you can make < a href="classRegister:true" > <- "true" value for class filename however this script work for mailto link :) if (url.startsWith("mailto:")) { String[] blah_email = url.split(":"); Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); emailIntent.setType("text/plain"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{blah_email[1]}); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, what_ever_you_want_the_subject_to_be)"); Log.v("NOTICE", "Sending Email to: " + blah_email[1] + " with subject: " + what_ever_you_want_the_subject_to_be); startActivity(emailIntent); } A: Add this code in Manifest.xml <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="www.parag-chauhan.com" android:path="/test" android:scheme="http" /> </intent-filter> For test create another project and run below code Intent i = new Intent( Intent.ACTION_VIEW , Uri.parse("http://www.parag-chauhan.com/test") ); startActivity(i); You can also pass parameter in link. For more info, see my blog post Make a link in the Android browser start up my app?
{ "language": "en", "url": "https://stackoverflow.com/questions/7570253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Rails - Store unique data for each open tab/window I have an application that has different data sets depending on which company the user has currently selected (dropdown box on sidebar currently used to set a session variable). My client has expressed a desire to have the ability to work on multiple different data sets from a single browser simultaneously. Hence, sessions no longer cut it. Googling seems to imply get or post data along with every request is the way, which was my first guess. Is there a better/easier/rails way to achieve this? A: You have a few options here, but as you point out, the session system won't work for you since it is global across all instances of the same browser. The standard approach is to add something to the URL that identifies the context in which to execute. This could be as simple as a prefix like /companyx/users instead of /users where you're fetching the company slug and using that as a scope. Generally you do this by having a controller base class that does this work for you, then inherit from that for all other controllers that will be affected the same way. Another approach is to move the company identifying component from the URL to the host name. This is common amongst software-as-a-service providers because it makes sharding your application much easier. Instead of myapp.com/companyx/users you'd have companyx.myapp.com/users. This has the advantage of preserving the existing URL structure, and when you have large amounts of data, you can partition your app by customer into different databases without a lot of headache. The answer you found with tagging all the URLs using a GET token or a POST field is not going to work very well. For one, it's messy, and secondly, a site with every link being a POST is very annoying to work with as it makes navigating with the back-button or forcing a reload troublesome. The reason it has seen use is because out of the box PHP and ASP do not have support routes, so people have had to make do. A: You can create a temporary database table, or use a key-value database and store all data you need in it. The uniq key can be used as a window id. Furthermore, you have to add this window id to each link. So you can receive the corresponding data for each browser tab out of the database and store it in the session, object,... If you have an object, lets say @data, you can store it in the database using Marshal.dump and get it back with Marshal.load.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get access to embedded assembly's metadata using IMetaDataDispenser.OpenScope? I have a .NET solution which consists of several projects. It's possible to say that one of these projects is logically a primary one and all others are secondary. Our team has decided to build the project the next way. The main project will produce an assembly (I'll refer it to as Primary). All other projects' assemblies are Secondary and they will be embedded as a resource into the Primary one. The SourceCodeForExceptionHelper class in the Primary project is responsible for getting the original source code using PDB files on every encountered exception. To do that I use the approach described here. It worked correctly in my separate proof of concept project. But when I tried to move that class into the real solution I've encountered a problem: the IMetaDataDispenser.OpenScope method requires not null reference to assembly file's path. Surely, I haven't such a reference for any of Secondary assembly (because their files are embedded in the Primary). For that reason I can't create an object of the type ISymbolReader and read the source code. How can I solve that problem? By the way, the problem is even worse because we embed only Secondary assemblies without their PDB files (though we will do it if it is necessary). Thanks in advance for any help and advice! A: I don't think you can do this using the .NET Framework builtin functions, as they rely on physical files. However, there is a solution using the Mono Cecil library, as it has an overloads that takes a Stream as input instead of a file path for its symbols reader. Here is an example of a Console app named "TestPdb" which dumps its IL code to the console, including PDB information: using System; using System.IO; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Pdb; namespace TestPdb { class Program { static void Main(string[] args) { // we use a Stream for the assembly AssemblyDefinition asm; using (FileStream asmStream = new FileStream("testpdb.exe", FileMode.Open, FileAccess.Read, FileShare.Read)) { asm = AssemblyDefinition.ReadAssembly(asmStream); } // we use a Stream for the PDB using (FileStream symbolStream = new FileStream("testpdb.pdb", FileMode.Open, FileAccess.Read, FileShare.Read)) { asm.MainModule.ReadSymbols(new PdbReaderProvider().GetSymbolReader(asm.MainModule, symbolStream)); } TypeDefinition type = asm.MainModule.GetType("TestPdb.Program"); foreach (MethodDefinition method in type.Methods) { Console.WriteLine("Method:" + method.Name); foreach (Instruction ins in method.Body.Instructions) { Console.WriteLine(" " + ins); if (ins.SequencePoint != null) { Console.WriteLine(" Url:" + ins.SequencePoint.Document.Url); // see http://blogs.msdn.com/b/jmstall/archive/2005/06/19/feefee-sequencepoints.aspx if (ins.SequencePoint.StartLine != 0xFEEFEE) { Console.WriteLine(" StartLine:" + ins.SequencePoint.StartLine + " StartColumn:" + ins.SequencePoint.StartColumn); Console.WriteLine(" EndLine:" + ins.SequencePoint.EndLine + " EndColumn:" + ins.SequencePoint.EndColumn); } // etc... } } } } } } NOTE: since you only need to read from PDBs, you can recompile the Cecil library defining the READ_ONLY conditional symbol to save some bytes. You can also embed Cecil source code directly in your assemblies, no need to use the .DLL versions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jqgrid .clearGridData() not working in firefox I am using jqgrid 3.6.4. The following is a snippet of my code: jQuery("#lookupTable").clearGridData(true) .addRowData('id',objArray5); The problem that I am facing in firefox and chrome and not in IE, is that the grid is not getting cleared. Hence, every time the above mentioned code is called the data is being appended to the grid (whose id is 'lookupTable'). Could someone tell me why is the grid not getting cleared of its data? A: I remember facing the same issue. I resolved it by reloading grid after clear and then adding the new data. This issue exists even in the recent 4.1.2v also. jQuery("#lookupTable").clearGridData(true).trigger("reloadGrid") .addRowData('id',objArray5); I hope this will solve the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }