qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
56,773,429 | I have created VBA code that automatically copies data from other workbooks, based on a certain date and portfolio, to the active sheet.
I have successfully copied all the information I need, however, I am missing 2 parts.
I want to find the minimum value in a certain range in the other workbook (that I open using the `For` loop) and copy it to my active sheet.
Same goes for the maximum of another range in the opened workbook.
Following is the code I have so far. Somehow the
```
Application.Max(Workbooks(portfolioName).Worksheets("VaR Comparison").Range("J16:J1000"))
```
functions are simply returning a value of zero.
```
Option Explicit
Function MatchHeader(strSearch As String) As Long
Dim myRight As Long, Colcount As Long
myRight = ActiveSheet.Cells(1, ActiveSheet.Columns.Count).End(xlToLeft).Column
For Colcount = 1 To myRight
If ActiveSheet.Cells(1, Colcount) = strSearch Then
MatchHeader = Colcount
Exit For
End If
Next Colcount
End Function
Sub StressTest()
Dim index As Integer
Dim dateColumn As Integer
Dim portfolioDate As String
Dim portfolioName As Variant
Dim ParametricVar As Double
Dim AuM As Double
Dim PreviousVar As Double
Dim PreviousAuM As Double
Dim strPath As String
Dim strFilePath As String
Dim wb As Workbook
Dim sheet As Worksheet
Set wb = ThisWorkbook
Set sheet = ActiveSheet
portfolioDate = InputBox("Please enter date under the following form : YYYY-MM", "Date at the time of Stress Test", "Type Here")
Debug.Print "InputBox provided value is: " & portfolioDate
For index = 26 To Cells(Rows.Count, "B").End(xlUp).Row
dateColumn = MatchHeader(portfolioDate)
portfolioName = ActiveSheet.Range("B" & index & "").Value
strPath = "G:\Risk\Risk Reports\VaR-Stress test\" & portfolioDate & "\" & portfolioName & ""
Set wb = Workbooks.Open(strPath)
ParametricVar = Workbooks(portfolioName).Worksheets("VaR Comparison").Range("B19")
AuM = Workbooks(portfolioName).Worksheets("Holdings - Main View").Range("E11")
PreviousVar = sheet.Cells(index, dateColumn + 7).Value
PreviousAuM = sheet.Cells(index, dateColumn + 9).Value
sheet.Cells(index, dateColumn).Value = ParametricVar / AuM
sheet.Cells(index, dateColumn + 2).Value = AuM
sheet.Cells(index, dateColumn + 1).Value = (ParametricVar - PreviousVar) / PreviousVar
sheet.Cells(index, dateColumn + 3).Value = (AuM - PreviousAuM) / PreviousAuM
sheet.Cells(index, dateColumn + 5).Value = Application.Min(Workbooks(portfolioName).Worksheets("VaR Comparison").Range("P11:AA11"))
sheet.Cells(index, dateColumn + 6).Value = Application.Max(Workbooks(portfolioName).Worksheets("VaR Comparison").Range("J16:J1000"))
wb.Close Savechanges:=False
Next index
End Sub
``` | 2019/06/26 | [
"https://Stackoverflow.com/questions/56773429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11669731/"
]
| Modify & Try:
```
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim Max As Double, Min As Double
'Set the workbook
Set wb = Workbooks("Book1")
'Set the worksheet
Set ws = wb.Worksheets("Sheet1")
'Set range
Set rng = ws.Range("A1:A10")
Max = Application.WorksheetFunction.Max(rng)
Debug.Print Max
Min = Application.WorksheetFunction.Min(rng)
Debug.Print Min
End Sub
``` | One of the answers was very good.
If you're looking to just add a few lines to yours you can try for the minimum:
```
ActiveCell.FormulaR1C1 = "=MIN(R[1]C[-9]:R[37]C[-2])"
Range("CELL YOU WANT IT IN").Select
```
And for max:
```
ActiveCell.FormulaR1C1 = "=MAX(R[1]C[-11]:R[37]C[-4])"
Range("CELL YOU WANT IT IN").Select
``` |
69,286,834 | I am trying to iterate over an object that's in an array of an array, however, I'm not able to display the data in the front-end.
I tried this method:
```
<div *ngFor="let item of events of event | keyvalue">
{{item.key}}:{{item.value}}
</div>
```
and this one:
```
<div *ngFor="let item of events of event | json">
Test: {{item}}
</div>
```
The structure of the JSON data is given in this format.
```
[
[
{
"age": "age3",
"gender": "gender3"
},
{
"age": "age3",
"gender": "gender3"
}
]
]
``` | 2021/09/22 | [
"https://Stackoverflow.com/questions/69286834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9533726/"
]
| with ROWCOUNT this command tells you the number of rows that read in the database from the last query that execute. You can first execute the query (SELECT DISTINCT ID FROM import) to know, how many rows will be affected and validate if is correct
Set @@ROWCOUNT the number of rows affected or read.
here is an example.
```
USE AdventureWorks2012;
GO
UPDATE HumanResources.Employee
SET JobTitle = N'Executive'
WHERE NationalIDNumber = 123456789
IF @@ROWCOUNT = 0
PRINT 'Warning: No rows were updated';
GO
```
[here](https://learn.microsoft.com/en-us/sql/t-sql/functions/rowcount-transact-sql?view=sql-server-ver15) is more information about it. | You can use `COUNT(*)` to count all the rows returned by the query or `COUNT(DISTINCT ID)` to get the count of all the different IDs in your query. I guess this could help you: [https://www.javatpoint.com/mysql-count#:~:text=MySQL%20count()%20function%20is,not%20find%20any%20matching%20rows](https://www.javatpoint.com/mysql-count#:%7E:text=MySQL%20count()%20function%20is,not%20find%20any%20matching%20rows).
Anyway this would be the implementation:
```
CREATE PROCEDURE `UpdateUsers`()
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SHOW ERRORS;
ROLLBACK;
END;
START TRANSACTION;
UPDATE users SET status='A'
WHERE id IN (SELECT DISTINCT ID FROM import);
COMMIT;
SELECT COUNT(DISTINCT ID) FROM import;
END
```
Or in the case you want this value to be in a variable it would be like this:
```
DECLARE COUNT_DISTINCT INT;
SET COUNT_DISTINCT =(SELECT COUNT(DISTINCT ID) FROM import);
``` |
24,600,860 | I have a problem launching Eclipse 4.4 on my Mac. I'm getting the following error:
"Version 1.6.0\_65 of the JVM is not suitable for this product."
I have the latest version installed. When I'm running java -version I'm getting:
```
java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)
```
Here is my eclipse.ini file where I already tried to explicit set the -vm parameter to my jdk1.8:
```
-startup
../../../plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.library
../../../plugins/org.eclipse.equinox.launcher.cocoa.macosx_1.1.200.v20140603-1326
-product
org.eclipse.epp.package.standard.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.7
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m
-Xdock:icon=../Resources/Eclipse.icns
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-vm
/Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/Home/bin/java
``` | 2014/07/06 | [
"https://Stackoverflow.com/questions/24600860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/969109/"
]
| Here's how to fix this error when launching Eclipse:
>
> Version 1.6.0\_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.
>
>
>
1. Go and install [latest JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html)
2. Make sure you have installed 64 bit Eclipse | Your -vm argument seems ok BUT it's position is wrong. According to this [Eclipse Wiki entry](http://wiki.eclipse.org/Eclipse.ini#Specifying_the_JVM) :
>
> The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.
>
>
>
So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0\_65. |
24,600,860 | I have a problem launching Eclipse 4.4 on my Mac. I'm getting the following error:
"Version 1.6.0\_65 of the JVM is not suitable for this product."
I have the latest version installed. When I'm running java -version I'm getting:
```
java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)
```
Here is my eclipse.ini file where I already tried to explicit set the -vm parameter to my jdk1.8:
```
-startup
../../../plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.library
../../../plugins/org.eclipse.equinox.launcher.cocoa.macosx_1.1.200.v20140603-1326
-product
org.eclipse.epp.package.standard.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.7
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m
-Xdock:icon=../Resources/Eclipse.icns
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-vm
/Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/Home/bin/java
``` | 2014/07/06 | [
"https://Stackoverflow.com/questions/24600860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/969109/"
]
| Here's how to fix this error when launching Eclipse:
>
> Version 1.6.0\_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.
>
>
>
1. Go and install [latest JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html)
2. Make sure you have installed 64 bit Eclipse | Please check if you got the x64 edition of eclipse. Someone answered this just [a few hours ago](https://stackoverflow.com/questions/24598465/eclipse-in-os-x-uses-different-version-of-java-than-cli/). |
33,469,666 | In the following class I have defined an `operator()` returning a vector of `return_T`:
```
#include <vector>
template <typename return_T, typename ... arg_T>
class A
{
public:
std::vector<return_T> operator()(arg_T... args);
};
```
This works, except in the case where `return_T = void`, since a `vector<void>` is impossible. So I'll need to define a specialization of `A<void, arg_T>::operator()` somehow. I'm experimenting with the following code:
```
#include <vector>
template <typename return_T, typename ... arg_T>
class A
{
public:
auto operator()(arg_T... args);
};
template<typename return_T, typename... arg_T>
auto A<return_T, arg_T...>::operator()(arg_T... args) -> typename std::enable_if<!std::is_void<return_T>::value, std::vector<return_T>>::type
{ }
template<typename return_T, typename... arg_T>
auto A<void, arg_T...>::operator()(arg_T... args) -> void
{ }
```
But the compiler doesn't like it.
```
error : prototype for 'typename std::enable_if<(! std::is_void<_Tp>::value), std::vector<_Tp> >::type A<return_T, arg_T>::operator()(arg_T ...)' does not match any in class 'A<return_T, arg_T>'
auto A<return_T, arg_T...>::operator()(arg_T... args) -> typename std::enable_if<!std::is_void<return_T>::value, std::vector<return_T>>::type
error : candidate is: auto A<return_T, arg_T>::operator()(arg_T ...)
auto operator()(arg_T... args);
^
error : invalid use of incomplete type 'class A<void, arg_T ...>'
auto A<void, arg_T...>::operator()(arg_T... args) -> void
^
```
Of course, I could easily write a second class with `void operator()`, but I'm curious if it could be done with a single class too. So there's my question: is this possible? | 2015/11/02 | [
"https://Stackoverflow.com/questions/33469666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5434231/"
]
| ***UPDATE*** *this answer is out of date and will not work with Bokeh versions newer than `0.10`*
Please refer to [recent documentation](http://bokeh.pydata.org/en/latest/docs/user_guide/charts.html)
---
---
You're passing invalid input. From the [doc](http://bokeh.pydata.org/en/0.10.0/docs/reference/charts.html):
>
> (dict, OrderedDict, lists, arrays and DataFrames are valid inputs)
>
>
>
This is the example they have on there:
```
from collections import OrderedDict
from bokeh.charts import Bar, output_file, show
# (dict, OrderedDict, lists, arrays and DataFrames are valid inputs)
xyvalues = OrderedDict()
xyvalues['python']=[-2, 5]
xyvalues['pypy']=[12, 40]
xyvalues['jython']=[22, 30]
cat = ['1st', '2nd']
bar = Bar(xyvalues, cat, title="Stacked bars",
xlabel="category", ylabel="language")
output_file("stacked_bar.html")
show(bar)
```
Your `amount` is a `dict_values()` which will not be accepted. I'm not sure what your `bugrlary_dict` is but have that as the `data` for the `Bar()` and I'm assuming your `months` is the label. That should work assuming `len(bugrlary_dict) == 12`
Output from Bokeh's example:
[](https://i.stack.imgur.com/uJuih.png) | In [Bokeh 0.12.5](http://bokeh.pydata.org/en/latest/docs/reference/charts.html#bar), you can do it the following way:
```
from bokeh.charts import Bar, output_file, show
# best support is with data in a format that is table-like
data = {
'sample': ['1st', '2nd', '1st', '2nd', '1st', '2nd'],
'interpreter': ['python', 'python', 'pypy', 'pypy', 'jython', 'jython'],
'timing': [-2, 5, 12, 40, 22, 30]
}
# x-axis labels pulled from the interpreter column, grouping labels from sample column
bar = Bar(data, values='timing', label='sample', group='interpreter',
title="Python Interpreter Sampling - Grouped Bar chart",
legend='top_left', plot_width=400, xlabel="Category", ylabel="Language")
output_file("grouped_bar.html")
show(bar)
```
Output:
[](https://i.stack.imgur.com/l6vye.png)
**Change the parameter in `Bar()` from `group` to `stack` if you want a stacked bar chart** |
6,461,632 | Currently I have a php script that external sites access with a api key. Based on the api key it returns data back in json. I been reading up on nodejs and feel this might be a good use of nodejs since I have noticed a high load/access of the api, though Im still new at this so might be wrong if I am wrong let me know. My question is in my php script I do a lot of checks to determine what information to pass back, using nodejs should I be doing all the checks using javascript or can I still use php with nodejs to extract the information needed to pass back as json?
**EDIT**
the PHP script/API consists of mysql access if that helps at all | 2011/06/23 | [
"https://Stackoverflow.com/questions/6461632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/500805/"
]
| Well it sounds like nodejs would not be the route to go in this case. I will instead go the route of either file based caching or memcache along with continue research to improve the code and db indexes/queries. | I am commenting on the first answer, but it is actually possible to run Node.js on a shared host as long as you have shell access or can compile and upload a compatible build of node. This method uses a library developed by samcday on github (http://github.com/samcday/node-fastcgi-application) and allows Node to respond to FastCGI calls. You do not need to be able to bind to a port on a public IP address and this will work with a virtual host. |
6,461,632 | Currently I have a php script that external sites access with a api key. Based on the api key it returns data back in json. I been reading up on nodejs and feel this might be a good use of nodejs since I have noticed a high load/access of the api, though Im still new at this so might be wrong if I am wrong let me know. My question is in my php script I do a lot of checks to determine what information to pass back, using nodejs should I be doing all the checks using javascript or can I still use php with nodejs to extract the information needed to pass back as json?
**EDIT**
the PHP script/API consists of mysql access if that helps at all | 2011/06/23 | [
"https://Stackoverflow.com/questions/6461632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/500805/"
]
| As an alternative to memcache you can cache inside the Node.js process.
```
app.get('/:apitype/:action/:apikey', function( req, res ) {
if( checkApiKey(req.params.apikey) === false ) {
return res.send('Invalid API key');
}
if( api[req.params.apitype][req.params.action].cache ) {
return res.send( api[req.params.apitype][req.params.action].cache );
}
query( req.params.apitype, req.params.action, function ( result ) {
api[req.params.apitype][req.params.action].cache = JSON.stringify(result);
res.send( api[req.params.apitype][req.params.action].cache );
setTimeout( function () {
api[req.params.apitype][req.params.action].cache = null;
}, 5 * 60 * 1000);
});
});
``` | I am commenting on the first answer, but it is actually possible to run Node.js on a shared host as long as you have shell access or can compile and upload a compatible build of node. This method uses a library developed by samcday on github (http://github.com/samcday/node-fastcgi-application) and allows Node to respond to FastCGI calls. You do not need to be able to bind to a port on a public IP address and this will work with a virtual host. |
47,504,879 | I am trying to label my results based on two properties of my query set which falls within each combination of two threshold of another query. Here is a piece of code for clarification:
```
threshold_query = threshold.objects.all()
main_query = main.ojbects.values(
'Athreshold', 'Bthreshold'
).annotate(
Case(
When(
Q(Avalue__lte=threshold_query['Avalue'])
& Q(Bvalue__lte=threshold_query['Bvalue']),
then=Value(threshold_query['label'])
...
)
)
)
```
the model for thresholds is like:
```
class threshold(models.Model):
Avalue = models.FloatField(default=0.1)
Bvalue = models.FloatField(default=0.3)
label = models.CharField(default='Accepted')
```
so there is a matrix that decides the labels, for example if there are two thresholds {'Avalue': 0.4, 'Bvalue': 0.6, 'label': 'rejected'} and {'Avalue': 0.7, 'Bvalue': 0.7, 'label': Accepted} if you demonstrate the Avalues on horizontal axis (naming the row of the matrix) and Bvalues on vertical axis (naming the column of the matrix), the combination of these two thresholds decides the value of the cell which would be 'Accepted' or 'Rejected'.
Is it possible to obtain what is in my mind using one query?
my purpose is to minimize the number of queries due to enormity of Data. | 2017/11/27 | [
"https://Stackoverflow.com/questions/47504879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3993575/"
]
| Use this..
>
>
> ```
> <script>
> $('#sms_form').bootstrapValidator({
> // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
> feedbackIcons: {
> valid: 'glyphicon glyphicon-ok',
> invalid: 'glyphicon glyphicon-remove',
> validating: 'glyphicon glyphicon-refresh'
> },
> fields: {
> message:{
> validators: {
> regexp: {
> regexp: /^[a-zA-Z0-9_\.\s]+$/,
> message: 'The message can only consist of alphabetical, number, dot and underscore'
> },
> notEmpty: {
> message: 'Please supply your message'
> }
> }
> }
> }
> .on('success.field.fv', function(e, data) {
> $( "form" ).submit();
> });
> });
> </script>
>
> ```
>
> | Wasn't this a fun one to play with.
Long story Short.
You need to have your JS After you load your jquery.js file ( which is all part of your Bootstrap js files). Your current JS works.
You also need it after the bootstrapValidator.js ,if you don't, you will need to wrap your js in...
```
$(document).ready(function () {
// JS Code here if this is rendered before bootstrapValidator.min.js
})
```
The trick here is to watch the console messages in your Browsers Developer tools...
Just saying, it don't work, without looking at the console messages won't be helpful.
If you have no clue as to what I am on about I'll clarify it later.
>
> UPDATE: This is the test code I used to investigate your issue.
>
>
>
**Test View - views/form\_validator\_view.php**
```
<!doctype html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
<h1>Hello, world!</h1>
<div class="container">
<form class="" data-toggle="validator" role="form" id="sms_form" method="Post" action="<?php echo site_url('sms/sendIndividualMsg/' . 1) ?>">
<div class="form-group">
<label for="message"><strong>Message</strong></label>
<div class="col-md-12">
<textarea class="form-control" id="message" name="message" placeholder=" Your Message"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-xs-9 col-xs-offset-3">
<button type="submit" class="btn btn-primary" name="signup" value="Sign up">Submit</button>
</div>
</div>
</form>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script src="//oss.maxcdn.com/jquery.bootstrapvalidator/0.5.2/js/bootstrapValidator.min.js"></script>
<script>
$(document).ready(function () {
// JS Code here if this is rendered before bootstrapValidator.min.js
})
// $(document).ready(function () {
$('#sms_form').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
message: {
validators: {
regexp: {
regexp: /^[a-zA-Z0-9_\.\s]+$/,
message: 'The message can only consist of alphabetical, number, dot and underscore'
},
notEmpty: {
message: 'Please supply your message'
}
}
}
}
});
// })
</script>
</body>
</html>
```
**Test Controller - controllers/Sms.php**
```
<?php
class Sms extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
}
public function index() {
$this->load->view('form_validator_view');
}
public function sendIndividualMsg($id) {
echo "The ID is $id";
var_dump($_POST);
}
}
``` |
19,204 | There is a study that users do not go past top 3-5 pages in a Google search, on which predominantly everybody would agree. If you would get your best results - it means to be within the top 5 page at least. Merely users abandon to search or change the query if the results do not get laid in the first few pages. In that case, why do we have MORE search results, pages 10, 11, 12, ... and beyond? What meaningful impact does it serve when users rarely do get to that page? Is there any useful content lying far deep? | 2012/03/25 | [
"https://ux.stackexchange.com/questions/19204",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11604/"
]
| You have to realize that Google's or Bing's job as search engine is not worry about the behavior of their users with regards to how deep they are willing to dig to get results.
Their role is provide relevant search results based upon the keywords entered and the matching SEO of the site.Though Google (and Bing) use [algorithms](http://www.smallbusinesssem.com/10-likely-elements-of-googles-local-search-algorithm/519/) to determine the optimal search results based upon the keywords entered, the success of the search results depend on two factors
1. The keywords entered : Though Google does try to help out by features like Google instant,spell correct and autocomplete,it cant account for all unique cases for which the user is searching for and if the users keywords are not specific enough, he might not get the search results he wants
2. The SEO of the site : If the site has relevant content but doesnt have a decent SEO you might not find it at the top of the pile (within 10 pages) especially if its about a common topic
You also need to account for the fact that the popularity of Google and Bing depend upon the number of pages they index and hence they need to show as many search results as
possible.


Another reason Google provides the full number of search results, sometimes in the millions, to provide the user with an idea of how much more the search query would need to be refined. This encourages the user to make better use of the engine by making them do smarter searches and they account for people using incorrect keywords or having very specific or ambiguous requirements. However they do restrict the number to 1000 results as going beyond a thousand would eat up their resources because they have to rank each hit, and crawling the Net every day, several times a day, makes that unrealistic and unnecessary.

**Bottom line**: Its not really about UX,but its about showing people that there is a ton of information out there about any subject they choose to search for and Google/Bing can help them find it for them and also provide incentive's to users to perform smarter search results after a while
That said here is a nice article on how to [build an effective search results page](http://www.uxbooth.com/blog/create-effective-search-result-pages/) | Users often do not find a good result in the first page - this depends on how specific of a result they are looking for and how many false matches fit their query.
I personally often go through a few pages of search results before refining the search query to try and improve the quality of the results. |
19,204 | There is a study that users do not go past top 3-5 pages in a Google search, on which predominantly everybody would agree. If you would get your best results - it means to be within the top 5 page at least. Merely users abandon to search or change the query if the results do not get laid in the first few pages. In that case, why do we have MORE search results, pages 10, 11, 12, ... and beyond? What meaningful impact does it serve when users rarely do get to that page? Is there any useful content lying far deep? | 2012/03/25 | [
"https://ux.stackexchange.com/questions/19204",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11604/"
]
| Why not show them? The data is there, and on the first dozens of pages it's still pretty relevant. In terms of UI it doesn't cost you anything because you're using the same paging control that lets the users navigate through the first pages. If you tell your users that you've got millions of results but you only let them view a hundred, it makes them wonder why. For an "arbitrary" cut-off, 100 pages is very reasonable, while 10 or 20 is a bit strange. | Users often do not find a good result in the first page - this depends on how specific of a result they are looking for and how many false matches fit their query.
I personally often go through a few pages of search results before refining the search query to try and improve the quality of the results. |
19,204 | There is a study that users do not go past top 3-5 pages in a Google search, on which predominantly everybody would agree. If you would get your best results - it means to be within the top 5 page at least. Merely users abandon to search or change the query if the results do not get laid in the first few pages. In that case, why do we have MORE search results, pages 10, 11, 12, ... and beyond? What meaningful impact does it serve when users rarely do get to that page? Is there any useful content lying far deep? | 2012/03/25 | [
"https://ux.stackexchange.com/questions/19204",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11604/"
]
| It's a way to improve search result quality by letting users explore information found in long tail of the result.
More importantly, having long tail mitigates a dangerous feedback loop in which the first few pages results get disproportionately higher ranking. | Users often do not find a good result in the first page - this depends on how specific of a result they are looking for and how many false matches fit their query.
I personally often go through a few pages of search results before refining the search query to try and improve the quality of the results. |
19,204 | There is a study that users do not go past top 3-5 pages in a Google search, on which predominantly everybody would agree. If you would get your best results - it means to be within the top 5 page at least. Merely users abandon to search or change the query if the results do not get laid in the first few pages. In that case, why do we have MORE search results, pages 10, 11, 12, ... and beyond? What meaningful impact does it serve when users rarely do get to that page? Is there any useful content lying far deep? | 2012/03/25 | [
"https://ux.stackexchange.com/questions/19204",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11604/"
]
| Search engines such as Google or Bing devote their resources to having high-precision queries for common, precision-oriented information needs. Think of them as recommender systems for popular documents. This works great when you're interested (as many people seem to be) in what Britney Spears is up to, for example.
If, however, a user's information need is recall-oriented, then settling for one of the top few results may not be appropriate. Think about searching for symptoms related to a disease, doing research, or trying to make a new connection between seemingly unrelated concepts. These kinds of searches may require people to dig into the results more deeply. | Users often do not find a good result in the first page - this depends on how specific of a result they are looking for and how many false matches fit their query.
I personally often go through a few pages of search results before refining the search query to try and improve the quality of the results. |
19,204 | There is a study that users do not go past top 3-5 pages in a Google search, on which predominantly everybody would agree. If you would get your best results - it means to be within the top 5 page at least. Merely users abandon to search or change the query if the results do not get laid in the first few pages. In that case, why do we have MORE search results, pages 10, 11, 12, ... and beyond? What meaningful impact does it serve when users rarely do get to that page? Is there any useful content lying far deep? | 2012/03/25 | [
"https://ux.stackexchange.com/questions/19204",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11604/"
]
| You have to realize that Google's or Bing's job as search engine is not worry about the behavior of their users with regards to how deep they are willing to dig to get results.
Their role is provide relevant search results based upon the keywords entered and the matching SEO of the site.Though Google (and Bing) use [algorithms](http://www.smallbusinesssem.com/10-likely-elements-of-googles-local-search-algorithm/519/) to determine the optimal search results based upon the keywords entered, the success of the search results depend on two factors
1. The keywords entered : Though Google does try to help out by features like Google instant,spell correct and autocomplete,it cant account for all unique cases for which the user is searching for and if the users keywords are not specific enough, he might not get the search results he wants
2. The SEO of the site : If the site has relevant content but doesnt have a decent SEO you might not find it at the top of the pile (within 10 pages) especially if its about a common topic
You also need to account for the fact that the popularity of Google and Bing depend upon the number of pages they index and hence they need to show as many search results as
possible.


Another reason Google provides the full number of search results, sometimes in the millions, to provide the user with an idea of how much more the search query would need to be refined. This encourages the user to make better use of the engine by making them do smarter searches and they account for people using incorrect keywords or having very specific or ambiguous requirements. However they do restrict the number to 1000 results as going beyond a thousand would eat up their resources because they have to rank each hit, and crawling the Net every day, several times a day, makes that unrealistic and unnecessary.

**Bottom line**: Its not really about UX,but its about showing people that there is a ton of information out there about any subject they choose to search for and Google/Bing can help them find it for them and also provide incentive's to users to perform smarter search results after a while
That said here is a nice article on how to [build an effective search results page](http://www.uxbooth.com/blog/create-effective-search-result-pages/) | Why not show them? The data is there, and on the first dozens of pages it's still pretty relevant. In terms of UI it doesn't cost you anything because you're using the same paging control that lets the users navigate through the first pages. If you tell your users that you've got millions of results but you only let them view a hundred, it makes them wonder why. For an "arbitrary" cut-off, 100 pages is very reasonable, while 10 or 20 is a bit strange. |
19,204 | There is a study that users do not go past top 3-5 pages in a Google search, on which predominantly everybody would agree. If you would get your best results - it means to be within the top 5 page at least. Merely users abandon to search or change the query if the results do not get laid in the first few pages. In that case, why do we have MORE search results, pages 10, 11, 12, ... and beyond? What meaningful impact does it serve when users rarely do get to that page? Is there any useful content lying far deep? | 2012/03/25 | [
"https://ux.stackexchange.com/questions/19204",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11604/"
]
| You have to realize that Google's or Bing's job as search engine is not worry about the behavior of their users with regards to how deep they are willing to dig to get results.
Their role is provide relevant search results based upon the keywords entered and the matching SEO of the site.Though Google (and Bing) use [algorithms](http://www.smallbusinesssem.com/10-likely-elements-of-googles-local-search-algorithm/519/) to determine the optimal search results based upon the keywords entered, the success of the search results depend on two factors
1. The keywords entered : Though Google does try to help out by features like Google instant,spell correct and autocomplete,it cant account for all unique cases for which the user is searching for and if the users keywords are not specific enough, he might not get the search results he wants
2. The SEO of the site : If the site has relevant content but doesnt have a decent SEO you might not find it at the top of the pile (within 10 pages) especially if its about a common topic
You also need to account for the fact that the popularity of Google and Bing depend upon the number of pages they index and hence they need to show as many search results as
possible.


Another reason Google provides the full number of search results, sometimes in the millions, to provide the user with an idea of how much more the search query would need to be refined. This encourages the user to make better use of the engine by making them do smarter searches and they account for people using incorrect keywords or having very specific or ambiguous requirements. However they do restrict the number to 1000 results as going beyond a thousand would eat up their resources because they have to rank each hit, and crawling the Net every day, several times a day, makes that unrealistic and unnecessary.

**Bottom line**: Its not really about UX,but its about showing people that there is a ton of information out there about any subject they choose to search for and Google/Bing can help them find it for them and also provide incentive's to users to perform smarter search results after a while
That said here is a nice article on how to [build an effective search results page](http://www.uxbooth.com/blog/create-effective-search-result-pages/) | It's a way to improve search result quality by letting users explore information found in long tail of the result.
More importantly, having long tail mitigates a dangerous feedback loop in which the first few pages results get disproportionately higher ranking. |
19,204 | There is a study that users do not go past top 3-5 pages in a Google search, on which predominantly everybody would agree. If you would get your best results - it means to be within the top 5 page at least. Merely users abandon to search or change the query if the results do not get laid in the first few pages. In that case, why do we have MORE search results, pages 10, 11, 12, ... and beyond? What meaningful impact does it serve when users rarely do get to that page? Is there any useful content lying far deep? | 2012/03/25 | [
"https://ux.stackexchange.com/questions/19204",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11604/"
]
| You have to realize that Google's or Bing's job as search engine is not worry about the behavior of their users with regards to how deep they are willing to dig to get results.
Their role is provide relevant search results based upon the keywords entered and the matching SEO of the site.Though Google (and Bing) use [algorithms](http://www.smallbusinesssem.com/10-likely-elements-of-googles-local-search-algorithm/519/) to determine the optimal search results based upon the keywords entered, the success of the search results depend on two factors
1. The keywords entered : Though Google does try to help out by features like Google instant,spell correct and autocomplete,it cant account for all unique cases for which the user is searching for and if the users keywords are not specific enough, he might not get the search results he wants
2. The SEO of the site : If the site has relevant content but doesnt have a decent SEO you might not find it at the top of the pile (within 10 pages) especially if its about a common topic
You also need to account for the fact that the popularity of Google and Bing depend upon the number of pages they index and hence they need to show as many search results as
possible.


Another reason Google provides the full number of search results, sometimes in the millions, to provide the user with an idea of how much more the search query would need to be refined. This encourages the user to make better use of the engine by making them do smarter searches and they account for people using incorrect keywords or having very specific or ambiguous requirements. However they do restrict the number to 1000 results as going beyond a thousand would eat up their resources because they have to rank each hit, and crawling the Net every day, several times a day, makes that unrealistic and unnecessary.

**Bottom line**: Its not really about UX,but its about showing people that there is a ton of information out there about any subject they choose to search for and Google/Bing can help them find it for them and also provide incentive's to users to perform smarter search results after a while
That said here is a nice article on how to [build an effective search results page](http://www.uxbooth.com/blog/create-effective-search-result-pages/) | Search engines such as Google or Bing devote their resources to having high-precision queries for common, precision-oriented information needs. Think of them as recommender systems for popular documents. This works great when you're interested (as many people seem to be) in what Britney Spears is up to, for example.
If, however, a user's information need is recall-oriented, then settling for one of the top few results may not be appropriate. Think about searching for symptoms related to a disease, doing research, or trying to make a new connection between seemingly unrelated concepts. These kinds of searches may require people to dig into the results more deeply. |
19,204 | There is a study that users do not go past top 3-5 pages in a Google search, on which predominantly everybody would agree. If you would get your best results - it means to be within the top 5 page at least. Merely users abandon to search or change the query if the results do not get laid in the first few pages. In that case, why do we have MORE search results, pages 10, 11, 12, ... and beyond? What meaningful impact does it serve when users rarely do get to that page? Is there any useful content lying far deep? | 2012/03/25 | [
"https://ux.stackexchange.com/questions/19204",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11604/"
]
| Why not show them? The data is there, and on the first dozens of pages it's still pretty relevant. In terms of UI it doesn't cost you anything because you're using the same paging control that lets the users navigate through the first pages. If you tell your users that you've got millions of results but you only let them view a hundred, it makes them wonder why. For an "arbitrary" cut-off, 100 pages is very reasonable, while 10 or 20 is a bit strange. | It's a way to improve search result quality by letting users explore information found in long tail of the result.
More importantly, having long tail mitigates a dangerous feedback loop in which the first few pages results get disproportionately higher ranking. |
19,204 | There is a study that users do not go past top 3-5 pages in a Google search, on which predominantly everybody would agree. If you would get your best results - it means to be within the top 5 page at least. Merely users abandon to search or change the query if the results do not get laid in the first few pages. In that case, why do we have MORE search results, pages 10, 11, 12, ... and beyond? What meaningful impact does it serve when users rarely do get to that page? Is there any useful content lying far deep? | 2012/03/25 | [
"https://ux.stackexchange.com/questions/19204",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11604/"
]
| Search engines such as Google or Bing devote their resources to having high-precision queries for common, precision-oriented information needs. Think of them as recommender systems for popular documents. This works great when you're interested (as many people seem to be) in what Britney Spears is up to, for example.
If, however, a user's information need is recall-oriented, then settling for one of the top few results may not be appropriate. Think about searching for symptoms related to a disease, doing research, or trying to make a new connection between seemingly unrelated concepts. These kinds of searches may require people to dig into the results more deeply. | It's a way to improve search result quality by letting users explore information found in long tail of the result.
More importantly, having long tail mitigates a dangerous feedback loop in which the first few pages results get disproportionately higher ranking. |
214,983 | By default the vertical spacing on sections is quite large with the pandoc default.latex template. Is there a way to pass an argument to reduce the size of the spacing?
I see that there is a titlesec package, however I'd like to keep using the default.latex template if possible without having to modify it.
IF I need to modify the template, is there a clever way to do it rather than copying the entire default.latex template? | 2014/12/02 | [
"https://tex.stackexchange.com/questions/214983",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/56640/"
]
| You can also use the YAML header to put commands in the preamble:
```
---
header-includes:
- \usepackage{titlesec}
- \titleformat*{\section}{\itshape}
---
``` | From the [User Guide](http://johnmacfarlane.net/pandoc/README.html#general-writer-options):
>
> **-H FILE, --include-in-header=FILE**
>
>
> Include contents of FILE, verbatim, at the end of the header.
> [...] This option can be used repeatedly to include multiple files in the header. They will be included in the order specified. Implies --standalone.
>
>
>
You can then put your customisation code in `FILE`.
The code inside `FILE` will be inserted at the end of the preamble **before** `\begin{document}` so you can import additional packages using `\usepackage`.
Additionally you can use
>
> **-B FILE, --include-before-body=FILE**
>
>
> Include contents of FILE, verbatim, at the beginning of the document body (e.g. after [...] the
> \begin{document} command in LaTeX). [...] This option can be used
> repeatedly to include multiple files. They will be included in the
> order specified. Implies --standalone.
>
>
> **-A FILE, --include-after-body=FILE**
>
>
> Include contents of FILE, verbatim, at the end of the document body (before [...] the \end{document} command in
> LaTeX). This option can be be used repeatedly to include multiple
> files. They will be included in the order specified. Implies
> --standalone.
>
>
> |
29,669,443 | I've been coding a project in AngularJS to start learning the framework, currently I'm using the angular-material library and I'm trying to implement a sidenav similar to their demo here: <https://material.angularjs.org/#/demo/material.components.sidenav>
Unfortunately the $mdMedia('gt-md') call within the html below is always returning false (I'm opening it on a laptop screen so it should be true) but if I log the return from $mdMedia('gt-md') in the relevant angular controller it returns true.
```
<md-sidenav class="md-sidenav-left md-whiteframe-z2" md-component-id="left" md-is-locked-open="$mdMedia('gt-md')">
```
Can anyone shed any light on why I'm seeing this behaviour? I've been struggling with it for a number of days now. | 2015/04/16 | [
"https://Stackoverflow.com/questions/29669443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4500832/"
]
| After looking at the link posted by @ExpertSystem adding the $mdMedia service to the $rootscope allowed me to use $mdMedia directly from my HTML code.
The problem arose because as $mdMedia is a service it is not available to the view unless it is available on the scope.
Thanks all for your help!! | If you are using "angular-material": "0.8.1" or below in yr project. Change above code to this
```
<md-sidenav
class="md-sidenav-left md-whiteframe-z2"
md-component-id="left"
md-is-locked-open="$media('gt-md')">
``` |
3,586,955 | I've got an elegant system set up using Core Data where any time a property of a model object is changed it is automatically reflected in its associated view using key-value observing but I have ran into a problem using undo.
The problem occurs when I have deleted a model object. The associated view is destroyed along with all the key-value observing when this occurs. The user suddenly decides that the deletion was a bad idea and issues an undo command restoring the model object. At this point the key-value observing has been destroyed and I can't seem to find a nice way to figure out which model object has been brought back from the dead and set everything up again.
The current solution I've thought of is registering for the NSUndoManagerDidUndoChangeNotification and then manually going through my Core Data model objects and seeing which ones do not have an associated view. I figure there must be a way to just know which particular object has been brought back though and thought this approach would be overkill.
I've also thought about creating an undo group where the removed view is re-added when the model object reappears but I would like to keep my undo manager related to the model only if that is possible.
I guess the solution I'm looking for is having the undo manager say, "Hey! Anybody who is interested listen up! I just did an undo and here is the Core Data model object that has been resurrected! Do with it what you will!" and then me setting up the view as if a new model object has been created.
Any ideas or guidance? | 2010/08/27 | [
"https://Stackoverflow.com/questions/3586955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281358/"
]
| The following method of [NSManagedObject](http://developer.apple.com/mac/library/documentation/cocoa/reference/CoreDataFramework/Classes/NSManagedObject_Class/Reference/NSManagedObject.html#//apple_ref/occ/instm/NSManagedObject/awakeFromSnapshotEvents:) could be the the right point to setup observings again:
```
- (void)awakeFromSnapshotEvents:(NSSnapshotEventType)flags
```
It is sent to a NSManagedObject after undo/redo operations | >
> The problem occurs when I have deleted
> a model object. The associated view is
> destroyed along with all the key-value
> observing when this occurs.
>
>
>
I'm not sure what you mean by that but a view should not be so directly tied to the model that the view object itself dies when the model deletes something. The controller should be handling that and should be able to reverse it.
It sounds like you need to register the controller for one of the [undo manager notifications.](http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSUndoManager_Class/Reference/Reference.html#//apple_ref/doc/uid/20000211-CJBGADBA) That will at least let you know when an undo has been performed and then you can take appropriate action. |
64,877,917 | I am trying to rewrite something I have seen done in Java to Go.
In Java, the example converts the int `1573346` to the char `Ǣ` using the type cast of `(char)1573346;`
After printing the int of the new value I get the decimal ascii of `482;`
```
int num = 1573346;
char ascii = (char)num; // Ǣ
int asciiNum = (int)ascii; // 482
```
I can't find a way to do the same thing in Go. | 2020/11/17 | [
"https://Stackoverflow.com/questions/64877917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10038648/"
]
| Java's `char` type is 2 bytes or 16 bits. When you do `(char)num` in Java, that will "trim" `num` to 16 bits, keeping the lowest 16 bits.
To do the same in Go, first convert the number to `uint16` for example, and then to `rune` (and optionally to `string` for printing).
Note that in Go you can't convert the constant value `1573346` to `uint16` because the number is not representable by a value of type `uint16`. So you first have to assign it to a variable and convert the value of the variable (which is allowed):
```
x := 1573346
fmt.Println(string(rune(uint16(x))))
```
Which outputs:
```
Ǣ
```
The same as:
```
fmt.Println(string(rune(482)))
```
Try the examples on the [Go Playground](https://play.golang.org/p/dJrPFiI2nN4). | <https://play.golang.org/p/1eVgDANNTUT>
```
package main
import "fmt"
func main() {
var num = int(1573346)
var ascii = uint16(num)
var asciiNum = int(ascii)
fmt.Printf("%d %c %d", num, ascii, asciiNum)
}
```
```
1573346 Ǣ 482
Program exited.
``` |
2,065,218 | This appears to be reasonably trivial if using the ssl module for TCP communication, but how would encrypted communication be done via UDP?
Can the ssl module still be used? if so, what steps would need to be performed for the client and server to be in a position where data can be sent to-and-fro as normal? | 2010/01/14 | [
"https://Stackoverflow.com/questions/2065218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50746/"
]
| [DTLS](http://en.wikipedia.org/wiki/Datagram_Transport_Layer_Security) is a TLS (aka SSL) derivative designed for use over datagram transports, like UDP.
[OpenSSL](http://www.openssl.org/) supports DTLS starting in 0.9.8, using `DTLSv1_METHOD` instead of `SSLv23_METHOD` or `TLSv1_METHOD` or similar. | You could use pyCrypto or [ezPyCrypto](http://www.freenet.org.nz/ezPyCrypto/) to manually encrypt/decrypt the packets. |
35,218,403 | I need one help.I need to push one array object value into another array object in each iteration using PHP.I am explaining my code below.
```
for($i=0;$i<$len;$i++){
while($report=mysqli_fetch_assoc($reportqry)){
$result[]=$report;
}
//$arry
}
```
Here i need the `$result` will push into `$arry` in each iteration of the loop.Please help me. | 2016/02/05 | [
"https://Stackoverflow.com/questions/35218403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| You have to remove the semicolon (`;`) after the temination condition of your while loop. `;` is the end of an statement, after that a new statment beginns. Apart from this your `return` statement would be inside the `while` loop. Remove it outside the loop. Adapt your code like this:
```
int len(char p[]) {
int count = 0;
while (*p != '\0')
{
count++;
p++;
}
return count;
}
```
Further you have to read a string from input into your dynamicly allocated array of `char`:
```
int main() {
int array_size = 100;
char *p=new char[array_size]; // allocate memory
cout << "Type a phrase" << endl;
cin >> p; // read string into allocated memory
cout << "Your phrase was " << len(p) << " characters long." << endl;
delete p; // free memory
return 0;
}
```
The function `strlen` gives you the length of a `\0`-terminated string.
```
#include <string.h>
int main() {
int array_size = 100;
char *p=new char[array_size]; // allocate memory
cout << "Type a phrase" << endl;
cin >> p; // read string into allocated memory
cout << "Your phrase was " << strlen(p) << " characters long." << endl;
delete p; // free memory
return 0;
}
```
**But I recommend to use `std::string`:**
```
#include <string>
int main() {
std::string str;
cout << "Type a phrase" << endl;
cin >> str;
cout << "Your phrase was " << str.size() << " characters long." << endl;
return 0;
}
```
`std::string` represents a sequences of characters with dynamic length. | **Getting the size of dynamically allocated array**
A dynamically allocated array does not have any information about its size that is available in a standards compliant way.
We are able to compute the length of C style strings since there is sentinel element, `'\0'`, to mark the end of the string. There are no such elements for other types.
Even then, you cannot compute the size of an array of characters allocated using heap memory like you have.
**Problems with posted code**
1. You have the following lines outside all functions.
```
int array_size;
typedef char* charPtr;
charPtr a = new char[array_size];
char *p=a;
```
They are executed before anything in `main` gets executed. When these lines are executed, `array_size` gets initialized to `0`. Then you allocate memory for `charPtr` using `0` as the value of `array_size`.
2. Function `len` has an error due to a typo, which could lead to either (a) a hanging program or an incorrect return value.
```
int len(char p[])
{
int count = 0;
while (*p != '\0');
// ^^^ The semicolon is a problem
{
count++;
p++;
return count;
}
}
```
If `*p` is not equal to `'\0'`, the program will never get out of the `while` statement. It will hange.
If `*p` is equal to `'\0'`, the program will get out of the `while` statement but it will still execute the the lines after that. As a consequence, you will end up returning `1` as the length where `0` is the right answer.
3. In `main`, you have:
```
cout << "Type a phrase" << endl;
cin >> array_size;
```
When the user sees the output, they will try to enter a phrase. However, `array_size` is an `int`. There is a mismatch between the prompt to the user and the line to read the data.
You could change it them to:
```
cout << "Type array size" << endl;
cin >> array_size;
cout << "Type a phrase" << endl;
```
That is one step better but that still does not change the fact that memory for `a` was allocated using a size of `0`.
4. Using uninitialized memory
You are calling `len(p)` in the `cout` line but the elements of `p` have not been initialized.
It's not clear from your post what the program is supposed to do. I am guessing that you want to read a phrase from `stdin` and write it out to `stdout`. You can use the following simplified version for that.
```
int main()
{
std::string phrase;
cout << "Type a phrase" << endl;
// Get the entire line as a phrase.
std::getline(std::cin, phrase);
cout << "Your phrase is " << phrase << endl;
cout << "It is " << phrase.size() << " characters long." << endl;
return 0;
}
``` |
35,218,403 | I need one help.I need to push one array object value into another array object in each iteration using PHP.I am explaining my code below.
```
for($i=0;$i<$len;$i++){
while($report=mysqli_fetch_assoc($reportqry)){
$result[]=$report;
}
//$arry
}
```
Here i need the `$result` will push into `$arry` in each iteration of the loop.Please help me. | 2016/02/05 | [
"https://Stackoverflow.com/questions/35218403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| **Getting the size of dynamically allocated array**
A dynamically allocated array does not have any information about its size that is available in a standards compliant way.
We are able to compute the length of C style strings since there is sentinel element, `'\0'`, to mark the end of the string. There are no such elements for other types.
Even then, you cannot compute the size of an array of characters allocated using heap memory like you have.
**Problems with posted code**
1. You have the following lines outside all functions.
```
int array_size;
typedef char* charPtr;
charPtr a = new char[array_size];
char *p=a;
```
They are executed before anything in `main` gets executed. When these lines are executed, `array_size` gets initialized to `0`. Then you allocate memory for `charPtr` using `0` as the value of `array_size`.
2. Function `len` has an error due to a typo, which could lead to either (a) a hanging program or an incorrect return value.
```
int len(char p[])
{
int count = 0;
while (*p != '\0');
// ^^^ The semicolon is a problem
{
count++;
p++;
return count;
}
}
```
If `*p` is not equal to `'\0'`, the program will never get out of the `while` statement. It will hange.
If `*p` is equal to `'\0'`, the program will get out of the `while` statement but it will still execute the the lines after that. As a consequence, you will end up returning `1` as the length where `0` is the right answer.
3. In `main`, you have:
```
cout << "Type a phrase" << endl;
cin >> array_size;
```
When the user sees the output, they will try to enter a phrase. However, `array_size` is an `int`. There is a mismatch between the prompt to the user and the line to read the data.
You could change it them to:
```
cout << "Type array size" << endl;
cin >> array_size;
cout << "Type a phrase" << endl;
```
That is one step better but that still does not change the fact that memory for `a` was allocated using a size of `0`.
4. Using uninitialized memory
You are calling `len(p)` in the `cout` line but the elements of `p` have not been initialized.
It's not clear from your post what the program is supposed to do. I am guessing that you want to read a phrase from `stdin` and write it out to `stdout`. You can use the following simplified version for that.
```
int main()
{
std::string phrase;
cout << "Type a phrase" << endl;
// Get the entire line as a phrase.
std::getline(std::cin, phrase);
cout << "Your phrase is " << phrase << endl;
cout << "It is " << phrase.size() << " characters long." << endl;
return 0;
}
``` | First problem: you cannot use array\_size till it has been initialized.
>
> `char* a = new char [array_size]`
>
>
>
since array\_size has not been initialized and has garbage data in it, you have no idea how big that array is going to be.
that's why first you have to initialize `array_size`, and only after allocate your `char array`.
like
```
int array_size = 0 //no reason to have this variable as global, but that's up to you
char *a = nullptr; //same
int main()
{
cin >> array_size;
if (array_size <= 0) //make sure the input is valid and not negative
return 0;
a = new char[array_size];
//now you can work on your newly allocated array of characters
//the number of characters the array has equals to the array_size variable.
delete[] a;
return 0;
}
```
your len function checks for a '\0' character, but again, you have not initialized that char array either, so it contains garbage data. therefore sometimes you may get a result of len 5, 10, 502043, anything can happen really (undefined behavior). |
35,218,403 | I need one help.I need to push one array object value into another array object in each iteration using PHP.I am explaining my code below.
```
for($i=0;$i<$len;$i++){
while($report=mysqli_fetch_assoc($reportqry)){
$result[]=$report;
}
//$arry
}
```
Here i need the `$result` will push into `$arry` in each iteration of the loop.Please help me. | 2016/02/05 | [
"https://Stackoverflow.com/questions/35218403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| You have to remove the semicolon (`;`) after the temination condition of your while loop. `;` is the end of an statement, after that a new statment beginns. Apart from this your `return` statement would be inside the `while` loop. Remove it outside the loop. Adapt your code like this:
```
int len(char p[]) {
int count = 0;
while (*p != '\0')
{
count++;
p++;
}
return count;
}
```
Further you have to read a string from input into your dynamicly allocated array of `char`:
```
int main() {
int array_size = 100;
char *p=new char[array_size]; // allocate memory
cout << "Type a phrase" << endl;
cin >> p; // read string into allocated memory
cout << "Your phrase was " << len(p) << " characters long." << endl;
delete p; // free memory
return 0;
}
```
The function `strlen` gives you the length of a `\0`-terminated string.
```
#include <string.h>
int main() {
int array_size = 100;
char *p=new char[array_size]; // allocate memory
cout << "Type a phrase" << endl;
cin >> p; // read string into allocated memory
cout << "Your phrase was " << strlen(p) << " characters long." << endl;
delete p; // free memory
return 0;
}
```
**But I recommend to use `std::string`:**
```
#include <string>
int main() {
std::string str;
cout << "Type a phrase" << endl;
cin >> str;
cout << "Your phrase was " << str.size() << " characters long." << endl;
return 0;
}
```
`std::string` represents a sequences of characters with dynamic length. | First problem: you cannot use array\_size till it has been initialized.
>
> `char* a = new char [array_size]`
>
>
>
since array\_size has not been initialized and has garbage data in it, you have no idea how big that array is going to be.
that's why first you have to initialize `array_size`, and only after allocate your `char array`.
like
```
int array_size = 0 //no reason to have this variable as global, but that's up to you
char *a = nullptr; //same
int main()
{
cin >> array_size;
if (array_size <= 0) //make sure the input is valid and not negative
return 0;
a = new char[array_size];
//now you can work on your newly allocated array of characters
//the number of characters the array has equals to the array_size variable.
delete[] a;
return 0;
}
```
your len function checks for a '\0' character, but again, you have not initialized that char array either, so it contains garbage data. therefore sometimes you may get a result of len 5, 10, 502043, anything can happen really (undefined behavior). |
21,106,548 | I want to use jni to call my c++ lib in spark. When i sbt run my program, it shows that java.lang.UnsatisfiedLinkError: no hq\_Image\_Process in java.library.path , so obviously the program can not find my hq\_Image\_Process.so .
In hadoop, -files can distribute the xxx.so file to the slaves like this:
```
[hadoop@Master ~]$ hadoop jar JniTest3.jar -files /home/hadoop/Documents/java/jni1/bin/libFakeSegmentForJni.so FakeSegmentForJni.TestFakeSegmentForJni input output
```
Are there any ways to call my hq\_Image\_Process.so like hadoop in spark?
I would appreciate any help. | 2014/01/14 | [
"https://Stackoverflow.com/questions/21106548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3094459/"
]
| First of all, the native library must be preinstalled on all worker nodes. Path to that library must be specified in `spark-env.sh`:
```
export SPARK_LIBRARY_PATH=/path/to/native/library
```
`SPARK_PRINT_LAUNCH_COMMAND` environment variable might be used to diagnose it:
```
export SPARK_PRINT_LAUNCH_COMMAND=1
```
If everything's set correctly, you will see output like this:
```
Spark Command:
/path/to/java -cp <long list of jars> -Djava.library.path=/path/to/native/library <etc>
========================================
``` | Solution of accepted answer was for older (<1.0) Spark versions.
You need to set the following properties (either or both) on your `spark-defaults.conf`.
```
spark.driver.extraLibraryPath /path/to/native/library
spark.executor.extraLibraryPath /path/to/native/library
```
The property keys are documented at [Configuration Section](http://spark.apache.org/docs/latest/configuration.html) of Spark docs. |
125,230 | For a class I am teaching I would like to deploy CDFs on a website (BlackBoard-driven, if it matters), and I am running into two issues at this point:
A) I would like to have the CDFs styled according to a custom stylesheet of mine, but this only seems to work if that stylesheet is present on the target computer. I did follow the workflow suggested [here](https://mathematica.stackexchange.com/questions/3170/cdf-and-personalized-style), but I still get a message saying
>
> The stylesheet "" depends upon a stylesheet named "`name`.nb" which
> cannot be found by the Wolfram System.
>
>
>
and no styles are applied to the content of the CDF.
B) When someone clicks on the link to a CDF, the results look disastrous: Not only are there no styles applied at all, but the CDF Player toolbar itself is messed up, like so:
[](https://i.stack.imgur.com/EbJ3w.png)
I note that this does not happen if I provide a link to a notebook; it's only CDFs that result in the broken CDF Player toolbar.
If I choose "Web embeddable..." during the CDF creation process, things go *a little* better, in that in this case I get a CDF that seems to have style information embedded. However, the browser plugin opens the CDF such that it fits the entire document in the browser window so no scrolling is required, which makes the CDF (and its toolbar) unreadable. In addition, if I open the CDF file that's created directly, while I do get a properly styled layout, but with all input cells revealed and open.
Ideally, what I would like is for people to see a nice rendering, with styles applied, of the CDF in the same way I see it if I click on the "Open in Player" icon. I guess my question is, what is the secret to producing a usable CDF? Is this possible? The methods provided by the frontend interface certainly do not result in such CDFs.
**Update:**
I spent more time troubleshooting this, and here's my latest findings:
I realized that I don't really understand the mechanics of embedding stylesheets into notebooks at all. It appears that somehow, and I really don't know how that happened, I was able to create a notebook that has the stylesheet information embedded. If I open this on a machine with the stylesheet in question, I get a "ding" when opening it, but no error messages, and the styling is applied as it should. However, I have another notebook, that I had thought I had treated the same, and this one insists on the stylesheet being present, or else it will not format correctly.
By now I'm pretty sure that one of the fundamental questions here is: **Why the hell is there no straightforward way to embed entire custom stylesheets in a notebook?** You know, something as amazingly nifty as a menu item saying "Embed style definitions in this notebook". What this function would do is simply copy all of the style definitions in the notebook's custom Stylesheet into its private style definitions, and then switch the stylesheet in use to the Standard Stylesheet. This way we will have created a portable notebook that will render its styles the same on any machine with a standard Mathematica installation.
I also found that the CDFs produced as "Standalone" or "Web embedded" versions are quite different, and that I get yet a third version if I use the Save button in the CDF player from within the browser. I can find no rhyme or reason behind any of these. | 2016/08/31 | [
"https://mathematica.stackexchange.com/questions/125230",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/41613/"
]
| In your `Cases` command you specifically asked for only the first line. You can grab all the lines, and `Catenate` the results into a single list
```
data = Catenate@
Cases[Plot[Tan@x, {x, 0, 2 Pi}], Line[data_] :> data, Infinity];
Export["file.txt", data, "Table"];
ListPlot[Import["file.txt", "Table"]]
```
 | An alternative
```
points = Table[{x, Tan[x]}, {x, Range[0, 2 π, .01]}];
ListLinePlot[points]
```
[](https://i.stack.imgur.com/SfZyp.png)
```
Shallow[points]
```
>
> {{0., 0.}, {0.01, 0.0100003}, {0.02, 0.0200027}, {0.03,
> 0.030009}, {0.04, 0.0400213}, {0.05, 0.0500417}, {0.06,
> 0.0600721}, {0.07, 0.0701146}, {0.08, 0.0801711}, {0.09,
> 0.0902438}, <<619>>}
>
>
>
So, **points** is your List, containing 600plus Values. And you can use your strategy to save'em:
```
Export["points.txt", points, "Table"]
``` |
14,739,558 | Our client requires a view only form (making controls as readonly is not an acceptable solution :-( ) which displays the value of the text box / drop down / List box (comma delimited values) as label when the user has readonly access to that form. Is there a Jquery plugin which would do this? I don't want to create a separate set of partial views to accomplish this.
Any help in this regard is much appreciated.
Thanks,
Raja | 2013/02/06 | [
"https://Stackoverflow.com/questions/14739558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201792/"
]
| Yes, you can. I don't advise it.
Declare your helpers with a css class so you can grab them all with a JQuery selector
```
@Html.TextBox("txtName", "20", new { @class = "cssChange" })
```
Use JQuery to change their form to Labels
```
$( ".cssChange" ).replaceWith( function() {
return "<input type=\"label\" value=\"" + $( this ).html() + "\" />";
});
```
My code was not *tested*. It is purely instructive.
And I recommend against it. I would instead recommend another div with labels and a toggle. But this option is available. good luck. | ```
public static MvcHtmlString EditorOrDisplayFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression,
bool canEdit, int boxWidth = 100)
{
var sb = new StringBuilder();
if (canEdit)
{
var editor = htmlHelper.TextBoxFor(expression, new { style = "width: " + boxWidth + "px;" });
sb.AppendFormat("<div class=\"TextEditor\">{0}</div>", editor);
}
else
{
var lbl = htmlHelper.LabelFor(expression);
var hid = htmlHelper.HiddenFor(expression);
sb.AppendFormat("<div class=\"CanNotEdit\">{0}{1}</div>", lbl, hid);
}
return MvcHtmlString.Create(sb.ToString());
}
``` |
19,835,979 | i have a store procedure which is called by 4 different trigger
is it possible to get trigger's information like name when the procedure is executed.
i can do it by passing a extra parameter to the procedure,
is there any other option?
i am using oracle 11g.
Thanks | 2013/11/07 | [
"https://Stackoverflow.com/questions/19835979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2964706/"
]
| You could use the function `dbms_utility.format_call_stack` which is documented [here](http://docs.oracle.com/cd/E11882_01/appdev.112/e40758/d_util.htm#ARPLS73240):
```
SQL> set serveroutput on
SQL> create table test_table (n number);
Table created.
SQL> create or replace procedure test_procedure as
2 begin
3 dbms_output.put_line(dbms_utility.format_call_stack);
4 end;
5 /
Procedure created.
SQL> create or replace trigger test_trigger_insert
2 before insert on test_table
3 for each row
4 begin
5 test_procedure;
6 end;
7 /
Trigger created.
SQL> create or replace trigger test_trigger_delete
2 before delete on test_table
3 for each row
4 begin
5 test_procedure;
6 end;
7 /
Trigger created.
SQL> rem direct execution of the procedure
SQL> exec test_procedure;
----- PL/SQL Call Stack -----
object line object
handle number name
0x2bc2f1ca0 3 procedure YOUR_SCHEMA.TEST_PROCEDURE
0x31a218568 1
anonymous block
PL/SQL procedure successfully completed.
SQL> rem procedure called by trigger test_trigger_insert
SQL> insert into test_table (n) values (42);
----- PL/SQL Call Stack -----
object line object
handle number name
0x2bc2f1ca0 3 procedure YOUR_SCHEMA.TEST_PROCEDURE
0x2adc40fb0 2
YOUR_SCHEMA.TEST_TRIGGER_INSERT
1 row created.
SQL> rem procedure called by trigger test_trigger_delete
SQL> delete from test_table where n = 42;
----- PL/SQL Call Stack -----
object line object
handle number name
0x2bc2f1ca0 3 procedure YOUR_SCHEMA.TEST_PROCEDURE
0x2f10ffd28 2
YOUR_SCHEMA.TEST_TRIGGER_DELETE
1 row deleted.
``` | If your trigger is called My\_Trigger you can try this:
```
SELECT Trigger_type, Triggering_event, Table_name
FROM USER_TRIGGERS
WHERE Trigger_name = 'My_Trigger';
``` |
38,629,220 | I created some public method in controller which does some work.
```
def current_service
service_name = params[:controller].gsub('api/v1/', '').gsub(%r{/.+}, '')
end
```
I would like to test this method using RSpec but I dont't know how can I stub params. How should I do that? | 2016/07/28 | [
"https://Stackoverflow.com/questions/38629220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5032873/"
]
| If this is a controller spec, you should be able to do something like this:
```
allow(controller).to receive(:params).and_return({controller: 'a value'})
```
Alternatively, move the `params[:controller]` statement to a separate method and stub that in your spec. | For strong parameters you can stub them as following:
```
params = ActionController::Parameters.new(foo: 'bar')
allow(controller).to receive(:params).and_return(params)
``` |
5,660,115 | How can I go about loading a Spring context with my own `ClassLoader` instance? | 2011/04/14 | [
"https://Stackoverflow.com/questions/5660115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45525/"
]
| Many Spring Context Loader (for example [ClassPathXmlApplicationContext](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/context/support/ClassPathXmlApplicationContext.html)
) are subclass of [DefaultResourceLoader](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/DefaultResourceLoader.html).
`DefaultResourceLoader` has a [constructor](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/DefaultResourceLoader.html#DefaultResourceLoader%28java.lang.ClassLoader%29) where you can specify the Classloader and also has a [`setClassLoader`](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/DefaultResourceLoader.html#setClassLoader%28java.lang.ClassLoader%29) method.
So it is your task to find a constructor of the Spring Context Loader you need, where you can specify the classloader, or just create it, and then use the set to set the classloader you want. | The `org.springframework.context.support.ClassPathXmlApplicationContext` class is here for you. |
5,660,115 | How can I go about loading a Spring context with my own `ClassLoader` instance? | 2011/04/14 | [
"https://Stackoverflow.com/questions/5660115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45525/"
]
| ```
final ClassLoader properClassLoader = YourClass.class.getClassLoader();
appContext = new ClassPathXmlApplicationContext("application-context.xml") {
protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
super.initBeanDefinitionReader(reader);
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
reader.setBeanClassLoader(properClassLoader);
setClassLoader(properClassLoader);
```
See here if you are doing this for OSGI purposes: [How do I use a Spring bean inside an OSGi bundle?](https://stackoverflow.com/questions/8039931/how-do-i-use-a-spring-bean-inside-an-osgi-bundle) | The `org.springframework.context.support.ClassPathXmlApplicationContext` class is here for you. |
5,660,115 | How can I go about loading a Spring context with my own `ClassLoader` instance? | 2011/04/14 | [
"https://Stackoverflow.com/questions/5660115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45525/"
]
| Many Spring Context Loader (for example [ClassPathXmlApplicationContext](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/context/support/ClassPathXmlApplicationContext.html)
) are subclass of [DefaultResourceLoader](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/DefaultResourceLoader.html).
`DefaultResourceLoader` has a [constructor](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/DefaultResourceLoader.html#DefaultResourceLoader%28java.lang.ClassLoader%29) where you can specify the Classloader and also has a [`setClassLoader`](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/DefaultResourceLoader.html#setClassLoader%28java.lang.ClassLoader%29) method.
So it is your task to find a constructor of the Spring Context Loader you need, where you can specify the classloader, or just create it, and then use the set to set the classloader you want. | ```
final ClassLoader properClassLoader = YourClass.class.getClassLoader();
appContext = new ClassPathXmlApplicationContext("application-context.xml") {
protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
super.initBeanDefinitionReader(reader);
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
reader.setBeanClassLoader(properClassLoader);
setClassLoader(properClassLoader);
```
See here if you are doing this for OSGI purposes: [How do I use a Spring bean inside an OSGi bundle?](https://stackoverflow.com/questions/8039931/how-do-i-use-a-spring-bean-inside-an-osgi-bundle) |
5,660,115 | How can I go about loading a Spring context with my own `ClassLoader` instance? | 2011/04/14 | [
"https://Stackoverflow.com/questions/5660115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45525/"
]
| Many Spring Context Loader (for example [ClassPathXmlApplicationContext](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/context/support/ClassPathXmlApplicationContext.html)
) are subclass of [DefaultResourceLoader](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/DefaultResourceLoader.html).
`DefaultResourceLoader` has a [constructor](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/DefaultResourceLoader.html#DefaultResourceLoader%28java.lang.ClassLoader%29) where you can specify the Classloader and also has a [`setClassLoader`](http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/DefaultResourceLoader.html#setClassLoader%28java.lang.ClassLoader%29) method.
So it is your task to find a constructor of the Spring Context Loader you need, where you can specify the classloader, or just create it, and then use the set to set the classloader you want. | People who are using spring boot and wants to use custom classloader to create application context can do it like this:
```
@SpringBootApplication
public class Application
{
public static void main(String[] args) {
SpringApplication app =
new SpringApplication(Application.class);
ResourceLoader resourceLoader = new DefaultResourceLoader();
YourClassLoaderObject yourClassLoaderObject = new YourClassLoaderObject();
((DefaultResourceLoader)resourceLoader).setClassLoader(yourClassLoaderObject);
app.setResourceLoader(resourceLoader);
context = app.run(args);
}
}
``` |
5,660,115 | How can I go about loading a Spring context with my own `ClassLoader` instance? | 2011/04/14 | [
"https://Stackoverflow.com/questions/5660115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45525/"
]
| ```
final ClassLoader properClassLoader = YourClass.class.getClassLoader();
appContext = new ClassPathXmlApplicationContext("application-context.xml") {
protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
super.initBeanDefinitionReader(reader);
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
reader.setBeanClassLoader(properClassLoader);
setClassLoader(properClassLoader);
```
See here if you are doing this for OSGI purposes: [How do I use a Spring bean inside an OSGi bundle?](https://stackoverflow.com/questions/8039931/how-do-i-use-a-spring-bean-inside-an-osgi-bundle) | People who are using spring boot and wants to use custom classloader to create application context can do it like this:
```
@SpringBootApplication
public class Application
{
public static void main(String[] args) {
SpringApplication app =
new SpringApplication(Application.class);
ResourceLoader resourceLoader = new DefaultResourceLoader();
YourClassLoaderObject yourClassLoaderObject = new YourClassLoaderObject();
((DefaultResourceLoader)resourceLoader).setClassLoader(yourClassLoaderObject);
app.setResourceLoader(resourceLoader);
context = app.run(args);
}
}
``` |
57,008,839 | I'm trying to download an image from a URL using Glide and get the path of the file and forward it to `WallpaperManager.getCropAndSetWallpaperIntent` to be set as a wallpaper.
I found that this can be done using `asFile` method of Glide
Kotlin:
```
val data = Glide
.with(context)
.asFile()
.load(url)
.submit()
```
But when I call `data.get()` I get the error
`java.lang.IllegalArgumentException: You must call this method on a background thread`
So followed [this](https://stackoverflow.com/a/12575319/8608146) answer and implemented `MyAsyncTask`
```
interface AsyncResponse {
fun processFinish(output: File?)
}
class MyAsyncTask(delegate: AsyncResponse) : AsyncTask<FutureTarget<File>, Void, File?>() {
override fun doInBackground(vararg p0: FutureTarget<File>?): File? {
return p0[0]?.get()
}
private var delegate: AsyncResponse? = null
init {
this.delegate = delegate
}
override fun onPostExecute(result: File?) {
delegate!!.processFinish(result)
}
}
```
And I'm doing this now
```
fun getFile(context: Context, url: String) : File {
val data = Glide
.with(context)
.asFile()
.load(url)
.submit()
val asyncTask = MyAsyncTask(object : AsyncResponse {
override fun processFinish(output: File?) {
println(output?.path)
}
}).execute(data)
return asyncTask.get()
}
```
But I can't seem to get the `File`
**Edit:**
It was working but now there's a new error
```java
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.service.wallpaper.CROP_AND_SET_WALLPAPER dat=content://com.rithvij.scrolltest.provider/cache/image_manager_disk_cache/efebce47b249d7d92fd17340ecf91eb6b7ff86f91d71aabf50468f9e74d0e324.0 flg=0x1 pkg=is.shortcut }
```
Full stack trace
```java
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.rithvij.scrolltest, PID: 2760
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.service.wallpaper.CROP_AND_SET_WALLPAPER dat=content://com.rithvij.scrolltest.provider/cache/image_manager_disk_cache/efebce47b249d7d92fd17340ecf91eb6b7ff86f91d71aabf50468f9e74d0e324.0 flg=0x1 pkg=is.shortcut }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1816)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1525)
at android.app.Activity.startActivityForResult(Activity.java:4396)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4355)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at android.app.Activity.startActivity(Activity.java:4679)
at android.app.Activity.startActivity(Activity.java:4647)
at com.rithvij.scrolltest.MainActivity$onCreate$1.onClick(MainActivity.kt:71)
at android.view.View.performClick(View.java:5619)
at android.view.View$PerformClick.run(View.java:22298)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6375)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
```
1. Now my question is is this the preferred way to set wallpaper from a url?
2. How to deal with the other error? | 2019/07/12 | [
"https://Stackoverflow.com/questions/57008839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8608146/"
]
| I've built a document with a few paragraphs of the same style ("Normal") and various `space_after`:
[](https://i.stack.imgur.com/oJpwn.png)
Select all paragraphs and toggle the "Dont' add space between paragraphs of the same style" to checked.
Now it looks like so:
[](https://i.stack.imgur.com/umZaq.png)
Save and close the document from Word, then examine it via docx:
```
>>> from docx import Document
>>> document = Document(r'c:\debug\doc1.docx')
>>> for p in document.paragraphs:
... print(p.paragraph_format.space_after)
...
635000
None
None
```
So, clearly the `space_after` is retained, but it's not being observed in the document as it's overridden by the checkbox option. This is given by the `<w:contextualSpacing/>` element of the `<w:pPr>` (I notice this by examining the `\word\document.xml` part of the Docx).
```xml
<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:cx1="http://schemas.microsoft.com/office/drawing/2015/9/8/chartex" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" w:rsidR="00E00961" w:rsidRDefault="00174F18">
<w:pPr>
<w:spacing w:after="1000"/>
<w:contextualSpacing/>
</w:pPr>
<w:bookmarkStart w:id="0" w:name="_GoBack"/>
<w:r>
<w:t>hello, world!
</w:t>
</w:r>
</w:p>
```
You can remove these from the underlying XML like so:
```python
for p in document.paragraphs:
p_element = p._element
cspacing = p_element.xpath(r'w:pPr/w:contextualSpacing')[0]
cspacing.getparent().remove(cspacing)
```
After removing those elements, open the document again and observe the toggle has been turned off, and the paragraphs observe the `space_after`:
[](https://i.stack.imgur.com/IKzFg.png) | I tried David Zemens answer with an ordered list of style "List Number", but still had the check on "Dont't add space between paragraphs of the same style" in my docx file.
When examining the underlying xml files, I found a "w:contextualSpacing" entry in the "List Number" section of word/styles.xml.
My work-around is to rewrite the docx file (archive) without that contextualSpacing entry:
```
from io import BytesIO
import re
from zipfile import ZipFile
def remove_contextual_spacing_from_style(docx_path, style_name):
mod_docx = BytesIO()
style_byte = style_name.encode('utf-8')
# load docx file as zip archive
with ZipFile(docx_path, 'r') as old_docx, ZipFile(mod_docx, 'w') as new_docx:
# iterate through underlying xml files
for xml_item in old_docx.infolist():
with old_docx.open(xml_item) as old_xml:
content = old_xml.read()
# search style_name section in word/styles.xml
if xml_item.filename == 'word/styles.xml':
cspace = re.search(b'"%s".*?<\/w:pPr>'%(style_byte), content)
# remove contextualSpacing entry
if cspace:
cspace = cspace.group(0)
wo_cspace = cspace.replace(b'<w:contextualSpacing/>', b'')
content = re.sub(cspace, wo_cspace, content)
# store xml file in modified docx archive
new_docx.writestr(xml_item, content)
# overwrite old docx file with modified docx
with open(docx_path, 'wb') as new_docx:
new_docx.write(mod_docx.getbuffer())
# example usage with style "List Number"
remove_contextual_spacing_from_style('path_to.docx', 'List Number')
```
Used sources:
under "Use case #3, attempt #3"
<https://medium.com/dev-bits/ultimate-guide-for-working-with-i-o-streams-and-zip-archives-in-python-3-6f3cf96dca50>
<https://techoverflow.net/2020/11/11/how-to-modify-file-inside-a-zip-file-using-python/> |
5,263,150 | I created WCF service and testing WCF client using stand alone application. I was able to view this service using Internet Explorer also able to view in Visual studio service references. Here is the error message.
`"The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)."`
Could you please advice what could be wrong?
Thank you. | 2011/03/10 | [
"https://Stackoverflow.com/questions/5263150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528434/"
]
| Since the returned content type is `text/html`, I suspect your call result in a server-side error outside of WCF (you are receiving an HTML error page).
Try viewing the response with a web debugging proxy such as [Fiddler](http://www.fiddler2.com/fiddler2/).
---
(Edit based on comments) :
Based on your comments, I see that your WCF is hosted under Sharepoint 2010, in a form-authenticated site.
The error you are receiving is due to the fact that your your WCF client is NOT authenticated with sharepoint -- it does not have a valid authentication cookie. Sharepoint then return an HTTP Redirect to an html page (the login.aspx page); which is not expected by your WCF client.
To go further you will have to obtain an authentication cookie from Sharepoint (see [Authentication Web Service](http://msdn.microsoft.com/en-us/library/websvcauthentication.aspx)) and pass it to your WCF client.
---
(Updated edit) :
Mistake: The site is using claim based authentication.
Although this is not necessarily due to cookies or form authentication, the explaination of the provided error message remain the same. An authentication problem cause a redirection to an HTML page, which is not handled by the WCF client. | It sounds like your application is expecting XML but is receiving plain text. What type of object are you passing in? |
5,263,150 | I created WCF service and testing WCF client using stand alone application. I was able to view this service using Internet Explorer also able to view in Visual studio service references. Here is the error message.
`"The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)."`
Could you please advice what could be wrong?
Thank you. | 2011/03/10 | [
"https://Stackoverflow.com/questions/5263150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528434/"
]
| This may be helpful, check the url rewrite rules in ISS 7. This issue will occur if is you didn't configure rule properly. | It sounds like your application is expecting XML but is receiving plain text. What type of object are you passing in? |
5,263,150 | I created WCF service and testing WCF client using stand alone application. I was able to view this service using Internet Explorer also able to view in Visual studio service references. Here is the error message.
`"The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)."`
Could you please advice what could be wrong?
Thank you. | 2011/03/10 | [
"https://Stackoverflow.com/questions/5263150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528434/"
]
| Since the returned content type is `text/html`, I suspect your call result in a server-side error outside of WCF (you are receiving an HTML error page).
Try viewing the response with a web debugging proxy such as [Fiddler](http://www.fiddler2.com/fiddler2/).
---
(Edit based on comments) :
Based on your comments, I see that your WCF is hosted under Sharepoint 2010, in a form-authenticated site.
The error you are receiving is due to the fact that your your WCF client is NOT authenticated with sharepoint -- it does not have a valid authentication cookie. Sharepoint then return an HTTP Redirect to an html page (the login.aspx page); which is not expected by your WCF client.
To go further you will have to obtain an authentication cookie from Sharepoint (see [Authentication Web Service](http://msdn.microsoft.com/en-us/library/websvcauthentication.aspx)) and pass it to your WCF client.
---
(Updated edit) :
Mistake: The site is using claim based authentication.
Although this is not necessarily due to cookies or form authentication, the explaination of the provided error message remain the same. An authentication problem cause a redirection to an HTML page, which is not handled by the WCF client. | This may be helpful, check the url rewrite rules in ISS 7. This issue will occur if is you didn't configure rule properly. |
5,263,150 | I created WCF service and testing WCF client using stand alone application. I was able to view this service using Internet Explorer also able to view in Visual studio service references. Here is the error message.
`"The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)."`
Could you please advice what could be wrong?
Thank you. | 2011/03/10 | [
"https://Stackoverflow.com/questions/5263150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528434/"
]
| Since the returned content type is `text/html`, I suspect your call result in a server-side error outside of WCF (you are receiving an HTML error page).
Try viewing the response with a web debugging proxy such as [Fiddler](http://www.fiddler2.com/fiddler2/).
---
(Edit based on comments) :
Based on your comments, I see that your WCF is hosted under Sharepoint 2010, in a form-authenticated site.
The error you are receiving is due to the fact that your your WCF client is NOT authenticated with sharepoint -- it does not have a valid authentication cookie. Sharepoint then return an HTTP Redirect to an html page (the login.aspx page); which is not expected by your WCF client.
To go further you will have to obtain an authentication cookie from Sharepoint (see [Authentication Web Service](http://msdn.microsoft.com/en-us/library/websvcauthentication.aspx)) and pass it to your WCF client.
---
(Updated edit) :
Mistake: The site is using claim based authentication.
Although this is not necessarily due to cookies or form authentication, the explaination of the provided error message remain the same. An authentication problem cause a redirection to an HTML page, which is not handled by the WCF client. | text/html is SOAP 1.1 header and Content-Type: application/soap+xml is SOAP 1.2
Verify your bindings and return header.
It should be same either 1.1 or 1.2 |
5,263,150 | I created WCF service and testing WCF client using stand alone application. I was able to view this service using Internet Explorer also able to view in Visual studio service references. Here is the error message.
`"The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)."`
Could you please advice what could be wrong?
Thank you. | 2011/03/10 | [
"https://Stackoverflow.com/questions/5263150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528434/"
]
| Since the returned content type is `text/html`, I suspect your call result in a server-side error outside of WCF (you are receiving an HTML error page).
Try viewing the response with a web debugging proxy such as [Fiddler](http://www.fiddler2.com/fiddler2/).
---
(Edit based on comments) :
Based on your comments, I see that your WCF is hosted under Sharepoint 2010, in a form-authenticated site.
The error you are receiving is due to the fact that your your WCF client is NOT authenticated with sharepoint -- it does not have a valid authentication cookie. Sharepoint then return an HTTP Redirect to an html page (the login.aspx page); which is not expected by your WCF client.
To go further you will have to obtain an authentication cookie from Sharepoint (see [Authentication Web Service](http://msdn.microsoft.com/en-us/library/websvcauthentication.aspx)) and pass it to your WCF client.
---
(Updated edit) :
Mistake: The site is using claim based authentication.
Although this is not necessarily due to cookies or form authentication, the explaination of the provided error message remain the same. An authentication problem cause a redirection to an HTML page, which is not handled by the WCF client. | Add the following code to the web.config server project
```
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding_IService">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Service">
<endpoint address="" name="BasicHttpBinding_IService"
binding="basicHttpBinding"
bindingConfiguration="basicHttpBinding_IService"
contract="IService" />
</service>
```
then update client web service,After the update, the following changes are made web.config
```
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService">
<security mode="Transport" />
</binding>
</basicHttpBinding>
</bindings>
<endpoint address="https://www.mywebsite.com/Service.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService"
contract="Service.IService" name="BasicHttpBinding_IService" />
```
I hope to be useful |
5,263,150 | I created WCF service and testing WCF client using stand alone application. I was able to view this service using Internet Explorer also able to view in Visual studio service references. Here is the error message.
`"The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)."`
Could you please advice what could be wrong?
Thank you. | 2011/03/10 | [
"https://Stackoverflow.com/questions/5263150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528434/"
]
| Since the returned content type is `text/html`, I suspect your call result in a server-side error outside of WCF (you are receiving an HTML error page).
Try viewing the response with a web debugging proxy such as [Fiddler](http://www.fiddler2.com/fiddler2/).
---
(Edit based on comments) :
Based on your comments, I see that your WCF is hosted under Sharepoint 2010, in a form-authenticated site.
The error you are receiving is due to the fact that your your WCF client is NOT authenticated with sharepoint -- it does not have a valid authentication cookie. Sharepoint then return an HTTP Redirect to an html page (the login.aspx page); which is not expected by your WCF client.
To go further you will have to obtain an authentication cookie from Sharepoint (see [Authentication Web Service](http://msdn.microsoft.com/en-us/library/websvcauthentication.aspx)) and pass it to your WCF client.
---
(Updated edit) :
Mistake: The site is using claim based authentication.
Although this is not necessarily due to cookies or form authentication, the explaination of the provided error message remain the same. An authentication problem cause a redirection to an HTML page, which is not handled by the WCF client. | i was getting this error in NavitaireProvider while calling BookingCommit service (WCF Service Reference)
so, when we get cached proxy object then it will also retrived old SigninToken which still may not be persisted
so that not able to authenticate
so as a solution i called **Logon** Service when i get this exception to retrieve new Token |
5,263,150 | I created WCF service and testing WCF client using stand alone application. I was able to view this service using Internet Explorer also able to view in Visual studio service references. Here is the error message.
`"The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)."`
Could you please advice what could be wrong?
Thank you. | 2011/03/10 | [
"https://Stackoverflow.com/questions/5263150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528434/"
]
| This may be helpful, check the url rewrite rules in ISS 7. This issue will occur if is you didn't configure rule properly. | text/html is SOAP 1.1 header and Content-Type: application/soap+xml is SOAP 1.2
Verify your bindings and return header.
It should be same either 1.1 or 1.2 |
5,263,150 | I created WCF service and testing WCF client using stand alone application. I was able to view this service using Internet Explorer also able to view in Visual studio service references. Here is the error message.
`"The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)."`
Could you please advice what could be wrong?
Thank you. | 2011/03/10 | [
"https://Stackoverflow.com/questions/5263150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528434/"
]
| This may be helpful, check the url rewrite rules in ISS 7. This issue will occur if is you didn't configure rule properly. | Add the following code to the web.config server project
```
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding_IService">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Service">
<endpoint address="" name="BasicHttpBinding_IService"
binding="basicHttpBinding"
bindingConfiguration="basicHttpBinding_IService"
contract="IService" />
</service>
```
then update client web service,After the update, the following changes are made web.config
```
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService">
<security mode="Transport" />
</binding>
</basicHttpBinding>
</bindings>
<endpoint address="https://www.mywebsite.com/Service.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService"
contract="Service.IService" name="BasicHttpBinding_IService" />
```
I hope to be useful |
5,263,150 | I created WCF service and testing WCF client using stand alone application. I was able to view this service using Internet Explorer also able to view in Visual studio service references. Here is the error message.
`"The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)."`
Could you please advice what could be wrong?
Thank you. | 2011/03/10 | [
"https://Stackoverflow.com/questions/5263150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528434/"
]
| This may be helpful, check the url rewrite rules in ISS 7. This issue will occur if is you didn't configure rule properly. | i was getting this error in NavitaireProvider while calling BookingCommit service (WCF Service Reference)
so, when we get cached proxy object then it will also retrived old SigninToken which still may not be persisted
so that not able to authenticate
so as a solution i called **Logon** Service when i get this exception to retrieve new Token |
10,141 | This is a very grey area, because while excel is fun to enter, and play around with, often times it's seen as a pseudo-programming language.
In Excel, one can drag-down formulas to automatically match cell entries, and other minor patterns. Usually, these formulas are dragged to the bottom of the input index, or (often times) all the way down to the bottom of the sheet.
One can start to see how this gets strange very quick, as these drag-downs are useful, but hard to score.
**Note, I'm not talking about answers where [dragging down is part of the input](https://codegolf.stackexchange.com/questions/87614/turtles-all-the-way-down/88761#88761). I'm explicitly referring to answers that already have the formulas in them before any input.**
How should we handle these answers? Should they be ignored? Scored? | 2016/09/22 | [
"https://codegolf.meta.stackexchange.com/questions/10141",
"https://codegolf.meta.stackexchange.com",
"https://codegolf.meta.stackexchange.com/users/-1/"
]
| Just count the bytes
--------------------
This is a common question for oddball languages, from Scratch to Minecraft to Lego WeDo. The answer is usually ([from what I've seen](https://codegolf.meta.stackexchange.com/a/9680/14215)) to just count the bytes of the saved file.
It's a simple method, easily understood by anyone. Will this make the score go up? Probably, but if you cared about having a super low score you probably wouldn't be using one of these languages in the first place.
Note: If you can save it one of several Excel formats, choose the one with the lower byte count. Assuming that format has the features necessary to then open it back up and run it properly. | Score as a polynomial
---------------------
The way I wanted to suggest scoring these is to leave the score as a polynomial.
for example, say you have some code in excel like the following:
[](https://i.stack.imgur.com/eJfDg.png)
because "=(some more code)" is at a single point in the sheet, this will be the 0th term in the polynomial. In this case it is **17 bytes**.
The "=(Some code)" snippet occurs along one dimension in the array (the A column), so that would be the 1st term in the polynomial. In this case it would be **12n bytes**.
And in the rare case that someone has a multidimensional formula, then it will be considered the 2nd term in the polynomial. In this case it would be **25n² bytes**
so, if we were to score this sheet all together, it would be **25n² + 12n + 17 bytes**.
While this method describes the nature of the entry well, it still lacks a proper method of scoring. |
10,141 | This is a very grey area, because while excel is fun to enter, and play around with, often times it's seen as a pseudo-programming language.
In Excel, one can drag-down formulas to automatically match cell entries, and other minor patterns. Usually, these formulas are dragged to the bottom of the input index, or (often times) all the way down to the bottom of the sheet.
One can start to see how this gets strange very quick, as these drag-downs are useful, but hard to score.
**Note, I'm not talking about answers where [dragging down is part of the input](https://codegolf.stackexchange.com/questions/87614/turtles-all-the-way-down/88761#88761). I'm explicitly referring to answers that already have the formulas in them before any input.**
How should we handle these answers? Should they be ignored? Scored? | 2016/09/22 | [
"https://codegolf.meta.stackexchange.com/questions/10141",
"https://codegolf.meta.stackexchange.com",
"https://codegolf.meta.stackexchange.com/users/-1/"
]
| Scored answers must be keyboard-only
------------------------------------
Given that the [`Range`](https://msdn.microsoft.com/en-us/library/office/ff838238.aspx) operator exists that can replace the mouse drag-down operation, and the arrow keys can move between cells to (for example) enter multiple snippets of code in separate areas, I can't think of a reason why the mouse needs to be involved.
This also has the benefit of being able to be scored similar to Vim, for example, based on keystrokes. | Score as a polynomial
---------------------
The way I wanted to suggest scoring these is to leave the score as a polynomial.
for example, say you have some code in excel like the following:
[](https://i.stack.imgur.com/eJfDg.png)
because "=(some more code)" is at a single point in the sheet, this will be the 0th term in the polynomial. In this case it is **17 bytes**.
The "=(Some code)" snippet occurs along one dimension in the array (the A column), so that would be the 1st term in the polynomial. In this case it would be **12n bytes**.
And in the rare case that someone has a multidimensional formula, then it will be considered the 2nd term in the polynomial. In this case it would be **25n² bytes**
so, if we were to score this sheet all together, it would be **25n² + 12n + 17 bytes**.
While this method describes the nature of the entry well, it still lacks a proper method of scoring. |
10,141 | This is a very grey area, because while excel is fun to enter, and play around with, often times it's seen as a pseudo-programming language.
In Excel, one can drag-down formulas to automatically match cell entries, and other minor patterns. Usually, these formulas are dragged to the bottom of the input index, or (often times) all the way down to the bottom of the sheet.
One can start to see how this gets strange very quick, as these drag-downs are useful, but hard to score.
**Note, I'm not talking about answers where [dragging down is part of the input](https://codegolf.stackexchange.com/questions/87614/turtles-all-the-way-down/88761#88761). I'm explicitly referring to answers that already have the formulas in them before any input.**
How should we handle these answers? Should they be ignored? Scored? | 2016/09/22 | [
"https://codegolf.meta.stackexchange.com/questions/10141",
"https://codegolf.meta.stackexchange.com",
"https://codegolf.meta.stackexchange.com/users/-1/"
]
| Scored answers must be keyboard-only
------------------------------------
Given that the [`Range`](https://msdn.microsoft.com/en-us/library/office/ff838238.aspx) operator exists that can replace the mouse drag-down operation, and the arrow keys can move between cells to (for example) enter multiple snippets of code in separate areas, I can't think of a reason why the mouse needs to be involved.
This also has the benefit of being able to be scored similar to Vim, for example, based on keystrokes. | Just count the bytes
--------------------
This is a common question for oddball languages, from Scratch to Minecraft to Lego WeDo. The answer is usually ([from what I've seen](https://codegolf.meta.stackexchange.com/a/9680/14215)) to just count the bytes of the saved file.
It's a simple method, easily understood by anyone. Will this make the score go up? Probably, but if you cared about having a super low score you probably wouldn't be using one of these languages in the first place.
Note: If you can save it one of several Excel formats, choose the one with the lower byte count. Assuming that format has the features necessary to then open it back up and run it properly. |
25,786 | I am developing a neuroscience-inspired training algorithm for feed-forward neural networks. The natural benchmark for comparison is backpropagation. So I need to know to know what sort of classification problems backpropagation (and thus feed-forward NNs) is most suited for. Also, since I ultimately want to move beyond backprop, what non NN algorithms are the best alternatives to backprop, when it comes to the sort of problems that backprop is good at.
Or, in other words, what problems should I benchmark a feed-forward network on, and what are the algorithms to beat for those problems? | 2012/04/03 | [
"https://stats.stackexchange.com/questions/25786",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/3443/"
]
| We know $X-\mu$ has a $N(0,\sigma^2)$ distribution. So
$$E( (X-\mu)^2 ) = {\rm var}(X-\mu) + [E(X-\mu)]^2 = \sigma^{2} + 0 = \sigma^2$$
therefore
$$E\left(\frac{(X-\mu)^2}{\sigma^6}\right) = \frac{1}{\sigma^6} \cdot E( (X-\mu)^2 ) = \frac{\sigma^2}{\sigma^{6}} = \frac{1}{\sigma^4}$$
which implies
$$-E \left [\frac{1}{2\sigma^4}-\frac{(X-\mu)^2}{\sigma^6}\right] = -\frac{1}{2\sigma^4} + \frac{1}{\sigma^4} = \frac{1}{2\sigma^4}$$ | If $\sigma$ is the standard deviation then it is positive (or at least non-negative).
If $\sigma$ is a constant then $$-E\left[ \frac 2 \sigma \right] = -\frac 2 \sigma$$
In the expression for the [Fisher Information](http://en.wikipedia.org/wiki/Fisher_information) you can often find
$$
\mathcal{I}(\theta) = - \operatorname{E} \left[\left. \frac{\partial^2}{\partial\theta^2} \log f(X;\theta)\right|\theta \right]\,
$$
the sign is present because the expectation is negative. There is another expression $$\mathcal{I}(\theta)=\operatorname{E} \left[\left. \left(\frac{\partial}{\partial\theta} \log f(X;\theta)\right)^2\right|\theta \right]$$ withought the negative sign. |
63,805,472 | I am going to generate e-invoice from C# code using put method.I have tested e-invoice api in sandbox environment using postmen tool.It works fine as per our requirement.I would like to know how to pass API Header information and body information from C# Code
```
Header :-
Content-Type : application/json
owner_id: zxererer45454545_4545456
gstin : 29AAFCD5862R000
Body :-
[
{
"transaction": {
"Version": "1.03",
"TranDtls": {
"TaxSch": "GST",
"SupTyp": "B2B",
"RegRev": "Y",
"EcmGstin": null,
"IgstOnIntra": "N"
},
"DocDtls": {
"Typ": "INV",
"No": "AS/20/0009",
"Dt": "08/09/2020"
},
"SellerDtls": {
"Gstin": "29AAFCD5862R000",
"LglNm": "K.H Exports India Private Limited",
"TrdNm": "K.H Exports India Private Limited",
"Addr1": "142/1,Trunk Road",
"Addr2": "142/1,Trunk Road",
"Loc": "Perumugai",
"Pin": "560037",
"Stcd": "29",
"Ph": "04162253164",
"Em": "[email protected]"
},
]
```
I am getting an error message when I use below code,Please check attached screenshot
[screenshot error message](https://i.stack.imgur.com/GuUDl.png) | 2020/09/09 | [
"https://Stackoverflow.com/questions/63805472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14224291/"
]
| You can use HttpClient to make request to an API in C#. Below is a sample code
```
public async Task<TResponse> SendPutRequestAsync<TRequest, TResponse>(TRequest data, string url, string accessToken = null)
{
var httpClient = new HttpClient
{
BaseAddress = "BaseAddress of your API"
};
if (!string.IsNullOrWhiteSpace(accessToken))
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
httpClient.DefaultRequestHeaders.Add("HeaderKey", "HeaderValue");
var response = await httpClient.PutAsJsonAsync(url, data);
if (response.IsSuccessStatusCode)
return JsonConvert.DeserializeObject<TResponse>(await response.Content.ReadAsStringAsync());
else
throw new HttpRequestException(response.ReasonPhrase);
}
```
This is the extension add data in the body of the request.
```
public static class HttpClientExtensions
{
public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpClient httpClient, string url, T data)
{
var dataAsString = JsonConvert.SerializeObject(data);
var content = new StringContent(dataAsString);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return httpClient.PutAsync(url, content);
}
}
``` | Here the response is of JSON format. You can use the standard package Newtonsoft.Json dll which will be available to download in the nuget server.
After referencing the Newtonsoft.json to your project do like
JObject jobject = JObject.Parse(response);
JObject header = jobject["Header"];
JObject body = jobject["Body"];
and now you have Header and Body as separate JObject.
If you want to fetch any header or body item just do same as like above.
ex to get "gstin" from header :
string gstin = header["gstin"];
for better clarity read on Newtonsoft.Json documentation for how to parse a json string. |
167,340 | I need for the 5th column in a delimited text file to be reduced to just the first 5 characters. All other columns must remain unedited.
Input:
```
file1.txt column1 column2 column3 column4 column5
123456789 123456789 123456789 123456789 123456789
```
I would like the output to look like:
```
output.txt column1 column2 column3 column4 column5
123456789 123456789 123456789 123456789 12345
```
Note: I happen to use commas as the delimiter. | 2014/11/11 | [
"https://unix.stackexchange.com/questions/167340",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/79825/"
]
| If `file.csv` looks like this:
```
123456789,123456789,123456789,123456789,123456789
123456789,123456789,123456789,123456789,223456789
123456789,123456789,123456789,123456789,323456789
123456789,123456789,123456789,123456789,423456789
```
Then, you can do:
```
$ awk -F, '{print $1","$2","$3","$4","substr($5,1,5) }' file.csv
123456789,123456789,123456789,123456789,12345
123456789,123456789,123456789,123456789,22345
123456789,123456789,123456789,123456789,32345
123456789,123456789,123456789,123456789,42345
``` | If all the values are simple (no quotes and newlines in a value) and if they are comma separated, like:
```
123456789,123456789,123456789,123456789,123456789
```
and if there are always 5 such values on a line, you can use `sed`:
```
sed '2,$s/\(.*\),\(.*\),\(.*\),\(.*\),\(.....\)\(.*\)/\1,\2,\3,\4,\5/' input
```
The `2,$` assumes you have a header that is comma separated as well (and that its
fifth column should not be truncated), if that is not the case leave it out. |
167,340 | I need for the 5th column in a delimited text file to be reduced to just the first 5 characters. All other columns must remain unedited.
Input:
```
file1.txt column1 column2 column3 column4 column5
123456789 123456789 123456789 123456789 123456789
```
I would like the output to look like:
```
output.txt column1 column2 column3 column4 column5
123456789 123456789 123456789 123456789 12345
```
Note: I happen to use commas as the delimiter. | 2014/11/11 | [
"https://unix.stackexchange.com/questions/167340",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/79825/"
]
| If `file.csv` looks like this:
```
123456789,123456789,123456789,123456789,123456789
123456789,123456789,123456789,123456789,223456789
123456789,123456789,123456789,123456789,323456789
123456789,123456789,123456789,123456789,423456789
```
Then, you can do:
```
$ awk -F, '{print $1","$2","$3","$4","substr($5,1,5) }' file.csv
123456789,123456789,123456789,123456789,12345
123456789,123456789,123456789,123456789,22345
123456789,123456789,123456789,123456789,32345
123456789,123456789,123456789,123456789,42345
``` | Or `awk`:
For white-space delimited:
```
awk 'NR==1 { print; next} {print $1, $2, $3, $4, substr($5,1,5)}'
```
For comma delimited:
```
awk 'BEGIN {FS=","} NR==1 { print; next} {print $1, $2, $3, $4, substr($5,1,5)}'
```
For slightly better CSV splitting and assuming GNU awk:
```
awk -vFPAT='[^,]*|"[^"]*"' 'NR==1 { print; next} {print $1, $2, $3, $4, substr($5,1,5)}'
``` |
9,949,461 | I want to start developing graphic programing using OpenGl
To kick start I am following [OpenGL](http://www.opengl.org/wiki/Getting_started)
I came across programing with GLUT and without GLUT but as being new to OpenGL in am even more confuse how to go with it? | 2012/03/30 | [
"https://Stackoverflow.com/questions/9949461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1278178/"
]
| GLUT is the **OpenGL Utility Toolkit**
It does stuff like this:
* Multiple windows for OpenGL rendering
* Callback driven event processing
* Sophisticated input devices
* An 'idle' routine and timers
* A simple, cascading pop-up menu facility
* Utility routines to generate various solid and wire frame objects
* Support for bitmap and stroke fonts
* Miscellaneous window management functions
You can find more about it [here](http://www.opengl.org/resources/libraries/glut/). | GLUT was designed as a lib for simple demos and tutorials. Maybe one cannot create full AAA game title using it... but for learning/teaching it is a great tool.
GLUT is very old right now, so look for FreeGlut which is an alternative that handles not only basic GLUT features but also gives some more advanced features: like fullscreen game mode, etc.
<http://freeglut.sourceforge.net/> |
387,383 | I'm trying to make a remote control RGB LED light using an ATtiny13A.
I know the ATtiny85 is better suited for this purpose, and I know I might not eventually be able to fit the whole code, but for now my main concern is to generate a software PWM using interrupts in CTC mode.
I cannot operate in any other mode (except for fast PWM with `OCR0A` as `TOP` which is basically the same thing) because the IR receiver code I am using needs a 38 kHz frequency which it generates using CTC and `OCR0A=122`.
So I'm trying to (and I've seen people mention this on the Internet) use the `Output Compare A` and `Output Compare B` interrupts to generate a software PWM.
`OCR0A`, which is also used by the IR code, determines the frequency, which I don't care about. And `OCR0B`, determines the duty cycle of the PWM which I'll be using for changing the LED colors.
I'm expecting to be able to get a PWM with 0-100% duty cycle by changing the `OCR0B` value from `0` to `OCR0A`. This is my understanding of what should happen:
[](https://i.stack.imgur.com/pTglv.png)
But what actually is happening is this (this is from Proteus ISIS simulation):
As you can see below, I'm able to get about 25%-75% duty cycle but for ~0-25% and ~75-100% the wave form is just stuck and doesn't change.
YELLOW line: Hardware PWM
RED line: Software PWM with fixed duty cycle
GREEN line: Software PWM with varying duty cycle
[](https://i.stack.imgur.com/OxqGt.gif)
And here is my code:
```
#ifndef F_CPU
#define F_CPU (9600000UL) // 9.6 MHz
#endif
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
int main(void)
{
cli();
TCCR0A = 0x00; // Init to zero
TCCR0B = 0x00;
TCCR0A |= (1<<WGM01); // CTC mode
TCCR0A |= (1<<COM0A0); // Toggle OC0A on compare match (50% PWM on PINB0)
// => YELLOW line on oscilloscope
TIMSK0 |= (1<<OCIE0A) | (1<<OCIE0B); // Compare match A and compare match B interrupt enabled
TCCR0B |= (1<<CS00); // Prescalar 1
sei();
DDRB = 0xFF; // All ports output
while (1)
{
OCR0A = 122; // This is the value I'll be using in my main program
for(int i=0; i<OCR0A; i++)
{
OCR0B = i; // Should change the duty cycle
_delay_ms(2);
}
}
}
ISR(TIM0_COMPA_vect){
PORTB ^= (1<<PINB3); // Toggle PINB3 on compare match (50% <SOFTWARE> PWM on PINB3)
// =>RED line on oscilloscope
PORTB &= ~(1<<PINB4); // PINB4 LOW
// =>GREEN line on oscilloscope
}
ISR(TIM0_COMPB_vect){
PORTB |= (1<<PINB4); // PINB4 HIGH
}
``` | 2018/07/24 | [
"https://electronics.stackexchange.com/questions/387383",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/165256/"
]
| A minimal software PWM could look like this:
```
volatile uint16_t dutyCycle;
uint8_t currentPwmCount;
ISR(TIM0_COMPA_vect){
const uint8_t cnt = currentPwmCount + 1; // will overflow from 255 to 0
currentPwmCount = cnt;
if ( cnt <= dutyCyle ) {
// Output 0 to pin
} else {
// Output 1 to pin
}
}
```
Your program sets `dutyCycle` to the desired value and the ISR outputs the corresponding PWM signal. `dutyCycle` is a `uint16_t` to allow for values between 0 and **256** inclusive; 256 is bigger than any possible value of `currentPwmCount` and thus provides full 100% duty cycle.
If you don't need 0% (or 100%) you can shave off some cycles by using a `uint8_t` so that either `0` results in a duty cycle of 1/256 and `255` is 100% or `0` is 0% and `255` is a duty cycle of 255/256.
You still don't have much time in a 38kHz ISR; using a little inline assembler you can probably cut the cycle count of the ISR by 1/3 to 1/2. Alternative: Run your PWM code only every other timer overflow, halving the PWM frequency.
If you have multiple PWM channels and the pins you're PMW-ing are all on the same `PORT` you can also collect all pins' states in a variable and finally output them to the port in one step which then only needs the read-from-port, and-with-mask, or-with-new-state, write-to-port *once* instead of *once per pin/channel*.
Example:
```
volatile uint8_t dutyCycleRed;
volatile uint8_t dutyCycleGreen;
volatile uint8_t dutyCycleBlue;
#define PIN_RED (0) // Example: Red on Pin 0
#define PIN_GREEN (4) // Green on pin 4
#define PIN_BLUE (7) // Blue on pin 7
#define BIT_RED (1<<PIN_RED)
#define BIT_GREEN (1<<PIN_GREEN)
#define BIT_BLUE (1<<PIN_BLUE)
#define RGB_PORT_MASK ((uint8_t)(~(BIT_RED | BIT_GREEN | BIT_BLUE)))
uint8_t currentPwmCount;
ISR(TIM0_COMPA_vect){
uint8_t cnt = currentPwmCount + 1;
if ( cnt > 254 ) {
/* Let the counter overflow from 254 -> 0, so that 255 is never reached
-> duty cycle 255 = 100% */
cnt = 0;
}
currentPwmCount = cnt;
uint8_t output = 0;
if ( cnt < dutyCycleRed ) {
output |= BIT_RED;
}
if ( cnt < dutyCycleGreen ) {
output |= BIT_GREEN;
}
if ( cnt < dutyCycleBlue ) {
output |= BIT_BLUE;
}
PORTx = (PORTx & RGB_PORT_MASK) | output;
}
```
This code maps the duty cycle to a logical `1` output on the pins; if your LEDs have 'negative logic' (LED on when pin is *low*), you can invert the polarity of the PWM signal by simply changing `if (cnt < dutyCycle...)` to `if (cnt >= dutyCycle...)`. | As @JimmyB commented the PWM frequency is too high.
It seems that the interrupts have a total latency of one quarter of the PWM cycle.
When overlapping, the duty cycle is fixed given by the total latency, since the second interrupt is queued and executed after the first is exited.
The minimum PWM duty cycle is given by the total interrupt latency percentage in the PWM period. The same logic applies to the maximum PWM duty cycle.
Looking at the graphs the minimum duty cycle is around 25%, and then the total latency must be ~ 1/(38000\*4) = 6.7 µs.
As consequence the minimum PWM period is 256\*6.7 µs = 1715 µs and 583 Hz maximum frequency.
Some more explanations about possible patches at a high frequency:
The interrupt has two blind windows when nothing can be done, entering end exiting the interrupt when the context is saved and recovered. Since your code is pretty simple I suspect that this takes a good portion of the latency.
A solution to skip the low values will still have a latency at least as exiting the interrupt and entering the next interrupt so the minimum duty cycle will not be as expected.
As long as this is not less than a PWM step, the PWM duty cycle will begin at a higher value. Just a slight improvement from what you have now.
I see you already use 25% of the processor time in interrupts, so why don't you use 50% or more of it, leave the second interrupt and just pool for the compare flag. If you use values only up to 128 you will have only up to 50% duty cycle, but with the latency of two instructions that could be optimized in assembler. |
21,379,601 | This is my div `style`
```
<style>
#N_fixedBottom
{
position:fixed;
bottom:0px;
left:0px;
right:0px;
background-color:#004369;
width:100%;
height:20px;
z-index:100;
}
</style>
<div id="N_fixedBottom">
</div>
```
This `div` should hide when it scroll down to the bottom of page. Because this DIV is hiding my footer. | 2014/01/27 | [
"https://Stackoverflow.com/questions/21379601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2833769/"
]
| assumes that body has a `margin` of 0. Else you'll need to add the top and bottom margin to the `$('body').height()`.
```
$(document).ready(function(){
$(window).scroll(function() {
if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
$('#N_fixedBottom').hide();
}
});
});
``` | ```
$(window).scroll(function() {
var fixedBottom = $("#N_fixedBottom");
if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
fixedBottom.css("opacity", 0 );
} else {
fixedBottom.css("opacity", 1 );
}
});
```
And then I would add opacity: 0 and transition: opacity 0.5s ease-out to #N\_fixedBottom so it fades in:
```
#N_fixedBottom {
transition: opacity 0.5s ease-out;
opacity: 0;
position: fixed;
bottom: 0px;
left: 0px;
right: 0px;
background-color: #004369;
width: 100%;
height: 20px;
z-index: 100;
}
``` |
21,379,601 | This is my div `style`
```
<style>
#N_fixedBottom
{
position:fixed;
bottom:0px;
left:0px;
right:0px;
background-color:#004369;
width:100%;
height:20px;
z-index:100;
}
</style>
<div id="N_fixedBottom">
</div>
```
This `div` should hide when it scroll down to the bottom of page. Because this DIV is hiding my footer. | 2014/01/27 | [
"https://Stackoverflow.com/questions/21379601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2833769/"
]
| Guess you want a pure javascript solution now you havent included the tag [jquery](/questions/tagged/jquery "show questions tagged 'jquery'")?
```
<div id="N_fixedBottom">bla bla</div>
```
script :
```js
document.onscroll = function() {
if (window.innerHeight + window.scrollY > document.body.clientHeight) {
document.getElementById('N_fixedBottom').style.display='none';
}
}
``` | ```
$(window).scroll(function() {
var fixedBottom = $("#N_fixedBottom");
if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
fixedBottom.css("opacity", 0 );
} else {
fixedBottom.css("opacity", 1 );
}
});
```
And then I would add opacity: 0 and transition: opacity 0.5s ease-out to #N\_fixedBottom so it fades in:
```
#N_fixedBottom {
transition: opacity 0.5s ease-out;
opacity: 0;
position: fixed;
bottom: 0px;
left: 0px;
right: 0px;
background-color: #004369;
width: 100%;
height: 20px;
z-index: 100;
}
``` |
277,767 | If an educational company described their session methodology as "high in reach" does it mean:
1. the size of the audience
2. the effectiveness of the training
3. other?
The original sentence in a press release was just "Our trainings are low in cost, high in reach".
I see that this comparison with cost is sometimes being used together [for example](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2957672/) "*Our interventions must be high in reach but low in cost in order to most persuasively demonstrate worth in intervention*" | 2015/10/04 | [
"https://english.stackexchange.com/questions/277767",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/139423/"
]
| It's a somewhat vague term, and can be interpreted in several ways. But think of a person simply jumping to touch the highest point on a wall that they can achieve. "High in reach" basically means challenging you to reach as far up as you can. | "High in reach" in this context would mean the goals are high but within reach. It's a motivational phrase that you have high and lofty goals but with your abilities they are well within reach, or that you are well within your ability to meet those goals. |
277,767 | If an educational company described their session methodology as "high in reach" does it mean:
1. the size of the audience
2. the effectiveness of the training
3. other?
The original sentence in a press release was just "Our trainings are low in cost, high in reach".
I see that this comparison with cost is sometimes being used together [for example](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2957672/) "*Our interventions must be high in reach but low in cost in order to most persuasively demonstrate worth in intervention*" | 2015/10/04 | [
"https://english.stackexchange.com/questions/277767",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/139423/"
]
| "High in reach" is a non-idiomatic way of saying that it *reaches* many people. This uses the word *reach* in the following sense:
>
> **reach** *noun*
> 2 The extent or range of something's application, effect, or influence.
> ‘he told a story to illustrate the reach of his fame’
> [- ODO](https://en.oxforddictionaries.com/definition/reach)
>
>
>
Consider the fuller quote of the [link you provided](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2957672/) (emphasis, mine):
>
> When all is said, the promise of the history of diffusion scholarship and diffusion practice is a promise of efficiency in intervention: **Communicating** an innovation **to a special small subset** of potential adopters so that they, in turn, will **influence the vast majority of other potential adopters** to attend to, consider, adopt, implement, and maintain the use of worthy innovations. Our interventions must be high in reach but low in cost in order to most persuasively demonstrate worth in intervention.
>
>
>
It's talking about accessing a small group that would *reach* the larger (target) audience. | "High in reach" in this context would mean the goals are high but within reach. It's a motivational phrase that you have high and lofty goals but with your abilities they are well within reach, or that you are well within your ability to meet those goals. |
277,767 | If an educational company described their session methodology as "high in reach" does it mean:
1. the size of the audience
2. the effectiveness of the training
3. other?
The original sentence in a press release was just "Our trainings are low in cost, high in reach".
I see that this comparison with cost is sometimes being used together [for example](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2957672/) "*Our interventions must be high in reach but low in cost in order to most persuasively demonstrate worth in intervention*" | 2015/10/04 | [
"https://english.stackexchange.com/questions/277767",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/139423/"
]
| "High in reach" is a non-idiomatic way of saying that it *reaches* many people. This uses the word *reach* in the following sense:
>
> **reach** *noun*
> 2 The extent or range of something's application, effect, or influence.
> ‘he told a story to illustrate the reach of his fame’
> [- ODO](https://en.oxforddictionaries.com/definition/reach)
>
>
>
Consider the fuller quote of the [link you provided](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2957672/) (emphasis, mine):
>
> When all is said, the promise of the history of diffusion scholarship and diffusion practice is a promise of efficiency in intervention: **Communicating** an innovation **to a special small subset** of potential adopters so that they, in turn, will **influence the vast majority of other potential adopters** to attend to, consider, adopt, implement, and maintain the use of worthy innovations. Our interventions must be high in reach but low in cost in order to most persuasively demonstrate worth in intervention.
>
>
>
It's talking about accessing a small group that would *reach* the larger (target) audience. | It's a somewhat vague term, and can be interpreted in several ways. But think of a person simply jumping to touch the highest point on a wall that they can achieve. "High in reach" basically means challenging you to reach as far up as you can. |
146,677 | Let $X\_t =x+bt+\sqrt{2}W\_t$, where $W\_t$ is a standard Brownian motion.
Let $T=\inf\{t: |X\_t|=1\}$. I am trying to find $\mathbb{E}[T]$ for the case $b\neq0$.
Firstly, I am going to apply Girsanov to change the measure and the drift:
$$M\_t = e^{-\frac{b}{\sqrt{2}}W\_t-\frac{b^2}{4}t},$$
If $\frac{d\mathbb{P}}{d\mathbb{Q}}|\mathcal{F}\_t=M\_t$, then
$\mathbb{E}[T|\mathcal{F\_t}]=\mathbb{E}^\mathbb{Q}[TM\_t|\mathcal{F\_t}]$. And under $\mathbb{Q}$, $X\_t$ is driftless BM.
So $\mathbb{E}^\mathbb{Q}[Te^{-\frac{b}{\sqrt{2}}W\_t-\frac{b^2}{4}t}|\mathcal{F\_t}]=\mathbb{E}^\mathbb{Q}[Te^{-\frac{b}{2}X\_t-\frac{b^2}{4}t+\frac{b}{2}x}|\mathcal{F}\_t]$
If I managed to show $T<\infty$ a.s., or otherwise, I could arrive at:
$$\mathbb{E}[T]=\mathbb{E}^\mathbb{Q}[Te^{-\frac{b}{2}X\_T-\frac{b^2}{4}T+\frac{b}{2}x}]=\mathbb{E}^\mathbb{Q}[Te^{-\frac{b^2}{4}T}]\mathbb{E}^\mathbb{Q}[e^{-\frac{b}{2}X\_T}]e^{\frac{b}{2}x}$$
Now
$$\mathbb{E}^\mathbb{Q}[e^{-\frac{b}{2}X\_T}]=e^{-\frac{b}{2}}\mathbb{P}^\mathbb{Q}(X\_T=1)+e^{\frac{b}{2}}\mathbb{P}^\mathbb{Q}(X\_T=-1)=e^{-\frac{b}{2}}\frac{1-x}{2}+e^{\frac{b}{2}}\frac{x+1}{2}$$
I have two questions:
1) How to compute $\mathbb{E}^\mathbb{Q}[Te^{-\frac{b^2}{4}T}]$
2) How to get around the problem that $T$ might not be finite?
**Edit:** 2) it's clear that $T<\infty$ under $\mathbb{Q}$, and so $T$ is $\mathbb{P}$-a.s. finite. | 2012/05/18 | [
"https://math.stackexchange.com/questions/146677",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/13205/"
]
| If I understand Tom's problem correctly, we are looking for the
two-sided first passage time ${\bf T}$ in a Wiener process $\{X(t), t \geq 0\}$
starting at $X(0)=x, \, -1 < x < +1$, with drift $b$, variance $2$,
and absorbing barriers at $-1$ and at $+1$.
This is a standard problem treated in many sources such as
Darling and Siegert (1953) who in their Theorem 6.1 and eq. (6.6) derive
the basic differential equation for $f(x) = {\sf E}[{\bf T}|X(0)=x]$,
which (in the present notation) is
$f^{''}(x) + b \, f^{'}(x) \; = \; -1$,
with $f(-1)=f(+1)=0$.
The solution is easily seen to be
$$
f(x) \; = \; {\sf E}[{\bf T}|X(0)=x] \; = \;
\frac{1}{b} \, \left\{ 2 \, \frac{1 - \exp[-b(1+x)]}{1 - \exp(-2b)} \, - \, (1+x) \, \right\}
$$ | I think $e^{-bX\_t}$ is a martingale, something like that is right, anyway. Using it you have $e^{bx} = e^{-ba}\mathbb P(X\_T = a) + e^{ba}\mathbb P(X\_T = -a)$, and $ 1 = \mathbb P(X\_T = a) +\mathbb P(X\_T = -a)$, from which you determine $\mathbb P(X\_T = a)$ and $\mathbb E(X\_T)$. Then Wald says $\mathbb E (X\_T) = b \mathbb E (T)$ |
923,683 | I was just thinking about infinity (as you do) and thought the following.
"There are infinitely many reals in the interval $x\in[0,1]$ and an *'equal number of reals'* $x\in[1,2]$, so there are *'double the number of reals'* in the interval $x\in[0,2]$ in comparison to $x\in[0,1]$"
Now I understand that the terminology I have italicized may be incorrect for whatever reason. I have a few questions regarding the statement.
1. Is there a branch of mathematics involving the 'measuring' or 'comparison' of infinities? My gut feeling is telling me something to do with set theory.
2. What key terms should I look up on Wikipedia regarding this?
3. The parts in italics, what is the 'correct' way of saying this, assuming it is incorrect to say it with that precise wording?
4. Using mathematical notation, how do we express the idea of one infinity being 'twice' the size of the other infinity? | 2014/09/08 | [
"https://math.stackexchange.com/questions/923683",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/141642/"
]
| 1. Yes. Set theory.
2. "Countable set" would be a good starting point on Wikipedia.
3. "Equal number of" is fine. The more formal term is that two sets have the "same cardinality"
"Double the number" is wrong.
You have to think what "equal number of" means for infinite sets. The answer is that there is a one-one correspondence between them (usually called a "bijection"). For example, $n\to2n$ is a bijection between the natural numbers and the (positive) even numbers.
4. Well "double" is not a useful concept for infinite numbers. Because if you have an infinite set and compare it with the result of "doubling it" you find they are the same size. More generally, what happens if you "multiply" or "add" infinite numbers is known as "cardinal arithmetic". | A way to write this using cardinal numbers is
$$|[0,1]| = |[1,2]| = 2^{\aleph\_0}$$
And
$$|[0,2]| = |[0,1]| + |[1,2]| = 2^{\aleph\_0} + 2^{\aleph\_0} = 2^{\aleph\_0}$$
Note the last equality seems irritating at first, but know that $|\mathbb R| = 2^{\aleph\_0}$ where $|\mathbb N| = \aleph\_0$. Two sets *have the same cardinality* if there exists a bijection between them.
From a measure-theoretic point of view, if we use the standard lebesgue measure, things are different, but may seem more natural to you:
$$\lambda([0,1]) = \lambda([1,2]) = 1$$
And
$$\lambda([0,2]) = \lambda([0,1]) + \lambda([1,2]) = 1+1 = 2$$
Note however that $\lambda(\mathbb R) = \infty, \lambda(\mathbb N) = 0$. |
28,355,238 | ```
uptime=$(uptime | sed 's/^.*up//;s/:/ hours and /; s/, load/ minutes, load/g')
```
The output is:
```
2 days, 3 hours and 41, load average: 0.04, 0.07, 0.10
```
I want the output to be like this:
```
2 days, 3 hours and 41 minutes, load average: 0.04, 0.07, 0.10
```
How do I do that with `sed` ? | 2015/02/05 | [
"https://Stackoverflow.com/questions/28355238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4534986/"
]
| ```
Sub Tester()
Dim labelCounter As Integer
Dim arrayTag() As String
Dim ct As String, ctl
labelCounter = 0
ReDim arrayTag(0 To labelCounter)
For Each ctl In Me.Controls
ct = TypeName(ctl)
If ct = "Label" Then
If labelCounter > 0 Then
ReDim Preserve arrayTag(0 To labelCounter)
End If
arrayTag(labelCounter) = ctl.Tag
labelCounter = labelCounter + 1
End If
Next
'Debug.Print Join(arrayTag, ",")
End Sub
``` | I think your only issue is you created an array (arrayTag) without specifying how many elements are in it. As far as I recall, when creating an array you need to either A.) Specify the number of elements in it, or B.) Create an array the way you did (With empty parenthesis) and then `ReDim` it once you reach a point in the code execution where you know how many elements are in it. I think you can also `ReDim Preserve` to change the size of the array without deleting its contents.
```
Dim labelCounter As Integer
labelCounter = 0
Dim arrayTag(50) As String
For Each ctl In Me.Controls
Select Case TypeName(ctl)
Case "Label"
arrayTag(labelCounter) = ctl.Tag
labelCounter = labelCounter + 1
End Select
Next
``` |
26,376,341 | I have an input dialog (Qt) with three options in a combobox. I would like a different action be launched on the Ok depending on the item which was selected in the combobox. For now, I have
```
QInputDialog qDialog ;
QStringList items;
items << QString("Choice 1");
items << QString("Choice 2");
items << QString("Choice 3");
qDialog.setOptions(QInputDialog::UseListViewForComboBoxItems);
qDialog.setComboBoxItems(items);
qDialog.setWindowTitle("Choose action");
QObject::connect(&qDialog, SIGNAL(textValueChanged(const QString &)),
this, SLOT(onCompute(const QString &)));
qDialog.exec();
```
The slot `oncompute` performs a different action depending on the selected item in the combobox... but this is called when the user selects a new item in the box, not on click on ok.
How can i retrieve the item selected on the combo box and perform action on click on Ok ? | 2014/10/15 | [
"https://Stackoverflow.com/questions/26376341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1141493/"
]
| Try to add Pods.debug into your project -> Info -> Configurations -> Debug, and Pods.release into Release section. I solve my missing 'RestKit.h' problem by this setting.
 | Try to write your podfile in that way:
```
source 'https://github.com/CocoaPods/Specs.git'
link_with ['PocketLobbyiOS', 'PocketLobbyiOSTests']
platform :ios, '6.0'
pod 'MWPhotoBrowser', :git => 'https://github.com/floriankrueger/MWPhotoBrowser.git', :tag => '1.4.1'
pod 'TestFlightSDK', '~> 3.0.2'
pod 'RestKit', '~> 0.23.1'
pod 'RestKit/ObjectMapping'
pod 'RestKit/Search'
pod 'RestKit/Testing'
pod 'PKRevealController', '~> 2.0.6'
pod 'Mapbox', :git => 'https://github.com/mapbox/mapbox-ios-sdk.git', :tag => '1.2.0'
pod 'MagicalRecord/Shorthand', '~> 2.2'
pod 'DDPageControl', '~> 0.1'
pod 'MWPhotoBrowser'
pod 'Reachability', '~> 3.1.1'
pod 'Mixpanel', '~> 2.4.0'
pod 'OHAttributedLabel', '~> 3.5.4'
# ignore all warnings from all pods
inhibit_all_warnings!
post_install do |installer_representation|
installer_representation.project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
end
end
end
```
Install pod, and at your project Build Setting->Other Linker Flags, add $(inherited). |
43,442,452 | I have the following code and I want for every `H2` with `id` attribute I would create an anchor link. I can not get it to work properly...
```
<div id="mydiv">
<h2 id="first">first</h2>
<h2>second</h2>
<h2 id="third">third</h2>
</div>
.sls {color: red;font-size: 12px;}
$('#mydiv')
.find('h2[id]')
.append(' <a href="http://www.test.com/page.html#'+ $('h2[id]')
.attr('id') +'" class="sls">Link</a>');
```
**<https://jsfiddle.net/ivanionut/1ohh2hws/>**
Thanks for your help. | 2017/04/16 | [
"https://Stackoverflow.com/questions/43442452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247090/"
]
| You can use `groupby.transform` with `nunique()` function to count the number of unique elements per *id*:
```
df['nos'] = df.groupby("id")['acct_nos'].transform("nunique")
df
```
[](https://i.stack.imgur.com/be9ri.png) | ***option 1***
```
df.assign(nos=df.id.map(df.drop_duplicates(['id', 'acct_nos']).id.value_counts()))
```
***option 2***
Using `Counter`
```
from collections import Counter
tups = pd.unique(
zip(df.id.values.tolist(), df.acct_nos.values.tolist())
).tolist()
df.assign(nos=df.id.map(Counter([tup[0] for tup in tups])))
id acct_nos name nos
0 1 1a one 1
1 1 1a two 1
2 2 2b three 1
3 3 3a four 4
4 3 3b five 4
5 3 3c six 4
6 3 3d seven 4
``` |
2,094,967 | I have the \*expression
$$\frac{1}{\sqrt{4a^2-b^2}}$$
and I am being asked to evaluate the case when $2|a| \geq|b|$
Logically I know what this statement mean but don't know how it applies to this problem: Cases when $a$ is twice greater than the distance of $b$ is from $0$.
(Correct me if i'm wrong)
I also know that absolute values on both sides of an equation are inpracticle and it would be better to write the inequality as $|a/b| \geq 1/2$.
Which can also be written as $a/b \geq 1/2$ or $a/b \leq 1/2$ which doesn't make any sense.
here's a link to the problem (#3)
[http://imgur.com/a/GheWI](https://imgur.com/a/GheWI)
Thank you, I would appreciate help I've been struggling with this for a while | 2017/01/12 | [
"https://math.stackexchange.com/questions/2094967",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/309332/"
]
| In addition to the things answered here, I just want to add this one.
**Proposition** Let $G$ be a finite group and $H$ a subgroup of prime *index* $p$, with gcd$(|G|,p-1)=1$. Then $G' \subseteq H$.
Note that this implies that $H \unlhd G$, and that it is in fact sufficient to prove that $H$ is normal, since then $G/H \cong C\_p$ is abelian.
**Proof** Firstly, we may assume by induction on $|G|$, that $H$ is core-free, that is core$\_G(H)=\bigcap\_{g \in G}H^g=1$. This means that $G$ can be homomorphically embedded in $S\_p$. Let $P \in Syl\_p(G)$ and note that because $|S\_p|=p \cdot (p-1) \cdots \cdot 1$, $|P|=p$. By the $N/C$-Theorem, $N\_G(P)/C\_G(P)$ embeds in Aut$(P) \cong C\_{p-1}$. By the assumption gcd$(|G|,p-1)=1$, we get that $N\_G(P)=C\_G(P)$. Since $P$ is abelian we have $P \subseteq C\_G(P)$, whence $P \subseteq Z(N\_G(P))$. We now can apply Burnside's Normal $p$-complement Theorem, which implies that $P$ has a normal complement $N$, that is $G=PN$ and $P \cap N=1$. Note that $|G/N|=p$. Look at the image of $H$ in $G/N$. Then $G=HN$, or $HN=N$. In the latter case $H \subseteq N$, and $|G:H|=|G:N|=p$, whence $H=N$ and we are done if we can refute the first case. If $G=HN$, then $|G:H \cap N|=|G:N|\cdot|N:H \cap N|=|G:N|\cdot |G:H|=p \cdot p=p^2$, contradicting the fact that $|G| \mid |S\_p|$. The proof is now complete.
**Corollary 1** Let $G$ be a finite group and let $H$ be a subgroup with $|G:H|=p$, the *smallest* prime dividing the order of $G$. Then $G' \subseteq H$. In particular, $H$ is normal.
**Corollary 2** Let $G$ be a finite group and let $H$ be a subgroup with $|G:H|=p$ and gcd$(|H|,p-1)=1$. Then $H$ is normal.
Observe that this last result renders a well-known result for $p=2$! Finally for fun:
**Corollary 3** Let $G$ be a finite group of *odd* order and $H$ a subgroup with $|G:H|=65537$. Then $H$ is normal. | Yes. If $p$ is the smallest prime dividing the order of $G$ and $[G : H] = p$, then $H \trianglelefteq G$. This is a corollary of what is commonly referred to as the [Strong Cayley Theorem](http://www.mathreference.com/grp-act,cayley.html). See the final corollary of [this document](https://math.la.asu.edu/~kawski/classes/mat444/handouts/strongCayley.pdf) for a proof. |
22,260 | There's a certain kind of people who like to hoard whatever limited resources they get "just in case"; they usually end up never using them, always waiting for bigger emergency. On the other hand, there are game mechanics based on spending some limited resourse: like bennies in Savage Worlds, fortune points in Warhammer, etc. You're supposed to spend them liberally, getting some in-game benefits.
The "hoarders" never spend these, robbing themselves of part of enjoyment. Simply explaining that "those point are meant to be spent" doesn't always work: players seem to understand that rationally, but some force of habit still prevents them from actually using their resources. I think this happens more often in videogames (I myself am guilty of hoarding all goodies till the end boss, and then never needing them), but I've seen this kind of behaviour in tabletop games too.
Of course, some players do this because they just like hoarding, or because they like the additional challenge, but some do notice that they're "doing it wrong."
Is there maybe some sort of trick to encourage resource spending?
**Clarification**
I'm mostly interested in "mechanical" resources like fate points and bennies. If you hoard something material, like potions, or money, at least you (probably) have more money as a result. When you hoard bennies, you essentially forfeit your chance to *do* something that matters. This is probably not what players want. | 2013/02/20 | [
"https://rpg.stackexchange.com/questions/22260",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3406/"
]
| Since Fate points are mentioned, I'm going to mention the angle offered by the great [fate](/questions/tagged/fate "show questions tagged 'fate'") based game [diaspora](/questions/tagged/diaspora "show questions tagged 'diaspora'"). In Diaspora, players start every session with five Fate points. It does not matter if they ended the previous session with ten or zero, every new session resets the count. *Use it or lose it* is the key phrase here.
This pushes players to spend what they have. They won't be keeping it anyway. | **Give out bennies like candy.** No, really. As long as your PCs are comfortable with the "refresh rate" of their valuable resources, they stop being all that valuable.
Don't forget to award the antagonists with something also - more mooks, more bennies, whatever. Your players should not feel the game suddenly becoming easier, but the opposite (you're aiming for "Man, we're lucky we spent all those bennies, otherwise we'd be toast now!").
Once they grow out of hoarding, you can dial down a bit and reward only their best moments with ~~candy~~ bennies. |
22,260 | There's a certain kind of people who like to hoard whatever limited resources they get "just in case"; they usually end up never using them, always waiting for bigger emergency. On the other hand, there are game mechanics based on spending some limited resourse: like bennies in Savage Worlds, fortune points in Warhammer, etc. You're supposed to spend them liberally, getting some in-game benefits.
The "hoarders" never spend these, robbing themselves of part of enjoyment. Simply explaining that "those point are meant to be spent" doesn't always work: players seem to understand that rationally, but some force of habit still prevents them from actually using their resources. I think this happens more often in videogames (I myself am guilty of hoarding all goodies till the end boss, and then never needing them), but I've seen this kind of behaviour in tabletop games too.
Of course, some players do this because they just like hoarding, or because they like the additional challenge, but some do notice that they're "doing it wrong."
Is there maybe some sort of trick to encourage resource spending?
**Clarification**
I'm mostly interested in "mechanical" resources like fate points and bennies. If you hoard something material, like potions, or money, at least you (probably) have more money as a result. When you hoard bennies, you essentially forfeit your chance to *do* something that matters. This is probably not what players want. | 2013/02/20 | [
"https://rpg.stackexchange.com/questions/22260",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3406/"
]
| Since Fate points are mentioned, I'm going to mention the angle offered by the great [fate](/questions/tagged/fate "show questions tagged 'fate'") based game [diaspora](/questions/tagged/diaspora "show questions tagged 'diaspora'"). In Diaspora, players start every session with five Fate points. It does not matter if they ended the previous session with ten or zero, every new session resets the count. *Use it or lose it* is the key phrase here.
This pushes players to spend what they have. They won't be keeping it anyway. | Something I do with fate points is impose a five point limit. So, the only way they can get additional points is to spend what they have first. |
22,260 | There's a certain kind of people who like to hoard whatever limited resources they get "just in case"; they usually end up never using them, always waiting for bigger emergency. On the other hand, there are game mechanics based on spending some limited resourse: like bennies in Savage Worlds, fortune points in Warhammer, etc. You're supposed to spend them liberally, getting some in-game benefits.
The "hoarders" never spend these, robbing themselves of part of enjoyment. Simply explaining that "those point are meant to be spent" doesn't always work: players seem to understand that rationally, but some force of habit still prevents them from actually using their resources. I think this happens more often in videogames (I myself am guilty of hoarding all goodies till the end boss, and then never needing them), but I've seen this kind of behaviour in tabletop games too.
Of course, some players do this because they just like hoarding, or because they like the additional challenge, but some do notice that they're "doing it wrong."
Is there maybe some sort of trick to encourage resource spending?
**Clarification**
I'm mostly interested in "mechanical" resources like fate points and bennies. If you hoard something material, like potions, or money, at least you (probably) have more money as a result. When you hoard bennies, you essentially forfeit your chance to *do* something that matters. This is probably not what players want. | 2013/02/20 | [
"https://rpg.stackexchange.com/questions/22260",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3406/"
]
| **Give out bennies like candy.** No, really. As long as your PCs are comfortable with the "refresh rate" of their valuable resources, they stop being all that valuable.
Don't forget to award the antagonists with something also - more mooks, more bennies, whatever. Your players should not feel the game suddenly becoming easier, but the opposite (you're aiming for "Man, we're lucky we spent all those bennies, otherwise we'd be toast now!").
Once they grow out of hoarding, you can dial down a bit and reward only their best moments with ~~candy~~ bennies. | Another possibility besides "limited inventory/carry weight" and "expiry date" is **inflation**. Have the resources become worth less, the more the game advances.
At the start of the game, 10 gold is a lot of money. Mid-campaign, every common thief carries 50 gold, shopkeepers have raised their prices. You were better off spending the gold than hoarding it, since it's worth nothing. |
22,260 | There's a certain kind of people who like to hoard whatever limited resources they get "just in case"; they usually end up never using them, always waiting for bigger emergency. On the other hand, there are game mechanics based on spending some limited resourse: like bennies in Savage Worlds, fortune points in Warhammer, etc. You're supposed to spend them liberally, getting some in-game benefits.
The "hoarders" never spend these, robbing themselves of part of enjoyment. Simply explaining that "those point are meant to be spent" doesn't always work: players seem to understand that rationally, but some force of habit still prevents them from actually using their resources. I think this happens more often in videogames (I myself am guilty of hoarding all goodies till the end boss, and then never needing them), but I've seen this kind of behaviour in tabletop games too.
Of course, some players do this because they just like hoarding, or because they like the additional challenge, but some do notice that they're "doing it wrong."
Is there maybe some sort of trick to encourage resource spending?
**Clarification**
I'm mostly interested in "mechanical" resources like fate points and bennies. If you hoard something material, like potions, or money, at least you (probably) have more money as a result. When you hoard bennies, you essentially forfeit your chance to *do* something that matters. This is probably not what players want. | 2013/02/20 | [
"https://rpg.stackexchange.com/questions/22260",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3406/"
]
| Interesting question and one that I'm gonna have to solve soon too for my gaming group has similar issues (They don't hoard. They sell it all to buy permanent magic items. But as you can see at least half of the solution I've adopted will apply to both situations.)
This mission/session only
-------------------------
The first half of the solution is taken from a videogame called Thief.
At the end of each mission you lose all your unused items and keep every treasure you collected during that mission.
At the beginning of the next mission, you can use that treasure to buy a wide array of arrows and other trinkets.
You might apply a similar strategy to your missions or even sessions, that heavily depends on your tastes and needs.
This applies greatly to mechanical resources as you requested in your clarification! But often potions and the like are just supposed to be used and not converted to some other type of advantage.
Let's take it to the next step:
The percentile issue
--------------------
The second half of the solution takes care of what happens if, seeing that these items are gonna disappear soon, the players try to monetize them.
Choose a percentage of treasure that should only be used to buy (or should be made of) consumables, while maybe the other treasure can't be used to buy potions and the like. (In this case remember to always include tham in your treasure parcels.)
In my D&D 3.5 game that would be 10% as suggested by the books.
Even if they sell those goods, that gold can only be used to buy different consumables (maybe a parallel economy system with different coins?). | Another possibility besides "limited inventory/carry weight" and "expiry date" is **inflation**. Have the resources become worth less, the more the game advances.
At the start of the game, 10 gold is a lot of money. Mid-campaign, every common thief carries 50 gold, shopkeepers have raised their prices. You were better off spending the gold than hoarding it, since it's worth nothing. |
22,260 | There's a certain kind of people who like to hoard whatever limited resources they get "just in case"; they usually end up never using them, always waiting for bigger emergency. On the other hand, there are game mechanics based on spending some limited resourse: like bennies in Savage Worlds, fortune points in Warhammer, etc. You're supposed to spend them liberally, getting some in-game benefits.
The "hoarders" never spend these, robbing themselves of part of enjoyment. Simply explaining that "those point are meant to be spent" doesn't always work: players seem to understand that rationally, but some force of habit still prevents them from actually using their resources. I think this happens more often in videogames (I myself am guilty of hoarding all goodies till the end boss, and then never needing them), but I've seen this kind of behaviour in tabletop games too.
Of course, some players do this because they just like hoarding, or because they like the additional challenge, but some do notice that they're "doing it wrong."
Is there maybe some sort of trick to encourage resource spending?
**Clarification**
I'm mostly interested in "mechanical" resources like fate points and bennies. If you hoard something material, like potions, or money, at least you (probably) have more money as a result. When you hoard bennies, you essentially forfeit your chance to *do* something that matters. This is probably not what players want. | 2013/02/20 | [
"https://rpg.stackexchange.com/questions/22260",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3406/"
]
| I don't think you should think of this as a "trick". I think the players are being rational. They are doing all right without spending the resources, and they have no idea what is coming up, that may require them.
So just make it rational to spend them. Have lasting rewards that make spending them worthwhile even when there is some risk of running out of the resource and not having it when they really do need it, or, I suppose, have them suffer permanent adverse consequences for *not* spending them. | Are you trying to change your players'/characters' personalities? Maybe! (Of course since it's an RPG that could be fun... read on)
Your question is asking about fungible resources, has no uniquenesss value, but *stores* value, and can be *spent* to gain some benefit... hey, sounds a lot like the economic definition of money, don't you think?
When it comes to money you can lump people into two types of behavior: spenders, (living more or less paycheck to paycheck) and savers/investors. You have just identified some of your players as savers.
Now since it's an RPG, maybe you should encourage players who tend to be savers, to imagine their character as being a little different, act like a wild spender for a change! When phrased that way it could be a liberating experience.
Just try not to let it come out as 'Come on, you guys never spend anything!' as your player could just take it as personal criticism. |
22,260 | There's a certain kind of people who like to hoard whatever limited resources they get "just in case"; they usually end up never using them, always waiting for bigger emergency. On the other hand, there are game mechanics based on spending some limited resourse: like bennies in Savage Worlds, fortune points in Warhammer, etc. You're supposed to spend them liberally, getting some in-game benefits.
The "hoarders" never spend these, robbing themselves of part of enjoyment. Simply explaining that "those point are meant to be spent" doesn't always work: players seem to understand that rationally, but some force of habit still prevents them from actually using their resources. I think this happens more often in videogames (I myself am guilty of hoarding all goodies till the end boss, and then never needing them), but I've seen this kind of behaviour in tabletop games too.
Of course, some players do this because they just like hoarding, or because they like the additional challenge, but some do notice that they're "doing it wrong."
Is there maybe some sort of trick to encourage resource spending?
**Clarification**
I'm mostly interested in "mechanical" resources like fate points and bennies. If you hoard something material, like potions, or money, at least you (probably) have more money as a result. When you hoard bennies, you essentially forfeit your chance to *do* something that matters. This is probably not what players want. | 2013/02/20 | [
"https://rpg.stackexchange.com/questions/22260",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3406/"
]
| I don't think you should think of this as a "trick". I think the players are being rational. They are doing all right without spending the resources, and they have no idea what is coming up, that may require them.
So just make it rational to spend them. Have lasting rewards that make spending them worthwhile even when there is some risk of running out of the resource and not having it when they really do need it, or, I suppose, have them suffer permanent adverse consequences for *not* spending them. | Interesting question and one that I'm gonna have to solve soon too for my gaming group has similar issues (They don't hoard. They sell it all to buy permanent magic items. But as you can see at least half of the solution I've adopted will apply to both situations.)
This mission/session only
-------------------------
The first half of the solution is taken from a videogame called Thief.
At the end of each mission you lose all your unused items and keep every treasure you collected during that mission.
At the beginning of the next mission, you can use that treasure to buy a wide array of arrows and other trinkets.
You might apply a similar strategy to your missions or even sessions, that heavily depends on your tastes and needs.
This applies greatly to mechanical resources as you requested in your clarification! But often potions and the like are just supposed to be used and not converted to some other type of advantage.
Let's take it to the next step:
The percentile issue
--------------------
The second half of the solution takes care of what happens if, seeing that these items are gonna disappear soon, the players try to monetize them.
Choose a percentage of treasure that should only be used to buy (or should be made of) consumables, while maybe the other treasure can't be used to buy potions and the like. (In this case remember to always include tham in your treasure parcels.)
In my D&D 3.5 game that would be 10% as suggested by the books.
Even if they sell those goods, that gold can only be used to buy different consumables (maybe a parallel economy system with different coins?). |
22,260 | There's a certain kind of people who like to hoard whatever limited resources they get "just in case"; they usually end up never using them, always waiting for bigger emergency. On the other hand, there are game mechanics based on spending some limited resourse: like bennies in Savage Worlds, fortune points in Warhammer, etc. You're supposed to spend them liberally, getting some in-game benefits.
The "hoarders" never spend these, robbing themselves of part of enjoyment. Simply explaining that "those point are meant to be spent" doesn't always work: players seem to understand that rationally, but some force of habit still prevents them from actually using their resources. I think this happens more often in videogames (I myself am guilty of hoarding all goodies till the end boss, and then never needing them), but I've seen this kind of behaviour in tabletop games too.
Of course, some players do this because they just like hoarding, or because they like the additional challenge, but some do notice that they're "doing it wrong."
Is there maybe some sort of trick to encourage resource spending?
**Clarification**
I'm mostly interested in "mechanical" resources like fate points and bennies. If you hoard something material, like potions, or money, at least you (probably) have more money as a result. When you hoard bennies, you essentially forfeit your chance to *do* something that matters. This is probably not what players want. | 2013/02/20 | [
"https://rpg.stackexchange.com/questions/22260",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3406/"
]
| Guarantee Results for Fate/Bennies/Roll Bonuses
-----------------------------------------------
We play D&D4e. I grant my players +1/-1 tokens for role-playing, doing out-of-character tasks (such as uploading photos, completing character histories, etc.), leveling, milestones, quests, etc. These tokens can by used to move any die-roll result +1 or -1 and may stack.
You'd think that they'd horde these like crazy, but *they usually run out before the end of a gaming session* - and here's why:
I tell them whenever a certain number would turn a miss into a hit - or when x points of additional damage would take the monster down - or how much more they need to make a critical skill check. ***They often decide to spend them.***
A guaranteed result is a huge incentive.
This has a great side-effect: The game (especially combat) moves forward quickly. With this little tweak the players have control of how fast they move through the story (burn resources.) | Are you trying to change your players'/characters' personalities? Maybe! (Of course since it's an RPG that could be fun... read on)
Your question is asking about fungible resources, has no uniquenesss value, but *stores* value, and can be *spent* to gain some benefit... hey, sounds a lot like the economic definition of money, don't you think?
When it comes to money you can lump people into two types of behavior: spenders, (living more or less paycheck to paycheck) and savers/investors. You have just identified some of your players as savers.
Now since it's an RPG, maybe you should encourage players who tend to be savers, to imagine their character as being a little different, act like a wild spender for a change! When phrased that way it could be a liberating experience.
Just try not to let it come out as 'Come on, you guys never spend anything!' as your player could just take it as personal criticism. |
22,260 | There's a certain kind of people who like to hoard whatever limited resources they get "just in case"; they usually end up never using them, always waiting for bigger emergency. On the other hand, there are game mechanics based on spending some limited resourse: like bennies in Savage Worlds, fortune points in Warhammer, etc. You're supposed to spend them liberally, getting some in-game benefits.
The "hoarders" never spend these, robbing themselves of part of enjoyment. Simply explaining that "those point are meant to be spent" doesn't always work: players seem to understand that rationally, but some force of habit still prevents them from actually using their resources. I think this happens more often in videogames (I myself am guilty of hoarding all goodies till the end boss, and then never needing them), but I've seen this kind of behaviour in tabletop games too.
Of course, some players do this because they just like hoarding, or because they like the additional challenge, but some do notice that they're "doing it wrong."
Is there maybe some sort of trick to encourage resource spending?
**Clarification**
I'm mostly interested in "mechanical" resources like fate points and bennies. If you hoard something material, like potions, or money, at least you (probably) have more money as a result. When you hoard bennies, you essentially forfeit your chance to *do* something that matters. This is probably not what players want. | 2013/02/20 | [
"https://rpg.stackexchange.com/questions/22260",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3406/"
]
| Before any change, talk with your players to let them know it's a problem. If they don't fix it themselves, then here's a few options:
1. Limit the maximum number of beanies a player can have at any time.
2. Limit the number of total beanies available to all the players. Once they're in the players hands, no more are available.
3. Have a maximum number of beanies available to be carried over from one session to another, with the excess beanies vanish, turn into gold, XP, etc.
4. Be more conservative on your awarding of beanies.
5. Get rid of the beanie system altogether. If the players are hoarding the beanies, they don't need them.
6. Overwhelm the PC's so they're forced to use their beanies or die. | Are you trying to change your players'/characters' personalities? Maybe! (Of course since it's an RPG that could be fun... read on)
Your question is asking about fungible resources, has no uniquenesss value, but *stores* value, and can be *spent* to gain some benefit... hey, sounds a lot like the economic definition of money, don't you think?
When it comes to money you can lump people into two types of behavior: spenders, (living more or less paycheck to paycheck) and savers/investors. You have just identified some of your players as savers.
Now since it's an RPG, maybe you should encourage players who tend to be savers, to imagine their character as being a little different, act like a wild spender for a change! When phrased that way it could be a liberating experience.
Just try not to let it come out as 'Come on, you guys never spend anything!' as your player could just take it as personal criticism. |
22,260 | There's a certain kind of people who like to hoard whatever limited resources they get "just in case"; they usually end up never using them, always waiting for bigger emergency. On the other hand, there are game mechanics based on spending some limited resourse: like bennies in Savage Worlds, fortune points in Warhammer, etc. You're supposed to spend them liberally, getting some in-game benefits.
The "hoarders" never spend these, robbing themselves of part of enjoyment. Simply explaining that "those point are meant to be spent" doesn't always work: players seem to understand that rationally, but some force of habit still prevents them from actually using their resources. I think this happens more often in videogames (I myself am guilty of hoarding all goodies till the end boss, and then never needing them), but I've seen this kind of behaviour in tabletop games too.
Of course, some players do this because they just like hoarding, or because they like the additional challenge, but some do notice that they're "doing it wrong."
Is there maybe some sort of trick to encourage resource spending?
**Clarification**
I'm mostly interested in "mechanical" resources like fate points and bennies. If you hoard something material, like potions, or money, at least you (probably) have more money as a result. When you hoard bennies, you essentially forfeit your chance to *do* something that matters. This is probably not what players want. | 2013/02/20 | [
"https://rpg.stackexchange.com/questions/22260",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3406/"
]
| It's their bennies to hoard, if they so wish. Personally, I wouldn't push or try to trick them as GM, but I would reinforce the benefits when the other players spend them. | Another possibility besides "limited inventory/carry weight" and "expiry date" is **inflation**. Have the resources become worth less, the more the game advances.
At the start of the game, 10 gold is a lot of money. Mid-campaign, every common thief carries 50 gold, shopkeepers have raised their prices. You were better off spending the gold than hoarding it, since it's worth nothing. |
22,260 | There's a certain kind of people who like to hoard whatever limited resources they get "just in case"; they usually end up never using them, always waiting for bigger emergency. On the other hand, there are game mechanics based on spending some limited resourse: like bennies in Savage Worlds, fortune points in Warhammer, etc. You're supposed to spend them liberally, getting some in-game benefits.
The "hoarders" never spend these, robbing themselves of part of enjoyment. Simply explaining that "those point are meant to be spent" doesn't always work: players seem to understand that rationally, but some force of habit still prevents them from actually using their resources. I think this happens more often in videogames (I myself am guilty of hoarding all goodies till the end boss, and then never needing them), but I've seen this kind of behaviour in tabletop games too.
Of course, some players do this because they just like hoarding, or because they like the additional challenge, but some do notice that they're "doing it wrong."
Is there maybe some sort of trick to encourage resource spending?
**Clarification**
I'm mostly interested in "mechanical" resources like fate points and bennies. If you hoard something material, like potions, or money, at least you (probably) have more money as a result. When you hoard bennies, you essentially forfeit your chance to *do* something that matters. This is probably not what players want. | 2013/02/20 | [
"https://rpg.stackexchange.com/questions/22260",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/3406/"
]
| *Is there maybe some sort of trick to encourage resource spending?*
Yeah - have a look at real life first. What prevents you from hoarding anything you can afford to acquire? Two things:
1. storage space/costs.
2. some goods have a "best before" date (or require even more storage resources)
Note that 2 applies even to non-physical things. I.e. if you learned French in high school "just in case", you will probably lose most of it unless you practice it, watch French movies, go to refresh courses and so on.
So, if it's a in-world resource (like potions), see that points 1&2 apply. If the PC is hoarding stuff and carrying it along all the time, apply saving throws to see if any of that is damaged when he is hit, too (AD&D had something this since the oldest editions for example).
If it is a "meta-gaming" resource like bennies, experience points, fate points, hero points etc. ... enforce some "stale/storage" scheme.
Like "you can't ever hold more than your level in fate points - if you are 7th Level and get one extra fate point you lose it automatically". | **Give out bennies like candy.** No, really. As long as your PCs are comfortable with the "refresh rate" of their valuable resources, they stop being all that valuable.
Don't forget to award the antagonists with something also - more mooks, more bennies, whatever. Your players should not feel the game suddenly becoming easier, but the opposite (you're aiming for "Man, we're lucky we spent all those bennies, otherwise we'd be toast now!").
Once they grow out of hoarding, you can dial down a bit and reward only their best moments with ~~candy~~ bennies. |
20,754,792 | I have a text file called "graphics" which contains the words "deoxyribonucleic acid".
When I run this code it works and it returns the first character. "d"
```
int main(){
FILE *fileptr;
fileptr = fopen("graphics.txt", "r");
char name;
if(fileptr != NULL){ printf("hey \n"); }
else{ printf("Error"); }
fscanf( fileptr, "%c", &name);
printf("%c\n", name);
fclose( fileptr );
return 0;
}
```
When I am using the `fscanf` function the parameters I am sending are the name of the FILE object, the type of data the function will read, and the name of the object it is going to store said data, correct? Also, why is it that I have to put an `&` in front of name in `fscanf` but not in `printf`?
Now, I want to have the program read the file and grab the first word and store it in name.
I understand that this will have to be a string (An array of characters).
So what I did was this:
I made name into an array of characters that can store 20 elements.
```
char name[20];
```
And changed the parameters in `fscanf` and `printf` to this, respectively:
```
fscanf( fileptr, "%s", name);
printf("%s\n", name);
```
Doing so produces no errors from the compiler but the program crashes and I don't understand why. I am letting `fscanf` know that I want it to read a string and I am also letting `printf` know that it will output a string. Where did I go wrong? How would I accomplish said task? | 2013/12/24 | [
"https://Stackoverflow.com/questions/20754792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977742/"
]
| For some reason, `/usr/local/bin/pip` is a symlink pointing to itself, and `easy_install` is getting confused trying to write to it, instead of just deleting it first. You can do that yourself by running
```
sudo rm /usr/local/bin/pip
```
then rerunning the installation process. | This may have nothing to do with python. Infinite recursion may be the cause. You can create a symbolic link to a non-existent file under Linux (Linux MYMachine 2.6.32-573.7.1.el6.x86\_64 #1 SMP Tue Sep 22 22:00:00 UTC 2015 x86\_64 x86\_64 x86\_64 GNU/Linux)
Here norealfile.fa is a link to self.
```
norealfile.fa -> /some/real/dir/norealfile.fa
```
Under linux, if you do
```
ls /some/real/dir/norealfile.fa
```
You should get an error message:
```
ls: cannot access /some/real/dir/norealfile.fa: Too many levels of symbolic links
```
In Mac OS, you will get "ls: /some/real/dir/norealfile.fa No such file or directory"
Let me know if you get something else on your OS. The implementation detail of symbolic link in different OS may dictate the exact behavior of self referencing symbolic links. |
1,263,732 | >
> **Possible Duplicate:**
>
> [Format a Microsoft JSON date?](https://stackoverflow.com/questions/206384)
>
>
>
The ASP.NET function `Json()` formats and returns a date as
```
{"d":"\/Date(1240718400000)\/"}
```
which has to be dealt with on the client side which is problematic. What are your suggestions for approaches to sending date values back and forth? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1263732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94508/"
]
| Not everyone agrees with me that it's a good idea, but I find myself most often returning formatted strings instead of proper dates. See *[How I handle JSON dates returned by ASP.NET AJAX](http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/)*. | After playing with the Json.NET library, I'm wondering why you would choose to use the IsoDateTimeConverter over the JavascriptDateTimeConverter.
I found this to be easier to use with the [Ext JS](http://en.wikipedia.org/wiki/Ext_JS) interfaces that I was using when serializing dates from an MVC Controller.
```
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.Formatting = Formatting.Indented;
jsonNetResult.SerializerSettings.Converters.Add(new JavaScriptDateTimeConverter());
jsonNetResult.Data = myObject;
```
I'm getting this data back into an Ext.data.JsonStore which is able to get the returned value as a date without me having to specify a date format to parse with.
```
store:new Ext.data.JsonStore({
url: pathContext + '/Subject.mvc/Notices',
baseParams: { subjectId: this.subjectId },
fields: [
{name: 'Title'},
{name: 'DateCreated', type: 'date' }
]
}),
```
The JSON returned looks like this:
```
[{"Title":"Some title","DateCreated":new Date(1259175818323)}]
```
There isn't any reason to convert to ISO 8601 format and back if you don't have to. |
1,263,732 | >
> **Possible Duplicate:**
>
> [Format a Microsoft JSON date?](https://stackoverflow.com/questions/206384)
>
>
>
The ASP.NET function `Json()` formats and returns a date as
```
{"d":"\/Date(1240718400000)\/"}
```
which has to be dealt with on the client side which is problematic. What are your suggestions for approaches to sending date values back and forth? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1263732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94508/"
]
| If you are not tied to the MS JSON serializer you could use [Json.NET](http://www.codeplex.com/Json). It comes with an IsoDateTimeConverter to handle issues with serializing dates. This will serialize dates into an [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) formatted string.
For instance, in our project serializing `myObject` is handled via the following code.
```
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.Formatting = Formatting.Indented;
jsonNetResult.SerializerSettings.Converters.Add(new IsoDateTimeConverter());
jsonNetResult.Data = myObject;
```
If you decide to take the Json.NET plunge you'll also want to grab [JsonNetResult](http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx) as it returns an ActionResult that can be used in ASP.NET MVC application. It's quite easy to use.
For more info see: [Good (Date)Times with Json.NET](http://james.newtonking.com/archive/2009/02/20/good-date-times-with-json-net.aspx) | It may be ugly, but it works:
```
var epoch = (new RegExp('/Date\\((-?[0-9]+)\\)/')).exec(d);
$("#field").text((new Date(parseInt(epoch[1]))).toDateString());
```
Probably, it is not necessary to match the whole string, and just (-?[0-9]+) is enough... |
1,263,732 | >
> **Possible Duplicate:**
>
> [Format a Microsoft JSON date?](https://stackoverflow.com/questions/206384)
>
>
>
The ASP.NET function `Json()` formats and returns a date as
```
{"d":"\/Date(1240718400000)\/"}
```
which has to be dealt with on the client side which is problematic. What are your suggestions for approaches to sending date values back and forth? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1263732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94508/"
]
| This was found in [another post](https://stackoverflow.com/questions/206384/how-to-format-json-date) on Stack Overflow:
```
var date = new Date(parseInt(jsonDate.substr(6)));
```
The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end. The resulting number is passed into the Date constructor. | It may be ugly, but it works:
```
var epoch = (new RegExp('/Date\\((-?[0-9]+)\\)/')).exec(d);
$("#field").text((new Date(parseInt(epoch[1]))).toDateString());
```
Probably, it is not necessary to match the whole string, and just (-?[0-9]+) is enough... |
1,263,732 | >
> **Possible Duplicate:**
>
> [Format a Microsoft JSON date?](https://stackoverflow.com/questions/206384)
>
>
>
The ASP.NET function `Json()` formats and returns a date as
```
{"d":"\/Date(1240718400000)\/"}
```
which has to be dealt with on the client side which is problematic. What are your suggestions for approaches to sending date values back and forth? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1263732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94508/"
]
| After playing with the Json.NET library, I'm wondering why you would choose to use the IsoDateTimeConverter over the JavascriptDateTimeConverter.
I found this to be easier to use with the [Ext JS](http://en.wikipedia.org/wiki/Ext_JS) interfaces that I was using when serializing dates from an MVC Controller.
```
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.Formatting = Formatting.Indented;
jsonNetResult.SerializerSettings.Converters.Add(new JavaScriptDateTimeConverter());
jsonNetResult.Data = myObject;
```
I'm getting this data back into an Ext.data.JsonStore which is able to get the returned value as a date without me having to specify a date format to parse with.
```
store:new Ext.data.JsonStore({
url: pathContext + '/Subject.mvc/Notices',
baseParams: { subjectId: this.subjectId },
fields: [
{name: 'Title'},
{name: 'DateCreated', type: 'date' }
]
}),
```
The JSON returned looks like this:
```
[{"Title":"Some title","DateCreated":new Date(1259175818323)}]
```
There isn't any reason to convert to ISO 8601 format and back if you don't have to. | Take a look at the blog post *[jQuery, Ajax, ASP.NET and dates](http://schotime.net/blog/index.php/2008/06/19/jquery-ajax-aspnet-and-dates/)*.
It details how to work with ASP.NET MVC and jQuery to pass dates via JSON between the server and client side. |
1,263,732 | >
> **Possible Duplicate:**
>
> [Format a Microsoft JSON date?](https://stackoverflow.com/questions/206384)
>
>
>
The ASP.NET function `Json()` formats and returns a date as
```
{"d":"\/Date(1240718400000)\/"}
```
which has to be dealt with on the client side which is problematic. What are your suggestions for approaches to sending date values back and forth? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1263732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94508/"
]
| It may be ugly, but it works:
```
var epoch = (new RegExp('/Date\\((-?[0-9]+)\\)/')).exec(d);
$("#field").text((new Date(parseInt(epoch[1]))).toDateString());
```
Probably, it is not necessary to match the whole string, and just (-?[0-9]+) is enough... | Take a look at the blog post *[jQuery, Ajax, ASP.NET and dates](http://schotime.net/blog/index.php/2008/06/19/jquery-ajax-aspnet-and-dates/)*.
It details how to work with ASP.NET MVC and jQuery to pass dates via JSON between the server and client side. |
1,263,732 | >
> **Possible Duplicate:**
>
> [Format a Microsoft JSON date?](https://stackoverflow.com/questions/206384)
>
>
>
The ASP.NET function `Json()` formats and returns a date as
```
{"d":"\/Date(1240718400000)\/"}
```
which has to be dealt with on the client side which is problematic. What are your suggestions for approaches to sending date values back and forth? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1263732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94508/"
]
| Not everyone agrees with me that it's a good idea, but I find myself most often returning formatted strings instead of proper dates. See *[How I handle JSON dates returned by ASP.NET AJAX](http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/)*. | Take a look at the blog post *[jQuery, Ajax, ASP.NET and dates](http://schotime.net/blog/index.php/2008/06/19/jquery-ajax-aspnet-and-dates/)*.
It details how to work with ASP.NET MVC and jQuery to pass dates via JSON between the server and client side. |
1,263,732 | >
> **Possible Duplicate:**
>
> [Format a Microsoft JSON date?](https://stackoverflow.com/questions/206384)
>
>
>
The ASP.NET function `Json()` formats and returns a date as
```
{"d":"\/Date(1240718400000)\/"}
```
which has to be dealt with on the client side which is problematic. What are your suggestions for approaches to sending date values back and forth? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1263732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94508/"
]
| It may be ugly, but it works:
```
var epoch = (new RegExp('/Date\\((-?[0-9]+)\\)/')).exec(d);
$("#field").text((new Date(parseInt(epoch[1]))).toDateString());
```
Probably, it is not necessary to match the whole string, and just (-?[0-9]+) is enough... | After playing with the Json.NET library, I'm wondering why you would choose to use the IsoDateTimeConverter over the JavascriptDateTimeConverter.
I found this to be easier to use with the [Ext JS](http://en.wikipedia.org/wiki/Ext_JS) interfaces that I was using when serializing dates from an MVC Controller.
```
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.Formatting = Formatting.Indented;
jsonNetResult.SerializerSettings.Converters.Add(new JavaScriptDateTimeConverter());
jsonNetResult.Data = myObject;
```
I'm getting this data back into an Ext.data.JsonStore which is able to get the returned value as a date without me having to specify a date format to parse with.
```
store:new Ext.data.JsonStore({
url: pathContext + '/Subject.mvc/Notices',
baseParams: { subjectId: this.subjectId },
fields: [
{name: 'Title'},
{name: 'DateCreated', type: 'date' }
]
}),
```
The JSON returned looks like this:
```
[{"Title":"Some title","DateCreated":new Date(1259175818323)}]
```
There isn't any reason to convert to ISO 8601 format and back if you don't have to. |
1,263,732 | >
> **Possible Duplicate:**
>
> [Format a Microsoft JSON date?](https://stackoverflow.com/questions/206384)
>
>
>
The ASP.NET function `Json()` formats and returns a date as
```
{"d":"\/Date(1240718400000)\/"}
```
which has to be dealt with on the client side which is problematic. What are your suggestions for approaches to sending date values back and forth? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1263732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94508/"
]
| It may be ugly, but it works:
```
var epoch = (new RegExp('/Date\\((-?[0-9]+)\\)/')).exec(d);
$("#field").text((new Date(parseInt(epoch[1]))).toDateString());
```
Probably, it is not necessary to match the whole string, and just (-?[0-9]+) is enough... | Auto convert dates on the client side (if you use jQuery)
--
You didn't specify it, but since you're using [ASP.NET MVC](http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework) you could be using jQuery. If you do, converting to actual dates just became simpler if you use code provided on [this blog post](http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html). The code extends jQuery's `$.parseJSON()` functionality, so it automatically converts ISO and ASP.NET date strings to actual JavaScript dates.
I use it with ASP.NET MVC, and it works like a charm. The best part is that it's also backwards compatible. Existing code that uses `$.parseJSON()` will work just like before (and actually work the same), but if you provide the second parameter and set its value to `true`, all dates will get automatically converted for you.
The extension uses native browser JSON support where applicable and also works in others that don't. Modern browsers support this functionality anyway. |
1,263,732 | >
> **Possible Duplicate:**
>
> [Format a Microsoft JSON date?](https://stackoverflow.com/questions/206384)
>
>
>
The ASP.NET function `Json()` formats and returns a date as
```
{"d":"\/Date(1240718400000)\/"}
```
which has to be dealt with on the client side which is problematic. What are your suggestions for approaches to sending date values back and forth? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1263732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94508/"
]
| This was found in [another post](https://stackoverflow.com/questions/206384/how-to-format-json-date) on Stack Overflow:
```
var date = new Date(parseInt(jsonDate.substr(6)));
```
The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end. The resulting number is passed into the Date constructor. | If you are not tied to the MS JSON serializer you could use [Json.NET](http://www.codeplex.com/Json). It comes with an IsoDateTimeConverter to handle issues with serializing dates. This will serialize dates into an [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) formatted string.
For instance, in our project serializing `myObject` is handled via the following code.
```
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.Formatting = Formatting.Indented;
jsonNetResult.SerializerSettings.Converters.Add(new IsoDateTimeConverter());
jsonNetResult.Data = myObject;
```
If you decide to take the Json.NET plunge you'll also want to grab [JsonNetResult](http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx) as it returns an ActionResult that can be used in ASP.NET MVC application. It's quite easy to use.
For more info see: [Good (Date)Times with Json.NET](http://james.newtonking.com/archive/2009/02/20/good-date-times-with-json-net.aspx) |
1,263,732 | >
> **Possible Duplicate:**
>
> [Format a Microsoft JSON date?](https://stackoverflow.com/questions/206384)
>
>
>
The ASP.NET function `Json()` formats and returns a date as
```
{"d":"\/Date(1240718400000)\/"}
```
which has to be dealt with on the client side which is problematic. What are your suggestions for approaches to sending date values back and forth? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1263732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94508/"
]
| Not everyone agrees with me that it's a good idea, but I find myself most often returning formatted strings instead of proper dates. See *[How I handle JSON dates returned by ASP.NET AJAX](http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/)*. | Auto convert dates on the client side (if you use jQuery)
--
You didn't specify it, but since you're using [ASP.NET MVC](http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework) you could be using jQuery. If you do, converting to actual dates just became simpler if you use code provided on [this blog post](http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html). The code extends jQuery's `$.parseJSON()` functionality, so it automatically converts ISO and ASP.NET date strings to actual JavaScript dates.
I use it with ASP.NET MVC, and it works like a charm. The best part is that it's also backwards compatible. Existing code that uses `$.parseJSON()` will work just like before (and actually work the same), but if you provide the second parameter and set its value to `true`, all dates will get automatically converted for you.
The extension uses native browser JSON support where applicable and also works in others that don't. Modern browsers support this functionality anyway. |
3 | This is a question that has been posted at many different forums, I thought maybe someone here would have a better or more conceptual answer than I have seen before:
Why do physicists care about representations of Lie groups? For myself, when I think about a representation that means there is some sort of group acting on a vector space, what is the vector space that this Lie group is acting on?
Or is it that certain things have to be invariant under a group action?
maybe this is a dumb question, but i thought it might be a good start...
To clarify, I am specifically thinking of the symmetry groups that people think about in relation to the standard model. I do not care why it might be a certain group, but more how we see the group acting, what is it acting on? etc. | 2010/11/02 | [
"https://physics.stackexchange.com/questions/3",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/40/"
]
| Let me give a try.
When we construct a theory, we suspect that the objects it deals with can be rather complicated. It is natural that we want to find the simplest «building blocks» which the complicated objects are made of. If our theory were absolutely arbitrary, we won't be able to classify these simple building blocks at all. Fortunately, when constructing theories we note that the lagrangian we specify and the vacuum state have certain symmetries. Once we noted it, then it is pure math to show that the simple objects in our theory should be classified according to representations of the symmetry group of the lagrangian and the vacuum state.
Note that there are some symmetries which are obvious to us, which we perceive (like invariance under the Poincare group), and there are some symmetries which we **invent** (like non-abelian gauge symmetries). In the latter case we know that, by construction, all the macroscopic states (including the vacuum state) must be invariant under this new internal symmetry group. This gives us a short-cut to the assertion that the simple object in our theory must be classified according to the representations of the new group.
And what concerns the specific question:
>
> so the fundamental particle is acting on the quantum states?
>
>
>
When we say that a particle or a field is in representation R of group G, we do not mean that the particles are associated with matrices of representation R acting on something else. We rather mean that the particle can be written in terms of **eigenstates** of matrices representing operators in R. So, it is the symmetry group transformations that act on the particles. | The vector space that is being acted on typically is a Hilbert space of states in quantum mechanics; very roughly, there's a basis of this vector space which is in one-to-one correspondence with the set of possibilities for a physical system. The simplest example to try to get your head around is that of the spin 1/2 particle (2 dim representation of SU(2)), which is explained in any introductory quantum mechanics book. |
3 | This is a question that has been posted at many different forums, I thought maybe someone here would have a better or more conceptual answer than I have seen before:
Why do physicists care about representations of Lie groups? For myself, when I think about a representation that means there is some sort of group acting on a vector space, what is the vector space that this Lie group is acting on?
Or is it that certain things have to be invariant under a group action?
maybe this is a dumb question, but i thought it might be a good start...
To clarify, I am specifically thinking of the symmetry groups that people think about in relation to the standard model. I do not care why it might be a certain group, but more how we see the group acting, what is it acting on? etc. | 2010/11/02 | [
"https://physics.stackexchange.com/questions/3",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/40/"
]
| The vector space that is being acted on typically is a Hilbert space of states in quantum mechanics; very roughly, there's a basis of this vector space which is in one-to-one correspondence with the set of possibilities for a physical system. The simplest example to try to get your head around is that of the spin 1/2 particle (2 dim representation of SU(2)), which is explained in any introductory quantum mechanics book. | See the [Wigner theorem](http://en.wikipedia.org/wiki/Wigner_theorem), it explain rigorously the relationship between a group of symmetries and states of a physical particle. |
3 | This is a question that has been posted at many different forums, I thought maybe someone here would have a better or more conceptual answer than I have seen before:
Why do physicists care about representations of Lie groups? For myself, when I think about a representation that means there is some sort of group acting on a vector space, what is the vector space that this Lie group is acting on?
Or is it that certain things have to be invariant under a group action?
maybe this is a dumb question, but i thought it might be a good start...
To clarify, I am specifically thinking of the symmetry groups that people think about in relation to the standard model. I do not care why it might be a certain group, but more how we see the group acting, what is it acting on? etc. | 2010/11/02 | [
"https://physics.stackexchange.com/questions/3",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/40/"
]
| Let me give a try.
When we construct a theory, we suspect that the objects it deals with can be rather complicated. It is natural that we want to find the simplest «building blocks» which the complicated objects are made of. If our theory were absolutely arbitrary, we won't be able to classify these simple building blocks at all. Fortunately, when constructing theories we note that the lagrangian we specify and the vacuum state have certain symmetries. Once we noted it, then it is pure math to show that the simple objects in our theory should be classified according to representations of the symmetry group of the lagrangian and the vacuum state.
Note that there are some symmetries which are obvious to us, which we perceive (like invariance under the Poincare group), and there are some symmetries which we **invent** (like non-abelian gauge symmetries). In the latter case we know that, by construction, all the macroscopic states (including the vacuum state) must be invariant under this new internal symmetry group. This gives us a short-cut to the assertion that the simple object in our theory must be classified according to the representations of the new group.
And what concerns the specific question:
>
> so the fundamental particle is acting on the quantum states?
>
>
>
When we say that a particle or a field is in representation R of group G, we do not mean that the particles are associated with matrices of representation R acting on something else. We rather mean that the particle can be written in terms of **eigenstates** of matrices representing operators in R. So, it is the symmetry group transformations that act on the particles. | See the [Wigner theorem](http://en.wikipedia.org/wiki/Wigner_theorem), it explain rigorously the relationship between a group of symmetries and states of a physical particle. |
2,708,799 | This .aspx page has a very nice set of collapsible sections with little "+ -" controls.
<http://www.microsoft.com/sqlserver/2008/en/us/editions-compare.aspx>
Can anyone tell me how this might be done in Visual Studio?
I have tried using firebug to deconstruct the page but can't find the script that is doing the showCollapsibleItem() call.
Thank you! | 2010/04/25 | [
"https://Stackoverflow.com/questions/2708799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320790/"
]
| Try the [AJAX Control Toolkit's CollapsiblePanel](http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/CollapsiblePanel/CollapsiblePanel.aspx).
You can also do this trivially with jQuery:
```
$('a.toggler').click(function() { $(this.rel).toggle(); return false; });
```
---
```
<a href="#" rel="#section1">Section 1</a>
<p id="section1">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
``` | A cheap way would be to use jquery's .hide() and .show() events. Here is a tutorial called [Simple Jquery Show/Hide Div](http://papermashup.com/simple-jquery-showhide-div/) that shows how to accomplish this. [Here is a demostration](http://papermashup.com/demos/jquery-sliding-div/) of what the tutorial will do.
Hope this helps some. |
2,708,799 | This .aspx page has a very nice set of collapsible sections with little "+ -" controls.
<http://www.microsoft.com/sqlserver/2008/en/us/editions-compare.aspx>
Can anyone tell me how this might be done in Visual Studio?
I have tried using firebug to deconstruct the page but can't find the script that is doing the showCollapsibleItem() call.
Thank you! | 2010/04/25 | [
"https://Stackoverflow.com/questions/2708799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320790/"
]
| Try the [AJAX Control Toolkit's CollapsiblePanel](http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/CollapsiblePanel/CollapsiblePanel.aspx).
You can also do this trivially with jQuery:
```
$('a.toggler').click(function() { $(this.rel).toggle(); return false; });
```
---
```
<a href="#" rel="#section1">Section 1</a>
<p id="section1">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
``` | If you didn't want to use jQuery, you could use the showCollapsibleItem function in the example page you have
`function showCollapsibleItem(id)
{if(document.getElementById(id+"ExpandIcon").className=='cueCollapsibleContentExpandIcon')
{document.getElementById(id).style.display='block';document.getElementById(id+"ExpandIcon").className='cueCollapsibleContentCollapseIcon';}
else
{document.getElementById(id).style.display='none';document.getElementById(id+"ExpandIcon").className='cueCollapsibleContentExpandIcon';}}`
<http://www.microsoft.com/sqlserver/shared/core/2/js/js.ashx?pt=Column3Zone3&c=cueCollapsibleContent> |
2,708,799 | This .aspx page has a very nice set of collapsible sections with little "+ -" controls.
<http://www.microsoft.com/sqlserver/2008/en/us/editions-compare.aspx>
Can anyone tell me how this might be done in Visual Studio?
I have tried using firebug to deconstruct the page but can't find the script that is doing the showCollapsibleItem() call.
Thank you! | 2010/04/25 | [
"https://Stackoverflow.com/questions/2708799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320790/"
]
| A cheap way would be to use jquery's .hide() and .show() events. Here is a tutorial called [Simple Jquery Show/Hide Div](http://papermashup.com/simple-jquery-showhide-div/) that shows how to accomplish this. [Here is a demostration](http://papermashup.com/demos/jquery-sliding-div/) of what the tutorial will do.
Hope this helps some. | If you didn't want to use jQuery, you could use the showCollapsibleItem function in the example page you have
`function showCollapsibleItem(id)
{if(document.getElementById(id+"ExpandIcon").className=='cueCollapsibleContentExpandIcon')
{document.getElementById(id).style.display='block';document.getElementById(id+"ExpandIcon").className='cueCollapsibleContentCollapseIcon';}
else
{document.getElementById(id).style.display='none';document.getElementById(id+"ExpandIcon").className='cueCollapsibleContentExpandIcon';}}`
<http://www.microsoft.com/sqlserver/shared/core/2/js/js.ashx?pt=Column3Zone3&c=cueCollapsibleContent> |
966,457 | This is **code-related** as in what the compiler will allow you to do in one language, but not allow you to do in another language (e.g. optional parameters in VB don't exist in C#).
Please provide a code example with your answer, if possible. Thank you! | 2009/06/08 | [
"https://Stackoverflow.com/questions/966457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114916/"
]
| In C# you can declare a property in an interface as having a 'get', and then implement it in a class with a get and set.
```
public interface IFoo {
string Bar {get;}
}
public class Foo : IFoo {
public string Bar {get; set;}
}
```
In VB, the equivalent to declating a property with a get would be to declare it ReadOnly. You can't then make the implementation writable.
```
Public Interface IFoo
ReadOnly Property Bar() As String
End Interface
Public Class Foo
Implements IFoo
Public Property Bar() As String Implements IFoo.Bar 'Compile error here'
End Class
```
I find this to be a severe limitation of VB. Quite often I want to define an Interface that allows other code only to be able to read a property, but I need a public setter in the implemented class, for use by the persistor. | Global variables don't exist in c# i think |
966,457 | This is **code-related** as in what the compiler will allow you to do in one language, but not allow you to do in another language (e.g. optional parameters in VB don't exist in C#).
Please provide a code example with your answer, if possible. Thank you! | 2009/06/08 | [
"https://Stackoverflow.com/questions/966457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114916/"
]
| One of my favorites (and bummers)
In VB.Net you can struture a switch/case statement as such:
```
Select Case True
Case User.Name = "Joe" And User.Role = "BigWig" And SecretTime = "HackerTime"
GrantCredentials()
End Select
```
which allows you to evaluate some complex evaluations through a switch instead of a variety of if/else blocks. You cannot do this in C#. | Global variables don't exist in c# i think |
966,457 | This is **code-related** as in what the compiler will allow you to do in one language, but not allow you to do in another language (e.g. optional parameters in VB don't exist in C#).
Please provide a code example with your answer, if possible. Thank you! | 2009/06/08 | [
"https://Stackoverflow.com/questions/966457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114916/"
]
| I'm surprised that C#'s [unsafe code](http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=351) has not been mentioned yet. This is not allowed in VB.NET. | Off the top of my head (pre 4.0):
VB language "features" not supported in C#:
* Optional Parameters
* Late Binding
* Case insensativity
I'm sure there's more. Your question might get better answers if you ask for specific examples of where each language excels. VB is a currently better than C# when interacting with COM. This is because COM is much less of a headache when optional parameters are available, and when you don't have to bind to the (often unknown type) at compile time.
C# on the other hand, is preferable by many when writing complex logic because of its type safety (in that you can't bypass static typing) and its conciseness.
In the end, the languages are mostly equivalent, since they only differ on the fringes. Functionally, they are equally capable.
**EDIT**
To be clear, I'm not implying that VB doesn't allow static typing... simply that *C# doesn't* [yet] *allow you to bypass static typing*. This makes C# a more attractive candidate for certain types of architectures. In the 4.0 C# language spec, you can bypass static typing, but you do it by defining a block of dynamic code, not by declaring the entire file "not strict," which makes it more deliberate and targeted. |
966,457 | This is **code-related** as in what the compiler will allow you to do in one language, but not allow you to do in another language (e.g. optional parameters in VB don't exist in C#).
Please provide a code example with your answer, if possible. Thank you! | 2009/06/08 | [
"https://Stackoverflow.com/questions/966457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114916/"
]
| VB.NET has support for CIL Exception Filters, C# doesn't:
```
Try
...
Catch ex As SomeException When ex.SomeProperty = 1
...
End Try
``` | In VB you can implement an interface with a method of any name - i.e. a method "Class.A" can implement interface method "Interface.B".
In C#, you would have to introduce an extra level of indirection to achieve this - an explicit interface implementation that *calls* "Class.A".
This is mainly noticeable when you want "Class.A" to be `protected` and/or `virtual` (explicit interface implementations are neither); if it was just "private" you'd probably just leave it as the explicit interface implementation.
C#:
```
interface IFoo {
void B();
}
class Foo : IFoo {
void IFoo.B() {A();} // <==== extra method here
protected virtual void A() {}
}
```
VB:
```
Interface IFoo
Sub B()
End Interface
Class Foo
Implements IFoo
Protected Overridable Sub A() Implements IFoo.B
End Sub
End Class
```
In the IL, VB does this mapping directly (which is fine; it is not necessary for an implementing method to share a name). |
966,457 | This is **code-related** as in what the compiler will allow you to do in one language, but not allow you to do in another language (e.g. optional parameters in VB don't exist in C#).
Please provide a code example with your answer, if possible. Thank you! | 2009/06/08 | [
"https://Stackoverflow.com/questions/966457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114916/"
]
| The volatile keyword is only available in C# <http://www.devcity.net/Articles/160/5/article.aspx> | Global variables don't exist in c# i think |
966,457 | This is **code-related** as in what the compiler will allow you to do in one language, but not allow you to do in another language (e.g. optional parameters in VB don't exist in C#).
Please provide a code example with your answer, if possible. Thank you! | 2009/06/08 | [
"https://Stackoverflow.com/questions/966457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114916/"
]
| In VB you can implement an interface with a method of any name - i.e. a method "Class.A" can implement interface method "Interface.B".
In C#, you would have to introduce an extra level of indirection to achieve this - an explicit interface implementation that *calls* "Class.A".
This is mainly noticeable when you want "Class.A" to be `protected` and/or `virtual` (explicit interface implementations are neither); if it was just "private" you'd probably just leave it as the explicit interface implementation.
C#:
```
interface IFoo {
void B();
}
class Foo : IFoo {
void IFoo.B() {A();} // <==== extra method here
protected virtual void A() {}
}
```
VB:
```
Interface IFoo
Sub B()
End Interface
Class Foo
Implements IFoo
Protected Overridable Sub A() Implements IFoo.B
End Sub
End Class
```
In the IL, VB does this mapping directly (which is fine; it is not necessary for an implementing method to share a name). | As Chris Dunaway mentioned, VB.NET has Modules which allow you to define functions and data.
VB.NET has the VB6 syntax for linking to methods in DLLs. For example:
```
Declare SetSuspendState Lib "powrprof" As Function (byval hibernate as Int32, byval forceCritical as Int32, byval disableWakeEvent) as Int32
```
(Although that actual declaration might have to be Marshalled)
--- |
966,457 | This is **code-related** as in what the compiler will allow you to do in one language, but not allow you to do in another language (e.g. optional parameters in VB don't exist in C#).
Please provide a code example with your answer, if possible. Thank you! | 2009/06/08 | [
"https://Stackoverflow.com/questions/966457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114916/"
]
| [Handles](http://msdn.microsoft.com/en-us/library/6k46st1y.aspx) and WithEvents keywords for automatic wiring of EventHandlers.
```
Private Sub btnOKClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOK.Click
End Sub
``` | True in VB.Net when converted to an integer will convert to -1 while in C# it will convert to 1.
Furthermore the NOT keyword in VB.Net is indeed a bitwise NOT (as in C# '~'), and not a logical NOT (C# '!').
While for the AND and OR operators, VB.Net has already logical operators AndAlso And OrElse which are true logical operators and short circuit, still there is no logical NOT.
This is especially important when dealing with the Win32 API, in which doing NOT on the result assuming that if the result is True the NOT will negate it, is wrong, since in C true == 1 and therefore a bitwise NOT on 1 is also a true value (and this is in fact probably the reason why in VB true == -1, as this is the only value on which a bitwise NOT will result in 0) |
966,457 | This is **code-related** as in what the compiler will allow you to do in one language, but not allow you to do in another language (e.g. optional parameters in VB don't exist in C#).
Please provide a code example with your answer, if possible. Thank you! | 2009/06/08 | [
"https://Stackoverflow.com/questions/966457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114916/"
]
| The volatile keyword is only available in C# <http://www.devcity.net/Articles/160/5/article.aspx> | In C# you have to assign your variable before you can use it. I think you can turn this off, but it's the default behavior.
So something like this:
```
int something;
if (something == 10)
{ ... }
```
Isn't allowed, but the VB equivalent would be. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.