qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
32,178,130 | I'm trying to get users count belongs to specific company.
Here is my model;
```
var Company = Bookshelf.Model.extend({
tableName: 'companies',
users: function () {
return this.hasMany(User.Model, "company_id");
},
users_count : function(){
return new User.Model().query(function(qb){
qb.where("company_id",9);
qb.count();
}).fetch();
},
organization: function () {
return this.belongsTo(Organization.Model, "organization_id");
}
});
```
* method "users" works very well, no problem.
* method "users\_count" query works well, but cant get value to "company" model.
in routes, i'm using bookshelf models like this;
```
new Company.Model({id:req.params.id})
.fetch({withRelated:['users']})
.then(function(model){
res.send(model.toJSON())
})
.catch(function(error){
res.send(error);
});
```
How should i use users\_count method, i'm kinda confused (probably because of promises) | 2015/08/24 | [
"https://Stackoverflow.com/questions/32178130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1011016/"
] | **Collection#count()**
If you upgrade to 0.8.2 you can use the new [`Collection#count` method](http://bookshelfjs.org/#Collection-count).
```
Company.forge({id: req.params.id}).users().count().then(userCount =>
res.send('company has ' + userCount + ' users!');
);
```
**Problem with your example**
The problem with your `users_count` method is that it tries to make Bookshelf turn the result of your query into Models.
```
users_count : function(){
return new User.Model().query(function(qb){
qb.where("company_id",9);
qb.count();
}).fetch(); // Fetch wanted an array of `user` records.
},
```
This should work in this instance.
```
users_count : function(){
return new User.Model().query()
.where("company_id",9)
.count()
},
```
See relevant discussion [here](https://github.com/tgriesser/bookshelf/issues/126).
**EDIT: How to get this in your attributes.**
Maybe try something like this:
```
knex = bookshelf.knex;
var Company = bookshelf.Model.extend({
tableName: 'companies',
initialize: function() {
this.on('fetching', function(model, attributes, options) {
var userCountWrapped = knex.raw(this.getUsersCountQuery()).wrap('(', ') as user_count');
options.query.select('*', userCountWrapped);
}
}
users: function () {
return this.hasMany(User.Model, "company_id");
},
getUsersCountQuery: function() {
return User.Model.query()
.where("company_id",9)
.count();
}
organization: function () {
return this.belongsTo(Organization.Model, "organization_id");
}
});
``` | ```
User.collection().query(function (qb) {
qb.join('courses', 'users.id', 'courses.user_id');
qb.groupBy('users.id');
qb.select("users.*");
qb.count('* as course_count');
qb.orderBy("course_count", "desc");
})
``` |
32,178,130 | I'm trying to get users count belongs to specific company.
Here is my model;
```
var Company = Bookshelf.Model.extend({
tableName: 'companies',
users: function () {
return this.hasMany(User.Model, "company_id");
},
users_count : function(){
return new User.Model().query(function(qb){
qb.where("company_id",9);
qb.count();
}).fetch();
},
organization: function () {
return this.belongsTo(Organization.Model, "organization_id");
}
});
```
* method "users" works very well, no problem.
* method "users\_count" query works well, but cant get value to "company" model.
in routes, i'm using bookshelf models like this;
```
new Company.Model({id:req.params.id})
.fetch({withRelated:['users']})
.then(function(model){
res.send(model.toJSON())
})
.catch(function(error){
res.send(error);
});
```
How should i use users\_count method, i'm kinda confused (probably because of promises) | 2015/08/24 | [
"https://Stackoverflow.com/questions/32178130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1011016/"
] | **Collection#count()**
If you upgrade to 0.8.2 you can use the new [`Collection#count` method](http://bookshelfjs.org/#Collection-count).
```
Company.forge({id: req.params.id}).users().count().then(userCount =>
res.send('company has ' + userCount + ' users!');
);
```
**Problem with your example**
The problem with your `users_count` method is that it tries to make Bookshelf turn the result of your query into Models.
```
users_count : function(){
return new User.Model().query(function(qb){
qb.where("company_id",9);
qb.count();
}).fetch(); // Fetch wanted an array of `user` records.
},
```
This should work in this instance.
```
users_count : function(){
return new User.Model().query()
.where("company_id",9)
.count()
},
```
See relevant discussion [here](https://github.com/tgriesser/bookshelf/issues/126).
**EDIT: How to get this in your attributes.**
Maybe try something like this:
```
knex = bookshelf.knex;
var Company = bookshelf.Model.extend({
tableName: 'companies',
initialize: function() {
this.on('fetching', function(model, attributes, options) {
var userCountWrapped = knex.raw(this.getUsersCountQuery()).wrap('(', ') as user_count');
options.query.select('*', userCountWrapped);
}
}
users: function () {
return this.hasMany(User.Model, "company_id");
},
getUsersCountQuery: function() {
return User.Model.query()
.where("company_id",9)
.count();
}
organization: function () {
return this.belongsTo(Organization.Model, "organization_id");
}
});
``` | Check out the [bookshelf-eloquent](https://www.npmjs.com/package/bookshelf-eloquent) extension. The withCount() function is probably what you are looking for. Your code would look something like this:
```
let company = await Company.where('id', req.params.id)
.withCount('users').first();
``` |
32,178,130 | I'm trying to get users count belongs to specific company.
Here is my model;
```
var Company = Bookshelf.Model.extend({
tableName: 'companies',
users: function () {
return this.hasMany(User.Model, "company_id");
},
users_count : function(){
return new User.Model().query(function(qb){
qb.where("company_id",9);
qb.count();
}).fetch();
},
organization: function () {
return this.belongsTo(Organization.Model, "organization_id");
}
});
```
* method "users" works very well, no problem.
* method "users\_count" query works well, but cant get value to "company" model.
in routes, i'm using bookshelf models like this;
```
new Company.Model({id:req.params.id})
.fetch({withRelated:['users']})
.then(function(model){
res.send(model.toJSON())
})
.catch(function(error){
res.send(error);
});
```
How should i use users\_count method, i'm kinda confused (probably because of promises) | 2015/08/24 | [
"https://Stackoverflow.com/questions/32178130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1011016/"
] | Check out the [bookshelf-eloquent](https://www.npmjs.com/package/bookshelf-eloquent) extension. The withCount() function is probably what you are looking for. Your code would look something like this:
```
let company = await Company.where('id', req.params.id)
.withCount('users').first();
``` | ```
User.collection().query(function (qb) {
qb.join('courses', 'users.id', 'courses.user_id');
qb.groupBy('users.id');
qb.select("users.*");
qb.count('* as course_count');
qb.orderBy("course_count", "desc");
})
``` |
10,077,837 | I'm having trouble putting this problem into searchable terms. I'm working on an Android application, and specifically the splash screen for my app. The app needs to fetch data from an external web service (a blocking function call), while it does this the user gets a nice title, image and progress bar. When the data arrives the user is redirected to the main menu. Its a simple screen, everything being defined in the xml layout file, my problem is that I just get a black screen for a few seconds and then the main menu. If I press back I get the splash screen with the progress bar spinning away happily.
Here is what I have so far:
```
public class SplashActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
}
@Override
public void onStart(){
super.onStart();
DatabaseManager db = new DatabaseManager(this.getBaseContext());
db.fetchExternCatalog(); //doesnt return until data arrives
Intent intent = new Intent().setClass(this, MainMenuActivity.class);
startActivity(intent);
}
}
```
It seems the screen isnt actually drawn until the activity is running (after onCreate(), onStart(), etc). I thought onStart() would be the perfect place to put this, but apparently not.
So how do I draw everything on the screen and make my blocking function call after so the user actually sees the splash screen while the data is downloaded? | 2012/04/09 | [
"https://Stackoverflow.com/questions/10077837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982955/"
] | Have a look at this project in GitHub.
<https://github.com/virajs/MongoDB-Mapping-Attributes.git>
This project mainly provide you with two mapping attributes. OneToMany and ManyToOne.
Checkout the code and play around with the test project. | You could declare your Comments property as List<MongoDBRef> and handle the relationship yourself but there is no automatic support for that. |
21,632,979 | I have an abstract class:
```
public abstract class Room {
}
```
and inherited classes that are not known at compile time like:
```
public class MagicRoom extends Room {
public MagicRoom(){
System.out.println("Creating a MagicRoom.");
}
public String magic = "";
}
```
or:
```
public class Dungeon extends Room {
public Dungeon(){
System.out.println("Creating a Dungeon");
}
public String keeper = "";
}
```
I have a class that I will be creating instances of these classes from:
```
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class MazeGame {
public static Room makeRoom(Class roomClass)
throws IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException,
SecurityException, NoSuchMethodException{
Constructor c = roomClass.getConstructor();
return c.newInstance();
}
}
```
makeRoom is my attempt to create a class inherited from Room which type I don't know at compile time, but I'm not sure what to put as its return type instead of Room. Because makeRoom returns a Room I get an exception if I try to use a field that belongs to an inherited class:
```
import java.lang.reflect.InvocationTargetException;
public class FactoryTest {
public static void main(String[] args)
throws IllegalArgumentException, SecurityException,
InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException{
MazeGame game = new MazeGame();
Room magicRoom = MazeGame.makeRoom(MagicRoom.class);
/*
* Exception in thread "main" java.lang.Error: Unresolved compilation problem:
* magic cannot be resolved or is not a field
*/
magicRoom.magic = "a";
}
}
``` | 2014/02/07 | [
"https://Stackoverflow.com/questions/21632979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284680/"
] | Make that method generic:
```
public static <T extends Room> T makeRoom(Class<T> roomClass)
throws IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException,
SecurityException, NoSuchMethodException{
// This is enough, if you have 0-arg constructor in all your subclasses
return roomClass.newInstance();
}
```
and then invoke it like:
```
MagicRoom magicRoom = MazeGame.makeRoom(MagicRoom.class);
``` | You'll have to cast the Room object to MagicRoom.
```
MagicRoom magicRoom = (MagicRoom) MazeGame.makeRoom(MagicRoom.class);
```
Also, I know it's only an example but you should make those attributes private and use accessor/mutator methods.
e.g.
```
public class MagicRoom extends Room {
public MagicRoom(){
System.out.println("Creating a MagicRoom.");
}
private String magic = "";
public String getMagic() {
return this.magic;
}
public void setMagic(String magic) {
this.magic = magic;
}
}
``` |
5,534,196 | I have Windows 7 installed on my PC. I am learning C and assembly language together. I use codeblock IDE for writing C codes and emu8086 for assembly codes. I am able to DEBUG the assembly codes from DOS prompt, but not the C codes. Why so?
I select console application option while writing C codes. they run well on their own from DOS prompt, but not through DEBUG mode.
I intend to observe the machine code and the symbolic assembly code created by the C compiler.
I was assuming that Using DEBUG I should be able to trace the execution of all executable files, after all that is the purpose of DEBUG. Isn't it? | 2011/04/04 | [
"https://Stackoverflow.com/questions/5534196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597858/"
] | The thing you're trying to do is doable, but you need to create a new implementation of IAsyncResult (something like "CompositeResult" that watches the first IAsyncResult, then kicks off the 2nd call).
However, this task is actually far easier using the Reactive Extensions - in that case you'd use Observable.FromAsyncPattern to convert your Begin/End methods into a Func that returns IObservable (which *also* represents an async result), then chain them using SelectMany:
```
IObservable<Stream> GetRequestStream(string Url);
IObservable<bool> MyOperation(Stream stream);
GetRequestStream().SelectMany(x => MyOperation(x)).Subscribe(x => {
// When everything is finished, this code will run
});
``` | I don't really understand what are you trying to achieve, but I think you should be rethinking the code.
An IAsyncResult instance is the object that allows to to handle asynchronous method calls, and they are created when you perform an async call through *BeginXXX*.
In your example, you basically want to return an instance of an IAsyncResult that **it doesn't exist yet**.
I don't really know which is the problem you are trying to solve, but maybe one of these approaches work better for you:
1. **Encapsulate** this code in a class, and make the users of your code aware that the operation is completed by **subscribing to an event**.
2. **Encapsulate** this code in a class, and make the users provide a callback delegate that will be called when the work is finished. You may pass the results as a parameter to this callback
Hope it helps! |
5,534,196 | I have Windows 7 installed on my PC. I am learning C and assembly language together. I use codeblock IDE for writing C codes and emu8086 for assembly codes. I am able to DEBUG the assembly codes from DOS prompt, but not the C codes. Why so?
I select console application option while writing C codes. they run well on their own from DOS prompt, but not through DEBUG mode.
I intend to observe the machine code and the symbolic assembly code created by the C compiler.
I was assuming that Using DEBUG I should be able to trace the execution of all executable files, after all that is the purpose of DEBUG. Isn't it? | 2011/04/04 | [
"https://Stackoverflow.com/questions/5534196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597858/"
] | I think the easiest way to solve this is to use `Task` wrappers. In particular, you can finish a [`TaskCompletionSource`](http://msdn.microsoft.com/en-us/library/dd449174.aspx) when `BeginGetResponse` completes. Then just return the [`Task` for that `TaskCompletionSource`](http://msdn.microsoft.com/en-us/library/dd449187.aspx). Note that `Task` implements `IAsyncResult`, so your client code won't have to change.
Personally, I would go a step further:
1. Wrap `BeginGetRequestStream` in a `Task` (using [`FromAsync`](http://msdn.microsoft.com/en-us/library/dd321543.aspx)).
2. Create a continuation for that `Task` that processes the request and wraps `BeginGetResponse` in a `Task` (again, using `FromAsync`).
3. Create a continuation for that second `Task` that completes the `TaskCompletionSource`.
IMHO, exceptions and result values are more naturally handled by `Task`s than `IAsyncResult`. | I don't really understand what are you trying to achieve, but I think you should be rethinking the code.
An IAsyncResult instance is the object that allows to to handle asynchronous method calls, and they are created when you perform an async call through *BeginXXX*.
In your example, you basically want to return an instance of an IAsyncResult that **it doesn't exist yet**.
I don't really know which is the problem you are trying to solve, but maybe one of these approaches work better for you:
1. **Encapsulate** this code in a class, and make the users of your code aware that the operation is completed by **subscribing to an event**.
2. **Encapsulate** this code in a class, and make the users provide a callback delegate that will be called when the work is finished. You may pass the results as a parameter to this callback
Hope it helps! |
5,534,196 | I have Windows 7 installed on my PC. I am learning C and assembly language together. I use codeblock IDE for writing C codes and emu8086 for assembly codes. I am able to DEBUG the assembly codes from DOS prompt, but not the C codes. Why so?
I select console application option while writing C codes. they run well on their own from DOS prompt, but not through DEBUG mode.
I intend to observe the machine code and the symbolic assembly code created by the C compiler.
I was assuming that Using DEBUG I should be able to trace the execution of all executable files, after all that is the purpose of DEBUG. Isn't it? | 2011/04/04 | [
"https://Stackoverflow.com/questions/5534196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597858/"
] | I don't really understand what are you trying to achieve, but I think you should be rethinking the code.
An IAsyncResult instance is the object that allows to to handle asynchronous method calls, and they are created when you perform an async call through *BeginXXX*.
In your example, you basically want to return an instance of an IAsyncResult that **it doesn't exist yet**.
I don't really know which is the problem you are trying to solve, but maybe one of these approaches work better for you:
1. **Encapsulate** this code in a class, and make the users of your code aware that the operation is completed by **subscribing to an event**.
2. **Encapsulate** this code in a class, and make the users provide a callback delegate that will be called when the work is finished. You may pass the results as a parameter to this callback
Hope it helps! | First, get the `AsyncResultNoResult` and `AsyncResult<TResult>` implementation code from Jeffrey Richter's MSDN magazine article "[Implementing the CLR Asynchronous Programming Model](http://msdn.microsoft.com/en-us/magazine/cc163467.aspx) (March 2007 issue)."
Once you have those base classes, you can relatively easily implement your own async result. In this example, I will use your basic code to start the web request and then get the response as a single async operation composed of multiple inner async operations.
```
// This is the class that implements the async operations that the caller will see
internal class MyClass
{
public MyClass() { /* . . . */ }
public IAsyncResult BeginMyOperation(Uri requestUri, AsyncCallback callback, object state)
{
return new MyOperationAsyncResult(this, requestUri, callback, state);
}
public WebResponse EndMyOperation(IAsyncResult result)
{
MyOperationAsyncResult asyncResult = (MyOperationAsyncResult)result;
return asyncResult.EndInvoke();
}
private sealed class MyOperationAsyncResult : AsyncResult<WebResponse>
{
private readonly MyClass parent;
private readonly HttpWebRequest webRequest;
private bool everCompletedAsync;
public MyOperationAsyncResult(MyClass parent, Uri requestUri, AsyncCallback callback, object state)
: base(callback, state)
{
// Occasionally it is necessary to access the outer class instance from this inner
// async result class. This also ensures that the async result instance is rooted
// to the parent and doesn't get garbage collected unexpectedly.
this.parent = parent;
// Start first async operation here
this.webRequest = WebRequest.Create(requestUri);
this.webRequest.Method = "POST";
this.webRequest.BeginGetRequestStream(this.OnGetRequestStreamComplete, null);
}
private void SetCompletionStatus(IAsyncResult result)
{
// Check to see if we did not complete sync. If any async operation in
// the chain completed asynchronously, it means we had to do a thread switch
// and the callback is being invoked outside the starting thread.
if (!result.CompletedSynchronously)
{
this.everCompletedAsync = true;
}
}
private void OnGetRequestStreamComplete(IAsyncResult result)
{
this.SetCompletionStatus(result);
Stream requestStream = null;
try
{
stream = this.webRequest.EndGetRequestStream(result);
}
catch (WebException e)
{
// Cannot let exception bubble up here as we are on a callback thread;
// in this case, complete the entire async result with an exception so
// that the caller gets it back when they call EndXxx.
this.SetAsCompleted(e, !this.everCompletedAsync);
}
if (requestStream != null)
{
this.WriteToRequestStream();
this.StartGetResponse();
}
}
private void WriteToRequestStream(Stream requestStream) { /* omitted */ }
private void StartGetResponse()
{
try
{
this.webRequest.BeginGetResponse(this.OnGetResponseComplete, null);
}
catch (WebException e)
{
// As above, we cannot let this exception bubble up
this.SetAsCompleted(e, !this.everCompletedAsync);
}
}
private void OnGetResponseComplete(IAsyncResult result)
{
this.SetCompletionStatus(result);
try
{
WebResponse response = this.webRequest.EndGetResponse(result);
// At this point, we can complete the whole operation which
// will invoke the callback passed in at the very beginning
// in the constructor.
this.SetAsCompleted(response, !this.everCompletedAsync);
}
catch (WebException e)
{
// As above, we cannot let this exception bubble up
this.SetAsCompleted(e, !this.everCompletedAsync);
}
}
}
}
```
Some things to note:
* You cannot throw an exception in the context of an async callback. You will crash your application since there will be no one to handle it. Instead, always complete the async operation with an exception. This guarantees that the caller will see the exception on the EndXxx call and can then handle it appropriately.
* Assume that whatever BeginXxx can throw is also possible to be thrown from EndXxx. The example above example assumes that WebException could happen in either case.
* Setting the "completed synchronously" status is important in the case where a caller is doing an asynchronous loop. This will inform the caller when they need to return from their async callback in order to avoid "stack dives". More information on this is available here on Michael Marucheck's blog post "[Asynchronous Programming in Indigo](http://blogs.msdn.com/b/mjm/archive/2005/05/04/414793.aspx)" (see the Stack Dive section).
Asynchronous programming is not the simplest thing but it is very powerful once you understand the concepts. |
5,534,196 | I have Windows 7 installed on my PC. I am learning C and assembly language together. I use codeblock IDE for writing C codes and emu8086 for assembly codes. I am able to DEBUG the assembly codes from DOS prompt, but not the C codes. Why so?
I select console application option while writing C codes. they run well on their own from DOS prompt, but not through DEBUG mode.
I intend to observe the machine code and the symbolic assembly code created by the C compiler.
I was assuming that Using DEBUG I should be able to trace the execution of all executable files, after all that is the purpose of DEBUG. Isn't it? | 2011/04/04 | [
"https://Stackoverflow.com/questions/5534196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597858/"
] | I realize that this question is almost one year old, but if the constraints of the asker still hold, there is an option available on .NET 3.5 to easily compose asynchronous operations. Look at Jeff Richter's [PowerThreading library](http://www.wintellect.com/PowerThreading.aspx). In the `Wintellect.PowerThreading.AsyncProgModel` namespace, you will find several variants of the `AsyncEnumerator` class, which you can use with sequence generators to write async code as if it were sequential.
The gist of it is that you write your async code as the body of a sequence generator that returns an `IEnumerator<int>`, and whenever you call an async method you issue a `yield return` with the number of async operations to wait for. The library handles the gory details.
For example, to post some data to a url and return the contents of the result:
```
public IAsyncResult BeginPostData(string url, string content, AsyncCallback callback, object state)
{
var ae = new AsyncEnumerator<string>();
return ae.BeginExecute(PostData(ae, url, content), callback, state);
}
public string EndPostData(IAsyncResult result)
{
var ae = AsyncEnumerator<string>.FromAsyncResult(result);
return ae.EndExecute(result);
}
private IEnumerator<int> PostData(AsyncEnumerator<string> ae, string url, string content)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.BeginGetRequestStream(ae.End(), null);
yield return 1;
using (var requestStream = req.EndGetRequestStream(ae.DequeAsyncResult()))
{
var bytes = Encoding.UTF8.GetBytes(content);
requestStream.BeginWrite(bytes, 0, bytes.Length, ae.end(), null);
yield return 1;
requestStream.EndWrite(ae.DequeueAsyncResult());
}
req.BeginGetResponse(ae.End(), null);
yield return 1;
using (var response = req.EndGetResponse(ae.DequeueAsyncResult()))
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
ae.Result = reader.ReadToEnd();
}
}
```
As you can see, the private `PostData()` method is responsible for the bulk of the work. There are three async methods kicked off, as indicated by the three `yield return 1` statements. With this pattern, you can chain as many async methods as you'd like and still just return one `IAsyncResult` to the caller. | I don't really understand what are you trying to achieve, but I think you should be rethinking the code.
An IAsyncResult instance is the object that allows to to handle asynchronous method calls, and they are created when you perform an async call through *BeginXXX*.
In your example, you basically want to return an instance of an IAsyncResult that **it doesn't exist yet**.
I don't really know which is the problem you are trying to solve, but maybe one of these approaches work better for you:
1. **Encapsulate** this code in a class, and make the users of your code aware that the operation is completed by **subscribing to an event**.
2. **Encapsulate** this code in a class, and make the users provide a callback delegate that will be called when the work is finished. You may pass the results as a parameter to this callback
Hope it helps! |
5,534,196 | I have Windows 7 installed on my PC. I am learning C and assembly language together. I use codeblock IDE for writing C codes and emu8086 for assembly codes. I am able to DEBUG the assembly codes from DOS prompt, but not the C codes. Why so?
I select console application option while writing C codes. they run well on their own from DOS prompt, but not through DEBUG mode.
I intend to observe the machine code and the symbolic assembly code created by the C compiler.
I was assuming that Using DEBUG I should be able to trace the execution of all executable files, after all that is the purpose of DEBUG. Isn't it? | 2011/04/04 | [
"https://Stackoverflow.com/questions/5534196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597858/"
] | The thing you're trying to do is doable, but you need to create a new implementation of IAsyncResult (something like "CompositeResult" that watches the first IAsyncResult, then kicks off the 2nd call).
However, this task is actually far easier using the Reactive Extensions - in that case you'd use Observable.FromAsyncPattern to convert your Begin/End methods into a Func that returns IObservable (which *also* represents an async result), then chain them using SelectMany:
```
IObservable<Stream> GetRequestStream(string Url);
IObservable<bool> MyOperation(Stream stream);
GetRequestStream().SelectMany(x => MyOperation(x)).Subscribe(x => {
// When everything is finished, this code will run
});
``` | First, get the `AsyncResultNoResult` and `AsyncResult<TResult>` implementation code from Jeffrey Richter's MSDN magazine article "[Implementing the CLR Asynchronous Programming Model](http://msdn.microsoft.com/en-us/magazine/cc163467.aspx) (March 2007 issue)."
Once you have those base classes, you can relatively easily implement your own async result. In this example, I will use your basic code to start the web request and then get the response as a single async operation composed of multiple inner async operations.
```
// This is the class that implements the async operations that the caller will see
internal class MyClass
{
public MyClass() { /* . . . */ }
public IAsyncResult BeginMyOperation(Uri requestUri, AsyncCallback callback, object state)
{
return new MyOperationAsyncResult(this, requestUri, callback, state);
}
public WebResponse EndMyOperation(IAsyncResult result)
{
MyOperationAsyncResult asyncResult = (MyOperationAsyncResult)result;
return asyncResult.EndInvoke();
}
private sealed class MyOperationAsyncResult : AsyncResult<WebResponse>
{
private readonly MyClass parent;
private readonly HttpWebRequest webRequest;
private bool everCompletedAsync;
public MyOperationAsyncResult(MyClass parent, Uri requestUri, AsyncCallback callback, object state)
: base(callback, state)
{
// Occasionally it is necessary to access the outer class instance from this inner
// async result class. This also ensures that the async result instance is rooted
// to the parent and doesn't get garbage collected unexpectedly.
this.parent = parent;
// Start first async operation here
this.webRequest = WebRequest.Create(requestUri);
this.webRequest.Method = "POST";
this.webRequest.BeginGetRequestStream(this.OnGetRequestStreamComplete, null);
}
private void SetCompletionStatus(IAsyncResult result)
{
// Check to see if we did not complete sync. If any async operation in
// the chain completed asynchronously, it means we had to do a thread switch
// and the callback is being invoked outside the starting thread.
if (!result.CompletedSynchronously)
{
this.everCompletedAsync = true;
}
}
private void OnGetRequestStreamComplete(IAsyncResult result)
{
this.SetCompletionStatus(result);
Stream requestStream = null;
try
{
stream = this.webRequest.EndGetRequestStream(result);
}
catch (WebException e)
{
// Cannot let exception bubble up here as we are on a callback thread;
// in this case, complete the entire async result with an exception so
// that the caller gets it back when they call EndXxx.
this.SetAsCompleted(e, !this.everCompletedAsync);
}
if (requestStream != null)
{
this.WriteToRequestStream();
this.StartGetResponse();
}
}
private void WriteToRequestStream(Stream requestStream) { /* omitted */ }
private void StartGetResponse()
{
try
{
this.webRequest.BeginGetResponse(this.OnGetResponseComplete, null);
}
catch (WebException e)
{
// As above, we cannot let this exception bubble up
this.SetAsCompleted(e, !this.everCompletedAsync);
}
}
private void OnGetResponseComplete(IAsyncResult result)
{
this.SetCompletionStatus(result);
try
{
WebResponse response = this.webRequest.EndGetResponse(result);
// At this point, we can complete the whole operation which
// will invoke the callback passed in at the very beginning
// in the constructor.
this.SetAsCompleted(response, !this.everCompletedAsync);
}
catch (WebException e)
{
// As above, we cannot let this exception bubble up
this.SetAsCompleted(e, !this.everCompletedAsync);
}
}
}
}
```
Some things to note:
* You cannot throw an exception in the context of an async callback. You will crash your application since there will be no one to handle it. Instead, always complete the async operation with an exception. This guarantees that the caller will see the exception on the EndXxx call and can then handle it appropriately.
* Assume that whatever BeginXxx can throw is also possible to be thrown from EndXxx. The example above example assumes that WebException could happen in either case.
* Setting the "completed synchronously" status is important in the case where a caller is doing an asynchronous loop. This will inform the caller when they need to return from their async callback in order to avoid "stack dives". More information on this is available here on Michael Marucheck's blog post "[Asynchronous Programming in Indigo](http://blogs.msdn.com/b/mjm/archive/2005/05/04/414793.aspx)" (see the Stack Dive section).
Asynchronous programming is not the simplest thing but it is very powerful once you understand the concepts. |
5,534,196 | I have Windows 7 installed on my PC. I am learning C and assembly language together. I use codeblock IDE for writing C codes and emu8086 for assembly codes. I am able to DEBUG the assembly codes from DOS prompt, but not the C codes. Why so?
I select console application option while writing C codes. they run well on their own from DOS prompt, but not through DEBUG mode.
I intend to observe the machine code and the symbolic assembly code created by the C compiler.
I was assuming that Using DEBUG I should be able to trace the execution of all executable files, after all that is the purpose of DEBUG. Isn't it? | 2011/04/04 | [
"https://Stackoverflow.com/questions/5534196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597858/"
] | I think the easiest way to solve this is to use `Task` wrappers. In particular, you can finish a [`TaskCompletionSource`](http://msdn.microsoft.com/en-us/library/dd449174.aspx) when `BeginGetResponse` completes. Then just return the [`Task` for that `TaskCompletionSource`](http://msdn.microsoft.com/en-us/library/dd449187.aspx). Note that `Task` implements `IAsyncResult`, so your client code won't have to change.
Personally, I would go a step further:
1. Wrap `BeginGetRequestStream` in a `Task` (using [`FromAsync`](http://msdn.microsoft.com/en-us/library/dd321543.aspx)).
2. Create a continuation for that `Task` that processes the request and wraps `BeginGetResponse` in a `Task` (again, using `FromAsync`).
3. Create a continuation for that second `Task` that completes the `TaskCompletionSource`.
IMHO, exceptions and result values are more naturally handled by `Task`s than `IAsyncResult`. | First, get the `AsyncResultNoResult` and `AsyncResult<TResult>` implementation code from Jeffrey Richter's MSDN magazine article "[Implementing the CLR Asynchronous Programming Model](http://msdn.microsoft.com/en-us/magazine/cc163467.aspx) (March 2007 issue)."
Once you have those base classes, you can relatively easily implement your own async result. In this example, I will use your basic code to start the web request and then get the response as a single async operation composed of multiple inner async operations.
```
// This is the class that implements the async operations that the caller will see
internal class MyClass
{
public MyClass() { /* . . . */ }
public IAsyncResult BeginMyOperation(Uri requestUri, AsyncCallback callback, object state)
{
return new MyOperationAsyncResult(this, requestUri, callback, state);
}
public WebResponse EndMyOperation(IAsyncResult result)
{
MyOperationAsyncResult asyncResult = (MyOperationAsyncResult)result;
return asyncResult.EndInvoke();
}
private sealed class MyOperationAsyncResult : AsyncResult<WebResponse>
{
private readonly MyClass parent;
private readonly HttpWebRequest webRequest;
private bool everCompletedAsync;
public MyOperationAsyncResult(MyClass parent, Uri requestUri, AsyncCallback callback, object state)
: base(callback, state)
{
// Occasionally it is necessary to access the outer class instance from this inner
// async result class. This also ensures that the async result instance is rooted
// to the parent and doesn't get garbage collected unexpectedly.
this.parent = parent;
// Start first async operation here
this.webRequest = WebRequest.Create(requestUri);
this.webRequest.Method = "POST";
this.webRequest.BeginGetRequestStream(this.OnGetRequestStreamComplete, null);
}
private void SetCompletionStatus(IAsyncResult result)
{
// Check to see if we did not complete sync. If any async operation in
// the chain completed asynchronously, it means we had to do a thread switch
// and the callback is being invoked outside the starting thread.
if (!result.CompletedSynchronously)
{
this.everCompletedAsync = true;
}
}
private void OnGetRequestStreamComplete(IAsyncResult result)
{
this.SetCompletionStatus(result);
Stream requestStream = null;
try
{
stream = this.webRequest.EndGetRequestStream(result);
}
catch (WebException e)
{
// Cannot let exception bubble up here as we are on a callback thread;
// in this case, complete the entire async result with an exception so
// that the caller gets it back when they call EndXxx.
this.SetAsCompleted(e, !this.everCompletedAsync);
}
if (requestStream != null)
{
this.WriteToRequestStream();
this.StartGetResponse();
}
}
private void WriteToRequestStream(Stream requestStream) { /* omitted */ }
private void StartGetResponse()
{
try
{
this.webRequest.BeginGetResponse(this.OnGetResponseComplete, null);
}
catch (WebException e)
{
// As above, we cannot let this exception bubble up
this.SetAsCompleted(e, !this.everCompletedAsync);
}
}
private void OnGetResponseComplete(IAsyncResult result)
{
this.SetCompletionStatus(result);
try
{
WebResponse response = this.webRequest.EndGetResponse(result);
// At this point, we can complete the whole operation which
// will invoke the callback passed in at the very beginning
// in the constructor.
this.SetAsCompleted(response, !this.everCompletedAsync);
}
catch (WebException e)
{
// As above, we cannot let this exception bubble up
this.SetAsCompleted(e, !this.everCompletedAsync);
}
}
}
}
```
Some things to note:
* You cannot throw an exception in the context of an async callback. You will crash your application since there will be no one to handle it. Instead, always complete the async operation with an exception. This guarantees that the caller will see the exception on the EndXxx call and can then handle it appropriately.
* Assume that whatever BeginXxx can throw is also possible to be thrown from EndXxx. The example above example assumes that WebException could happen in either case.
* Setting the "completed synchronously" status is important in the case where a caller is doing an asynchronous loop. This will inform the caller when they need to return from their async callback in order to avoid "stack dives". More information on this is available here on Michael Marucheck's blog post "[Asynchronous Programming in Indigo](http://blogs.msdn.com/b/mjm/archive/2005/05/04/414793.aspx)" (see the Stack Dive section).
Asynchronous programming is not the simplest thing but it is very powerful once you understand the concepts. |
5,534,196 | I have Windows 7 installed on my PC. I am learning C and assembly language together. I use codeblock IDE for writing C codes and emu8086 for assembly codes. I am able to DEBUG the assembly codes from DOS prompt, but not the C codes. Why so?
I select console application option while writing C codes. they run well on their own from DOS prompt, but not through DEBUG mode.
I intend to observe the machine code and the symbolic assembly code created by the C compiler.
I was assuming that Using DEBUG I should be able to trace the execution of all executable files, after all that is the purpose of DEBUG. Isn't it? | 2011/04/04 | [
"https://Stackoverflow.com/questions/5534196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597858/"
] | I realize that this question is almost one year old, but if the constraints of the asker still hold, there is an option available on .NET 3.5 to easily compose asynchronous operations. Look at Jeff Richter's [PowerThreading library](http://www.wintellect.com/PowerThreading.aspx). In the `Wintellect.PowerThreading.AsyncProgModel` namespace, you will find several variants of the `AsyncEnumerator` class, which you can use with sequence generators to write async code as if it were sequential.
The gist of it is that you write your async code as the body of a sequence generator that returns an `IEnumerator<int>`, and whenever you call an async method you issue a `yield return` with the number of async operations to wait for. The library handles the gory details.
For example, to post some data to a url and return the contents of the result:
```
public IAsyncResult BeginPostData(string url, string content, AsyncCallback callback, object state)
{
var ae = new AsyncEnumerator<string>();
return ae.BeginExecute(PostData(ae, url, content), callback, state);
}
public string EndPostData(IAsyncResult result)
{
var ae = AsyncEnumerator<string>.FromAsyncResult(result);
return ae.EndExecute(result);
}
private IEnumerator<int> PostData(AsyncEnumerator<string> ae, string url, string content)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.BeginGetRequestStream(ae.End(), null);
yield return 1;
using (var requestStream = req.EndGetRequestStream(ae.DequeAsyncResult()))
{
var bytes = Encoding.UTF8.GetBytes(content);
requestStream.BeginWrite(bytes, 0, bytes.Length, ae.end(), null);
yield return 1;
requestStream.EndWrite(ae.DequeueAsyncResult());
}
req.BeginGetResponse(ae.End(), null);
yield return 1;
using (var response = req.EndGetResponse(ae.DequeueAsyncResult()))
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
ae.Result = reader.ReadToEnd();
}
}
```
As you can see, the private `PostData()` method is responsible for the bulk of the work. There are three async methods kicked off, as indicated by the three `yield return 1` statements. With this pattern, you can chain as many async methods as you'd like and still just return one `IAsyncResult` to the caller. | First, get the `AsyncResultNoResult` and `AsyncResult<TResult>` implementation code from Jeffrey Richter's MSDN magazine article "[Implementing the CLR Asynchronous Programming Model](http://msdn.microsoft.com/en-us/magazine/cc163467.aspx) (March 2007 issue)."
Once you have those base classes, you can relatively easily implement your own async result. In this example, I will use your basic code to start the web request and then get the response as a single async operation composed of multiple inner async operations.
```
// This is the class that implements the async operations that the caller will see
internal class MyClass
{
public MyClass() { /* . . . */ }
public IAsyncResult BeginMyOperation(Uri requestUri, AsyncCallback callback, object state)
{
return new MyOperationAsyncResult(this, requestUri, callback, state);
}
public WebResponse EndMyOperation(IAsyncResult result)
{
MyOperationAsyncResult asyncResult = (MyOperationAsyncResult)result;
return asyncResult.EndInvoke();
}
private sealed class MyOperationAsyncResult : AsyncResult<WebResponse>
{
private readonly MyClass parent;
private readonly HttpWebRequest webRequest;
private bool everCompletedAsync;
public MyOperationAsyncResult(MyClass parent, Uri requestUri, AsyncCallback callback, object state)
: base(callback, state)
{
// Occasionally it is necessary to access the outer class instance from this inner
// async result class. This also ensures that the async result instance is rooted
// to the parent and doesn't get garbage collected unexpectedly.
this.parent = parent;
// Start first async operation here
this.webRequest = WebRequest.Create(requestUri);
this.webRequest.Method = "POST";
this.webRequest.BeginGetRequestStream(this.OnGetRequestStreamComplete, null);
}
private void SetCompletionStatus(IAsyncResult result)
{
// Check to see if we did not complete sync. If any async operation in
// the chain completed asynchronously, it means we had to do a thread switch
// and the callback is being invoked outside the starting thread.
if (!result.CompletedSynchronously)
{
this.everCompletedAsync = true;
}
}
private void OnGetRequestStreamComplete(IAsyncResult result)
{
this.SetCompletionStatus(result);
Stream requestStream = null;
try
{
stream = this.webRequest.EndGetRequestStream(result);
}
catch (WebException e)
{
// Cannot let exception bubble up here as we are on a callback thread;
// in this case, complete the entire async result with an exception so
// that the caller gets it back when they call EndXxx.
this.SetAsCompleted(e, !this.everCompletedAsync);
}
if (requestStream != null)
{
this.WriteToRequestStream();
this.StartGetResponse();
}
}
private void WriteToRequestStream(Stream requestStream) { /* omitted */ }
private void StartGetResponse()
{
try
{
this.webRequest.BeginGetResponse(this.OnGetResponseComplete, null);
}
catch (WebException e)
{
// As above, we cannot let this exception bubble up
this.SetAsCompleted(e, !this.everCompletedAsync);
}
}
private void OnGetResponseComplete(IAsyncResult result)
{
this.SetCompletionStatus(result);
try
{
WebResponse response = this.webRequest.EndGetResponse(result);
// At this point, we can complete the whole operation which
// will invoke the callback passed in at the very beginning
// in the constructor.
this.SetAsCompleted(response, !this.everCompletedAsync);
}
catch (WebException e)
{
// As above, we cannot let this exception bubble up
this.SetAsCompleted(e, !this.everCompletedAsync);
}
}
}
}
```
Some things to note:
* You cannot throw an exception in the context of an async callback. You will crash your application since there will be no one to handle it. Instead, always complete the async operation with an exception. This guarantees that the caller will see the exception on the EndXxx call and can then handle it appropriately.
* Assume that whatever BeginXxx can throw is also possible to be thrown from EndXxx. The example above example assumes that WebException could happen in either case.
* Setting the "completed synchronously" status is important in the case where a caller is doing an asynchronous loop. This will inform the caller when they need to return from their async callback in order to avoid "stack dives". More information on this is available here on Michael Marucheck's blog post "[Asynchronous Programming in Indigo](http://blogs.msdn.com/b/mjm/archive/2005/05/04/414793.aspx)" (see the Stack Dive section).
Asynchronous programming is not the simplest thing but it is very powerful once you understand the concepts. |
259,123 | Here's the problem, in a nutshell:
>
> *Glancy T. Pony is a mod on our mayonnaise site, and wakes up in the
> afternoon to find that her site has been littered by Miracle Whip
> astroturfers. As Glancy [cleans up the mess](https://meta.stackexchange.com/questions/259050/as-a-moderator-should-i-re-flag-spam-thats-already-flagged-or-just-delete-it/259117#259117), she notices that many
> of these spammers have accounts on multiple sites, where they've been
> dropping heathen sandwich spread everywhere.*
>
>
> *Glancy, sadly, can only
> take action on **her** site, so she spends even more of her valuable
> time rallying help in chat to get the rest of the accounts nuked. She
> feels like there **must** be some way for her actions to do more, since
> it's so blatant.*
>
>
>
I want to try to make this a reality, and I'm not talking about a site for mayonnaise (it's on-topic at Seasoned Advice). I'd like for per-site destructions of spammers to count more meaningfully when it comes to cleaning up network spam as a whole.
Here's what's blocking it:
* Mods are elected on a per-site basis, by individual communities. Are programmers willing to trust [car mechanics](http://mechanics.stackexchange.com) and [physicists](http://physics.stackexchange.com) to help keep Stack Overflow clean? (Along with the reverse)
* We've worked, quite extensively, at coming up with criteria for the system to notice and take action upon. E.g. if an *account* has more than X profiles destroyed for spam, and *all* profiles are eligible (less than 50 rep on any profile), automatically destroy them all. This works, but it turns out to be almost *as slow* as just waiting for the rest of the mods to notice in many cases. How can this be better, safely?
* While I am *certain* it would never come to pass, this sets up a system that if abused, could have some kind of awful consequences. We trust *every single one* of our moderators completely and extensively. It's just a possibility, however remote, that needs to be mentioned. What other guard rails could we put around it?
Please think about it. If you have ideas on how this could work, strong feelings on if it should or shouldn't be implemented, or just feedback in general - we'd love to hear it.
Part of my area of speciality at SE has been spam / abuse mitigation, and this keeps coming up. My response thus far has been *it's not a horrible idea, let's see if a time comes when we really need it.*
It's time to talk about it. | 2015/06/22 | [
"https://meta.stackexchange.com/questions/259123",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/50049/"
] | If I as a mod on Stack Overflow destroy an account for spam, you could immediately put a brake onto any linked accounts to require either more "I am human" validation or just hobble to one post per week and then flag up that account to the site moderators as one that's posted spam elsewhere. You could also feed the spam posts into the anti-spam program as more data (if you're not already doing that).
Then when the other moderators come online they'll see these flags and be able to act and hopefully the hobbling etc. will prevent too much spam being spewed onto the system in the meantime.
If they have accounts destroyed on **multiple** sites then intensify the hobbling or if enough accounts (more than half) are destroyed then automatically destroy the rest. | Create a "Destroy as spam account" function for moderators.
As part of the procedure do the following:
* Automatically generate a flag on any site that account is registered on for that user ("Network Spammer Detected")
* Automatically generate a flag for any other accounts with the same IP ("Possible Network Spammer")
* Prevent creation of new accounts on all of SE for accounts with that IP if they are "Destroyed as spam" on more than 1 SE site
This lets each site community handle their spammer(s) individually on a case by case basis.
But it still creates visibility for when network spammers exist on *other* sites which also affect your site.
Note that while this is going to "allow" a spammer to be destroyed on 1 site and then create another account, the third point will prevent mean that any spammer IP being destroyed on 2 sites will stop creation - period. Regardless of when the accounts were created.
---
Another thing which would help this:
* Automatically raise the second flag ("Possible Spammer") whenever a post has a community deleted spam post.
Right now, this is invisible to moderators. As a moderator I don't see users which post 1 thing and get community spam-flag deleted - providing visibility into this situation would help, too. |
259,123 | Here's the problem, in a nutshell:
>
> *Glancy T. Pony is a mod on our mayonnaise site, and wakes up in the
> afternoon to find that her site has been littered by Miracle Whip
> astroturfers. As Glancy [cleans up the mess](https://meta.stackexchange.com/questions/259050/as-a-moderator-should-i-re-flag-spam-thats-already-flagged-or-just-delete-it/259117#259117), she notices that many
> of these spammers have accounts on multiple sites, where they've been
> dropping heathen sandwich spread everywhere.*
>
>
> *Glancy, sadly, can only
> take action on **her** site, so she spends even more of her valuable
> time rallying help in chat to get the rest of the accounts nuked. She
> feels like there **must** be some way for her actions to do more, since
> it's so blatant.*
>
>
>
I want to try to make this a reality, and I'm not talking about a site for mayonnaise (it's on-topic at Seasoned Advice). I'd like for per-site destructions of spammers to count more meaningfully when it comes to cleaning up network spam as a whole.
Here's what's blocking it:
* Mods are elected on a per-site basis, by individual communities. Are programmers willing to trust [car mechanics](http://mechanics.stackexchange.com) and [physicists](http://physics.stackexchange.com) to help keep Stack Overflow clean? (Along with the reverse)
* We've worked, quite extensively, at coming up with criteria for the system to notice and take action upon. E.g. if an *account* has more than X profiles destroyed for spam, and *all* profiles are eligible (less than 50 rep on any profile), automatically destroy them all. This works, but it turns out to be almost *as slow* as just waiting for the rest of the mods to notice in many cases. How can this be better, safely?
* While I am *certain* it would never come to pass, this sets up a system that if abused, could have some kind of awful consequences. We trust *every single one* of our moderators completely and extensively. It's just a possibility, however remote, that needs to be mentioned. What other guard rails could we put around it?
Please think about it. If you have ideas on how this could work, strong feelings on if it should or shouldn't be implemented, or just feedback in general - we'd love to hear it.
Part of my area of speciality at SE has been spam / abuse mitigation, and this keeps coming up. My response thus far has been *it's not a horrible idea, let's see if a time comes when we really need it.*
It's time to talk about it. | 2015/06/22 | [
"https://meta.stackexchange.com/questions/259123",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/50049/"
] | If I as a mod on Stack Overflow destroy an account for spam, you could immediately put a brake onto any linked accounts to require either more "I am human" validation or just hobble to one post per week and then flag up that account to the site moderators as one that's posted spam elsewhere. You could also feed the spam posts into the anti-spam program as more data (if you're not already doing that).
Then when the other moderators come online they'll see these flags and be able to act and hopefully the hobbling etc. will prevent too much spam being spewed onto the system in the meantime.
If they have accounts destroyed on **multiple** sites then intensify the hobbling or if enough accounts (more than half) are destroyed then automatically destroy the rest. | One of the important things I think per-site mods should have possibility to **vote on nuking a network profile of spammer**.
How can it work
* One mod on one site can vote to nuke a network spammer's profile, and only one per site
* There would be three votes from three moderators of three different sites required to nuke the spammer network-wide; apart from that at least one moderator, who has their site attacked by spammer must vote, the other moderators can discuss whether to vote or not in the room number four.
* One spammer can be considered network-wide once he spam on three different stacks (three is probably for consistence there :).
This should ease destroying network spammers - I guess the decisions of three moderators of different sites can be trusted very well.
(Also, maybe some special item in the mod-dashboard can be added, annoyingly blinking when someone votes to nuke the network-wide spammer). |
259,123 | Here's the problem, in a nutshell:
>
> *Glancy T. Pony is a mod on our mayonnaise site, and wakes up in the
> afternoon to find that her site has been littered by Miracle Whip
> astroturfers. As Glancy [cleans up the mess](https://meta.stackexchange.com/questions/259050/as-a-moderator-should-i-re-flag-spam-thats-already-flagged-or-just-delete-it/259117#259117), she notices that many
> of these spammers have accounts on multiple sites, where they've been
> dropping heathen sandwich spread everywhere.*
>
>
> *Glancy, sadly, can only
> take action on **her** site, so she spends even more of her valuable
> time rallying help in chat to get the rest of the accounts nuked. She
> feels like there **must** be some way for her actions to do more, since
> it's so blatant.*
>
>
>
I want to try to make this a reality, and I'm not talking about a site for mayonnaise (it's on-topic at Seasoned Advice). I'd like for per-site destructions of spammers to count more meaningfully when it comes to cleaning up network spam as a whole.
Here's what's blocking it:
* Mods are elected on a per-site basis, by individual communities. Are programmers willing to trust [car mechanics](http://mechanics.stackexchange.com) and [physicists](http://physics.stackexchange.com) to help keep Stack Overflow clean? (Along with the reverse)
* We've worked, quite extensively, at coming up with criteria for the system to notice and take action upon. E.g. if an *account* has more than X profiles destroyed for spam, and *all* profiles are eligible (less than 50 rep on any profile), automatically destroy them all. This works, but it turns out to be almost *as slow* as just waiting for the rest of the mods to notice in many cases. How can this be better, safely?
* While I am *certain* it would never come to pass, this sets up a system that if abused, could have some kind of awful consequences. We trust *every single one* of our moderators completely and extensively. It's just a possibility, however remote, that needs to be mentioned. What other guard rails could we put around it?
Please think about it. If you have ideas on how this could work, strong feelings on if it should or shouldn't be implemented, or just feedback in general - we'd love to hear it.
Part of my area of speciality at SE has been spam / abuse mitigation, and this keeps coming up. My response thus far has been *it's not a horrible idea, let's see if a time comes when we really need it.*
It's time to talk about it. | 2015/06/22 | [
"https://meta.stackexchange.com/questions/259123",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/50049/"
] | When we get spam, it is almost invariably by users with 1 rep point whose network profiles are also at or around 1 rep. I am reasonably certain that all spammers I've deleted should have been deleted network-wide.
This would suggest that it may well be a good idea to propagate deletions across multiple sites. At least as long as those users have very low reputation. Perhaps even under 10. I would also not object to mods from other sites having such powers in the communities I represent.
However, to avoid complications and protect against human error, we could always simply raise automatic flags. For example, I can imagine a system where
1. I destroy a user choosing spam as the reason.
2. An automatic flag is raised on that user on all sites where they have a profile.
3. In the flag review page, the mods of the target site get the option to delete the user or not.
This has the advantage that it greatly facilitates communication between different sites and *bona fide* spammers will be destroyed more efficiently while at the same time not allowing a mistake I might make to affect other sites. It sounds like the best of both worlds. | One of the important things I think per-site mods should have possibility to **vote on nuking a network profile of spammer**.
How can it work
* One mod on one site can vote to nuke a network spammer's profile, and only one per site
* There would be three votes from three moderators of three different sites required to nuke the spammer network-wide; apart from that at least one moderator, who has their site attacked by spammer must vote, the other moderators can discuss whether to vote or not in the room number four.
* One spammer can be considered network-wide once he spam on three different stacks (three is probably for consistence there :).
This should ease destroying network spammers - I guess the decisions of three moderators of different sites can be trusted very well.
(Also, maybe some special item in the mod-dashboard can be added, annoyingly blinking when someone votes to nuke the network-wide spammer). |
259,123 | Here's the problem, in a nutshell:
>
> *Glancy T. Pony is a mod on our mayonnaise site, and wakes up in the
> afternoon to find that her site has been littered by Miracle Whip
> astroturfers. As Glancy [cleans up the mess](https://meta.stackexchange.com/questions/259050/as-a-moderator-should-i-re-flag-spam-thats-already-flagged-or-just-delete-it/259117#259117), she notices that many
> of these spammers have accounts on multiple sites, where they've been
> dropping heathen sandwich spread everywhere.*
>
>
> *Glancy, sadly, can only
> take action on **her** site, so she spends even more of her valuable
> time rallying help in chat to get the rest of the accounts nuked. She
> feels like there **must** be some way for her actions to do more, since
> it's so blatant.*
>
>
>
I want to try to make this a reality, and I'm not talking about a site for mayonnaise (it's on-topic at Seasoned Advice). I'd like for per-site destructions of spammers to count more meaningfully when it comes to cleaning up network spam as a whole.
Here's what's blocking it:
* Mods are elected on a per-site basis, by individual communities. Are programmers willing to trust [car mechanics](http://mechanics.stackexchange.com) and [physicists](http://physics.stackexchange.com) to help keep Stack Overflow clean? (Along with the reverse)
* We've worked, quite extensively, at coming up with criteria for the system to notice and take action upon. E.g. if an *account* has more than X profiles destroyed for spam, and *all* profiles are eligible (less than 50 rep on any profile), automatically destroy them all. This works, but it turns out to be almost *as slow* as just waiting for the rest of the mods to notice in many cases. How can this be better, safely?
* While I am *certain* it would never come to pass, this sets up a system that if abused, could have some kind of awful consequences. We trust *every single one* of our moderators completely and extensively. It's just a possibility, however remote, that needs to be mentioned. What other guard rails could we put around it?
Please think about it. If you have ideas on how this could work, strong feelings on if it should or shouldn't be implemented, or just feedback in general - we'd love to hear it.
Part of my area of speciality at SE has been spam / abuse mitigation, and this keeps coming up. My response thus far has been *it's not a horrible idea, let's see if a time comes when we really need it.*
It's time to talk about it. | 2015/06/22 | [
"https://meta.stackexchange.com/questions/259123",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/50049/"
] | Create a "Destroy as spam account" function for moderators.
As part of the procedure do the following:
* Automatically generate a flag on any site that account is registered on for that user ("Network Spammer Detected")
* Automatically generate a flag for any other accounts with the same IP ("Possible Network Spammer")
* Prevent creation of new accounts on all of SE for accounts with that IP if they are "Destroyed as spam" on more than 1 SE site
This lets each site community handle their spammer(s) individually on a case by case basis.
But it still creates visibility for when network spammers exist on *other* sites which also affect your site.
Note that while this is going to "allow" a spammer to be destroyed on 1 site and then create another account, the third point will prevent mean that any spammer IP being destroyed on 2 sites will stop creation - period. Regardless of when the accounts were created.
---
Another thing which would help this:
* Automatically raise the second flag ("Possible Spammer") whenever a post has a community deleted spam post.
Right now, this is invisible to moderators. As a moderator I don't see users which post 1 thing and get community spam-flag deleted - providing visibility into this situation would help, too. | Blatant spam is the one universal issue that I would expect every moderator from every site to recognize. It does not need any domain knowledge or familiarity with the site to act on it.
One thing I think would be nice in general, and would avoid honest mistakes would be to actually mention the consequences of the destroy action in the dialog. Currently this dialog only mentions why the user should be destroyed, it might not be obvious to all mods that this has further consequences beyond the removal of the account and the posts.
While there are no differences in power between mods right now, I think this kind of tool could behave a bit differently based on seniority of the moderator and the amount of spam flags and user destructions the moderator has done. I'm mostly thinking about not taking the first few destructions from a new mod into account, just to avoid bigger consequences in case they simply misunderstood the tools.
I think in terms of signal, two destructions by (not completely new) moderators on two different sites should be enough to trigger the removal of all connected accounts. With the safeguard that there should be no significant real participation (upvoted posts) by those accounts.
Most spammers don't have any upvoted posts, I'd use something like the following criteria to restrict the tool:
* No more than 1-2 upvoted posts. I'd maybe even go with 0, I generally don't see upvoted spam, but I've heard it exists.
* No older, unflagged posts. If it's been here for a week and isn't removed, it probably isn't spam and the user at least not a completely obvious spammer.
These restrictions would ensure that even if the tool is triggered in error, the damage would be very limited. Those criteria are certainly exploitable by spammers, but you can always change them if that turns out to actually happen.
I'd strongly support such a tool as I think the current way of handling cross-site spammers is unnecessarily noisy. Pinging other mods in chat or CMs just to clean up some spammer accounts that might be abandoned or not is just not that efficient. |
259,123 | Here's the problem, in a nutshell:
>
> *Glancy T. Pony is a mod on our mayonnaise site, and wakes up in the
> afternoon to find that her site has been littered by Miracle Whip
> astroturfers. As Glancy [cleans up the mess](https://meta.stackexchange.com/questions/259050/as-a-moderator-should-i-re-flag-spam-thats-already-flagged-or-just-delete-it/259117#259117), she notices that many
> of these spammers have accounts on multiple sites, where they've been
> dropping heathen sandwich spread everywhere.*
>
>
> *Glancy, sadly, can only
> take action on **her** site, so she spends even more of her valuable
> time rallying help in chat to get the rest of the accounts nuked. She
> feels like there **must** be some way for her actions to do more, since
> it's so blatant.*
>
>
>
I want to try to make this a reality, and I'm not talking about a site for mayonnaise (it's on-topic at Seasoned Advice). I'd like for per-site destructions of spammers to count more meaningfully when it comes to cleaning up network spam as a whole.
Here's what's blocking it:
* Mods are elected on a per-site basis, by individual communities. Are programmers willing to trust [car mechanics](http://mechanics.stackexchange.com) and [physicists](http://physics.stackexchange.com) to help keep Stack Overflow clean? (Along with the reverse)
* We've worked, quite extensively, at coming up with criteria for the system to notice and take action upon. E.g. if an *account* has more than X profiles destroyed for spam, and *all* profiles are eligible (less than 50 rep on any profile), automatically destroy them all. This works, but it turns out to be almost *as slow* as just waiting for the rest of the mods to notice in many cases. How can this be better, safely?
* While I am *certain* it would never come to pass, this sets up a system that if abused, could have some kind of awful consequences. We trust *every single one* of our moderators completely and extensively. It's just a possibility, however remote, that needs to be mentioned. What other guard rails could we put around it?
Please think about it. If you have ideas on how this could work, strong feelings on if it should or shouldn't be implemented, or just feedback in general - we'd love to hear it.
Part of my area of speciality at SE has been spam / abuse mitigation, and this keeps coming up. My response thus far has been *it's not a horrible idea, let's see if a time comes when we really need it.*
It's time to talk about it. | 2015/06/22 | [
"https://meta.stackexchange.com/questions/259123",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/50049/"
] | I suggest a *networked moderator review queue*, only accessible by moderators.
(Bear with me..it has good potential)
**TL;DR;**
Have a new review queue accessible by moderators only, which would be shown to all moderators across all sites.
When a user is marked as spammy, the system would raise a flag, add a new review in the moderator-only review queue, and then all moderators on all sites could see it and vote on what action to take (or add to a current review if user is already being reviewed).
Spam is not really site specific, so is ok for mods to vote on spam related things from other sites, imo.
---
Responses to your criteria (Tim)
--------------------------------
>
> Are programmers willing to trust car mechanics and physicists to help
> keep Stack Overflow clean? (Along with the reverse)
>
>
>
I don't think "spam" is site specific, however a review queue helps with this by requiring more than one vote to action something.
>
> if an account has more than X profiles destroyed for spam, and all
> profiles are eligible (less than 50 rep on any profile), automatically
> destroy them all.
>
>
>
This can easily be worked into a moderator review queue, and an auto action taken once vote thresholds are reached.
>
> While I am certain it would never come to pass, this sets up a system
> that if abused, could have some kind of awful consequences. We trust
> every single one of our moderators completely and extensively. It's
> just a possibility, however remote, that needs to be mentioned. What
> other guard rails could we put around it?
>
>
>
A review queue with multiple votes caters for this too.
And moderator decisions can be seen by all other mods, so anyone can nudge another mod and advise on their not-so-perfect decisions - "Hey, FYI, that was obvious spam because XYZ".
---
The basic setup
---------------
Again, this is all only accessible by moderators, and not even readable by non-mods.
Every Stack site would have a new "moderator review queue".
When a user is moderated for spammy actions by a mod on one site, the system raises a flag, and details of the actions would go into the moderator review queue on *all* sites.
If a flag has already been raised for that user, then there would already be a review in the queue, in that case this new flag would just be added to the current review of that user as additional data.
This would allow all mods on all sites to see current spam actions being made on other sites, by other mods. Moderators can then check the user account on *their* site and perform an action in that same (global) review.
It allows mods from any/all sites to cast votes as to how best to deal with this user, and not just based on their own site and own findings.
This makes it a fast process, and more than a single person making a decision.
When there's a review needing attention (i.e. without an outcome) there would be a notification on the top-bar (*like* the "suggested edits notification").
This would cater for the *fast action* requirement, especially as any mod on any site can cast a review vote, so an outcome would come quickly.
The review queue should be updated from various places where a mod deals with a spammy user.
e.g. A mod flags a user as spammy in an question or answer, the system adds it to the review (or a new review opened if none exists).
This stops mods having to manually raise or update a review - it's all just auto fed in based on their actions, and other mods from all sites can then review it.
The review
----------
Various useful data of the user would be in the review, such as:
* Links to all spam posts flagged by all mods/sites for the user
* Other "potential/suspected" accounts that user might have
* Previous moderation actions against the user
* A link in the review to the user's profile - but the link would be
different for each mod, and link to the site they are a mod for.
Allowing mods to quickly check if that user is spamming on *their*
site (instead of having to search for that user etc).
This allows a single place for all data to be studied about that user - instead of having to check other sites, chat to other mods, write stuff down, etc.
Review actions
--------------
Stack would set this up, and it's going to require more in-depth functions and consideration than I care to delve into here.
But for an example to illustrate how my idea would pan out:
1. Mod on *SiteA* flags spam from a user
2. System places data in the moderator review queue, all mods
on all sites can see it and are notified on the top-bar
3. Mods on *SiteB* see the user has also spammed on their site
(*SiteB*), they flag it and so it gets added to the review for that
user (same review). This updates the review to show the user has also
spammed on *SiteB* for all other mods on all other sites to see. A
picture is building up
4. Other actions can be performed, such as any mods voting to ban user,
suspend user, block account on one, some, or all sites, etc.
Or, point 3 might be non-existent, and user is only spamming on one site, so mods decide to vote to ban/suspend the user on that one site only.
The outcome will be determined by usual review queue criteria:
`X votes by mods for Z reason`
For example 5 mods vote "ban user site wide" and so the action is completed.
---
Complex review
--------------
For it to be useful, the moderator review won't be exactly like our current normal user review queues, where simply one action per user only, and when threshold met review is completed.
A moderator review should show various data about a flagged user, so a more concise and accurate decision can be made.
Such as the posts and sites the user has spammed on, and any suspected other accounts the user has.
So, while data is being gathered, new things come to light, so votes could change.
(These are moderators, so I expect that they won't just stupidly change votes for no good reason... or at least shouldn't.)
For example, changing one's vote:
1. UserA has a review up against them for spamming on *one* site
2. Mods start to vote "ban user on that one site"
3. A mod from another site flags spam on their site, which is fed into
the review. Now it shows the user is spamming on *two* sites
4. Mods can then change their vote from "ban on one site" to "ban on
two sites..or network wide" because more data is found
If votes are cast and review complete, and more data comes to light, mods want to change the outcome (re-vote).
There are two ways to tackle this. When a mod flags the newly found spam (from the same user but not previously flagged) the new data will either:
1. Resurrect the old review and reset the votes, so mods can vote
including with the new data
2. Or a new review can be made, with a link to the previous review so
previous data can be seen
There are pros and cons to both. I'm sure Stack would resolve this easily, perhaps with an option to re-open an old review if a user is seen to be "up to old tricks" etc.
---
I also suggest that different data within the review can be voted on separately.
This is because it's not going to be black and white "user has X spam posts - what should we do".
There will be other info and data to take into consideration.
For example:
1. Mods suspect the user of having multiple accounts, so the review
shows "potential/suspected other accounts for this user" (and a list
of the accounts)
2. Mods can investigate and gather data to confirm if the user has
multiple accounts
3. A mod finds one of those accounts *is* the same user, so marks the
"potential other account" as "confirmed" in the review queue
4. Other mods can see this, and vote accordingly, or change their
previous vote cast
This too will change voting, because a user with multiple bad accounts should perhaps be banned completely, whereas a user with one account and spammed on one site, might be simply "not knowing the rules" (etc).
---
Review done
-----------
The review will be done and moved out of the queue when all tasks are completed.
For example, if the voting is complete for banning, and the user is banned, but there are still some unconfirmed "potential/suspect other accounts", the review would stay in the queue until dealt with.
This is because those other accounts might not be yet banned, and it could be that same spammy user who is banned on one account. The entire task needs to be completed.
---
Advantages
----------
1. Fast outcomes - Any active mods from any site can jump in and
action the user
2. No one mod can invoke a network wide ban, takes multiple "opinions"
3. No one mod can ban a user from a site they are not a mod on, takes
multiple mods from various sites
4. While it would be new code, it will allow certain code re-use, and
hooks into the current systems and setup (rather than entire new system)
5. Staff and Stack devs have great knowledge of review queues now, with
tried and tested things, so you could fairly quickly set this up to
what works best (rather than entire new system)
6. A users previous moderation will be stored for future reference.
The system can pull out data to put in new reviews for the same
user
7. No need for "clunky" chat to tell each other about stuff, make
discuss, and a unanimous decision is made easily and without
discussions
8. There is a historical record of spam moderation, which means new
moderators, or those not so confident (small sites) can study the
previous decisions and learn good practices. Without having to chat
to or ask other mods
9. An outcome being from multiple moderators is more likely to make a
better decision
---
More than just spam
-------------------
This will take a fair bit of work, even re-using *some* current review code and knowledge of how reviewing works best (etc).
However, once this is up and running, tweaked, and bugs ironed out, other moderation things could be fed into here.
Not being a mod, I cannot suggest anything which would be useful, but there must surely be other things would would benefit a moderator-only review queue? | One of the important things I think per-site mods should have possibility to **vote on nuking a network profile of spammer**.
How can it work
* One mod on one site can vote to nuke a network spammer's profile, and only one per site
* There would be three votes from three moderators of three different sites required to nuke the spammer network-wide; apart from that at least one moderator, who has their site attacked by spammer must vote, the other moderators can discuss whether to vote or not in the room number four.
* One spammer can be considered network-wide once he spam on three different stacks (three is probably for consistence there :).
This should ease destroying network spammers - I guess the decisions of three moderators of different sites can be trusted very well.
(Also, maybe some special item in the mod-dashboard can be added, annoyingly blinking when someone votes to nuke the network-wide spammer). |
259,123 | Here's the problem, in a nutshell:
>
> *Glancy T. Pony is a mod on our mayonnaise site, and wakes up in the
> afternoon to find that her site has been littered by Miracle Whip
> astroturfers. As Glancy [cleans up the mess](https://meta.stackexchange.com/questions/259050/as-a-moderator-should-i-re-flag-spam-thats-already-flagged-or-just-delete-it/259117#259117), she notices that many
> of these spammers have accounts on multiple sites, where they've been
> dropping heathen sandwich spread everywhere.*
>
>
> *Glancy, sadly, can only
> take action on **her** site, so she spends even more of her valuable
> time rallying help in chat to get the rest of the accounts nuked. She
> feels like there **must** be some way for her actions to do more, since
> it's so blatant.*
>
>
>
I want to try to make this a reality, and I'm not talking about a site for mayonnaise (it's on-topic at Seasoned Advice). I'd like for per-site destructions of spammers to count more meaningfully when it comes to cleaning up network spam as a whole.
Here's what's blocking it:
* Mods are elected on a per-site basis, by individual communities. Are programmers willing to trust [car mechanics](http://mechanics.stackexchange.com) and [physicists](http://physics.stackexchange.com) to help keep Stack Overflow clean? (Along with the reverse)
* We've worked, quite extensively, at coming up with criteria for the system to notice and take action upon. E.g. if an *account* has more than X profiles destroyed for spam, and *all* profiles are eligible (less than 50 rep on any profile), automatically destroy them all. This works, but it turns out to be almost *as slow* as just waiting for the rest of the mods to notice in many cases. How can this be better, safely?
* While I am *certain* it would never come to pass, this sets up a system that if abused, could have some kind of awful consequences. We trust *every single one* of our moderators completely and extensively. It's just a possibility, however remote, that needs to be mentioned. What other guard rails could we put around it?
Please think about it. If you have ideas on how this could work, strong feelings on if it should or shouldn't be implemented, or just feedback in general - we'd love to hear it.
Part of my area of speciality at SE has been spam / abuse mitigation, and this keeps coming up. My response thus far has been *it's not a horrible idea, let's see if a time comes when we really need it.*
It's time to talk about it. | 2015/06/22 | [
"https://meta.stackexchange.com/questions/259123",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/50049/"
] | Blatant spam is the one universal issue that I would expect every moderator from every site to recognize. It does not need any domain knowledge or familiarity with the site to act on it.
One thing I think would be nice in general, and would avoid honest mistakes would be to actually mention the consequences of the destroy action in the dialog. Currently this dialog only mentions why the user should be destroyed, it might not be obvious to all mods that this has further consequences beyond the removal of the account and the posts.
While there are no differences in power between mods right now, I think this kind of tool could behave a bit differently based on seniority of the moderator and the amount of spam flags and user destructions the moderator has done. I'm mostly thinking about not taking the first few destructions from a new mod into account, just to avoid bigger consequences in case they simply misunderstood the tools.
I think in terms of signal, two destructions by (not completely new) moderators on two different sites should be enough to trigger the removal of all connected accounts. With the safeguard that there should be no significant real participation (upvoted posts) by those accounts.
Most spammers don't have any upvoted posts, I'd use something like the following criteria to restrict the tool:
* No more than 1-2 upvoted posts. I'd maybe even go with 0, I generally don't see upvoted spam, but I've heard it exists.
* No older, unflagged posts. If it's been here for a week and isn't removed, it probably isn't spam and the user at least not a completely obvious spammer.
These restrictions would ensure that even if the tool is triggered in error, the damage would be very limited. Those criteria are certainly exploitable by spammers, but you can always change them if that turns out to actually happen.
I'd strongly support such a tool as I think the current way of handling cross-site spammers is unnecessarily noisy. Pinging other mods in chat or CMs just to clean up some spammer accounts that might be abandoned or not is just not that efficient. | I suggest a *networked moderator review queue*, only accessible by moderators.
(Bear with me..it has good potential)
**TL;DR;**
Have a new review queue accessible by moderators only, which would be shown to all moderators across all sites.
When a user is marked as spammy, the system would raise a flag, add a new review in the moderator-only review queue, and then all moderators on all sites could see it and vote on what action to take (or add to a current review if user is already being reviewed).
Spam is not really site specific, so is ok for mods to vote on spam related things from other sites, imo.
---
Responses to your criteria (Tim)
--------------------------------
>
> Are programmers willing to trust car mechanics and physicists to help
> keep Stack Overflow clean? (Along with the reverse)
>
>
>
I don't think "spam" is site specific, however a review queue helps with this by requiring more than one vote to action something.
>
> if an account has more than X profiles destroyed for spam, and all
> profiles are eligible (less than 50 rep on any profile), automatically
> destroy them all.
>
>
>
This can easily be worked into a moderator review queue, and an auto action taken once vote thresholds are reached.
>
> While I am certain it would never come to pass, this sets up a system
> that if abused, could have some kind of awful consequences. We trust
> every single one of our moderators completely and extensively. It's
> just a possibility, however remote, that needs to be mentioned. What
> other guard rails could we put around it?
>
>
>
A review queue with multiple votes caters for this too.
And moderator decisions can be seen by all other mods, so anyone can nudge another mod and advise on their not-so-perfect decisions - "Hey, FYI, that was obvious spam because XYZ".
---
The basic setup
---------------
Again, this is all only accessible by moderators, and not even readable by non-mods.
Every Stack site would have a new "moderator review queue".
When a user is moderated for spammy actions by a mod on one site, the system raises a flag, and details of the actions would go into the moderator review queue on *all* sites.
If a flag has already been raised for that user, then there would already be a review in the queue, in that case this new flag would just be added to the current review of that user as additional data.
This would allow all mods on all sites to see current spam actions being made on other sites, by other mods. Moderators can then check the user account on *their* site and perform an action in that same (global) review.
It allows mods from any/all sites to cast votes as to how best to deal with this user, and not just based on their own site and own findings.
This makes it a fast process, and more than a single person making a decision.
When there's a review needing attention (i.e. without an outcome) there would be a notification on the top-bar (*like* the "suggested edits notification").
This would cater for the *fast action* requirement, especially as any mod on any site can cast a review vote, so an outcome would come quickly.
The review queue should be updated from various places where a mod deals with a spammy user.
e.g. A mod flags a user as spammy in an question or answer, the system adds it to the review (or a new review opened if none exists).
This stops mods having to manually raise or update a review - it's all just auto fed in based on their actions, and other mods from all sites can then review it.
The review
----------
Various useful data of the user would be in the review, such as:
* Links to all spam posts flagged by all mods/sites for the user
* Other "potential/suspected" accounts that user might have
* Previous moderation actions against the user
* A link in the review to the user's profile - but the link would be
different for each mod, and link to the site they are a mod for.
Allowing mods to quickly check if that user is spamming on *their*
site (instead of having to search for that user etc).
This allows a single place for all data to be studied about that user - instead of having to check other sites, chat to other mods, write stuff down, etc.
Review actions
--------------
Stack would set this up, and it's going to require more in-depth functions and consideration than I care to delve into here.
But for an example to illustrate how my idea would pan out:
1. Mod on *SiteA* flags spam from a user
2. System places data in the moderator review queue, all mods
on all sites can see it and are notified on the top-bar
3. Mods on *SiteB* see the user has also spammed on their site
(*SiteB*), they flag it and so it gets added to the review for that
user (same review). This updates the review to show the user has also
spammed on *SiteB* for all other mods on all other sites to see. A
picture is building up
4. Other actions can be performed, such as any mods voting to ban user,
suspend user, block account on one, some, or all sites, etc.
Or, point 3 might be non-existent, and user is only spamming on one site, so mods decide to vote to ban/suspend the user on that one site only.
The outcome will be determined by usual review queue criteria:
`X votes by mods for Z reason`
For example 5 mods vote "ban user site wide" and so the action is completed.
---
Complex review
--------------
For it to be useful, the moderator review won't be exactly like our current normal user review queues, where simply one action per user only, and when threshold met review is completed.
A moderator review should show various data about a flagged user, so a more concise and accurate decision can be made.
Such as the posts and sites the user has spammed on, and any suspected other accounts the user has.
So, while data is being gathered, new things come to light, so votes could change.
(These are moderators, so I expect that they won't just stupidly change votes for no good reason... or at least shouldn't.)
For example, changing one's vote:
1. UserA has a review up against them for spamming on *one* site
2. Mods start to vote "ban user on that one site"
3. A mod from another site flags spam on their site, which is fed into
the review. Now it shows the user is spamming on *two* sites
4. Mods can then change their vote from "ban on one site" to "ban on
two sites..or network wide" because more data is found
If votes are cast and review complete, and more data comes to light, mods want to change the outcome (re-vote).
There are two ways to tackle this. When a mod flags the newly found spam (from the same user but not previously flagged) the new data will either:
1. Resurrect the old review and reset the votes, so mods can vote
including with the new data
2. Or a new review can be made, with a link to the previous review so
previous data can be seen
There are pros and cons to both. I'm sure Stack would resolve this easily, perhaps with an option to re-open an old review if a user is seen to be "up to old tricks" etc.
---
I also suggest that different data within the review can be voted on separately.
This is because it's not going to be black and white "user has X spam posts - what should we do".
There will be other info and data to take into consideration.
For example:
1. Mods suspect the user of having multiple accounts, so the review
shows "potential/suspected other accounts for this user" (and a list
of the accounts)
2. Mods can investigate and gather data to confirm if the user has
multiple accounts
3. A mod finds one of those accounts *is* the same user, so marks the
"potential other account" as "confirmed" in the review queue
4. Other mods can see this, and vote accordingly, or change their
previous vote cast
This too will change voting, because a user with multiple bad accounts should perhaps be banned completely, whereas a user with one account and spammed on one site, might be simply "not knowing the rules" (etc).
---
Review done
-----------
The review will be done and moved out of the queue when all tasks are completed.
For example, if the voting is complete for banning, and the user is banned, but there are still some unconfirmed "potential/suspect other accounts", the review would stay in the queue until dealt with.
This is because those other accounts might not be yet banned, and it could be that same spammy user who is banned on one account. The entire task needs to be completed.
---
Advantages
----------
1. Fast outcomes - Any active mods from any site can jump in and
action the user
2. No one mod can invoke a network wide ban, takes multiple "opinions"
3. No one mod can ban a user from a site they are not a mod on, takes
multiple mods from various sites
4. While it would be new code, it will allow certain code re-use, and
hooks into the current systems and setup (rather than entire new system)
5. Staff and Stack devs have great knowledge of review queues now, with
tried and tested things, so you could fairly quickly set this up to
what works best (rather than entire new system)
6. A users previous moderation will be stored for future reference.
The system can pull out data to put in new reviews for the same
user
7. No need for "clunky" chat to tell each other about stuff, make
discuss, and a unanimous decision is made easily and without
discussions
8. There is a historical record of spam moderation, which means new
moderators, or those not so confident (small sites) can study the
previous decisions and learn good practices. Without having to chat
to or ask other mods
9. An outcome being from multiple moderators is more likely to make a
better decision
---
More than just spam
-------------------
This will take a fair bit of work, even re-using *some* current review code and knowledge of how reviewing works best (etc).
However, once this is up and running, tweaked, and bugs ironed out, other moderation things could be fed into here.
Not being a mod, I cannot suggest anything which would be useful, but there must surely be other things would would benefit a moderator-only review queue? |
259,123 | Here's the problem, in a nutshell:
>
> *Glancy T. Pony is a mod on our mayonnaise site, and wakes up in the
> afternoon to find that her site has been littered by Miracle Whip
> astroturfers. As Glancy [cleans up the mess](https://meta.stackexchange.com/questions/259050/as-a-moderator-should-i-re-flag-spam-thats-already-flagged-or-just-delete-it/259117#259117), she notices that many
> of these spammers have accounts on multiple sites, where they've been
> dropping heathen sandwich spread everywhere.*
>
>
> *Glancy, sadly, can only
> take action on **her** site, so she spends even more of her valuable
> time rallying help in chat to get the rest of the accounts nuked. She
> feels like there **must** be some way for her actions to do more, since
> it's so blatant.*
>
>
>
I want to try to make this a reality, and I'm not talking about a site for mayonnaise (it's on-topic at Seasoned Advice). I'd like for per-site destructions of spammers to count more meaningfully when it comes to cleaning up network spam as a whole.
Here's what's blocking it:
* Mods are elected on a per-site basis, by individual communities. Are programmers willing to trust [car mechanics](http://mechanics.stackexchange.com) and [physicists](http://physics.stackexchange.com) to help keep Stack Overflow clean? (Along with the reverse)
* We've worked, quite extensively, at coming up with criteria for the system to notice and take action upon. E.g. if an *account* has more than X profiles destroyed for spam, and *all* profiles are eligible (less than 50 rep on any profile), automatically destroy them all. This works, but it turns out to be almost *as slow* as just waiting for the rest of the mods to notice in many cases. How can this be better, safely?
* While I am *certain* it would never come to pass, this sets up a system that if abused, could have some kind of awful consequences. We trust *every single one* of our moderators completely and extensively. It's just a possibility, however remote, that needs to be mentioned. What other guard rails could we put around it?
Please think about it. If you have ideas on how this could work, strong feelings on if it should or shouldn't be implemented, or just feedback in general - we'd love to hear it.
Part of my area of speciality at SE has been spam / abuse mitigation, and this keeps coming up. My response thus far has been *it's not a horrible idea, let's see if a time comes when we really need it.*
It's time to talk about it. | 2015/06/22 | [
"https://meta.stackexchange.com/questions/259123",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/50049/"
] | Blatant spam is the one universal issue that I would expect every moderator from every site to recognize. It does not need any domain knowledge or familiarity with the site to act on it.
One thing I think would be nice in general, and would avoid honest mistakes would be to actually mention the consequences of the destroy action in the dialog. Currently this dialog only mentions why the user should be destroyed, it might not be obvious to all mods that this has further consequences beyond the removal of the account and the posts.
While there are no differences in power between mods right now, I think this kind of tool could behave a bit differently based on seniority of the moderator and the amount of spam flags and user destructions the moderator has done. I'm mostly thinking about not taking the first few destructions from a new mod into account, just to avoid bigger consequences in case they simply misunderstood the tools.
I think in terms of signal, two destructions by (not completely new) moderators on two different sites should be enough to trigger the removal of all connected accounts. With the safeguard that there should be no significant real participation (upvoted posts) by those accounts.
Most spammers don't have any upvoted posts, I'd use something like the following criteria to restrict the tool:
* No more than 1-2 upvoted posts. I'd maybe even go with 0, I generally don't see upvoted spam, but I've heard it exists.
* No older, unflagged posts. If it's been here for a week and isn't removed, it probably isn't spam and the user at least not a completely obvious spammer.
These restrictions would ensure that even if the tool is triggered in error, the damage would be very limited. Those criteria are certainly exploitable by spammers, but you can always change them if that turns out to actually happen.
I'd strongly support such a tool as I think the current way of handling cross-site spammers is unnecessarily noisy. Pinging other mods in chat or CMs just to clean up some spammer accounts that might be abandoned or not is just not that efficient. | Suspend the network user for a short time (a day or so) so there is a chance to do a 'review' of the account. (Was it a single time mistake, or is there more)
Then the SE Community Managers, or other moderators (on the same site or other sites) can review the account.
If a user gets 3 or more 'delete votes' against him, BANG! Delete the account. |
259,123 | Here's the problem, in a nutshell:
>
> *Glancy T. Pony is a mod on our mayonnaise site, and wakes up in the
> afternoon to find that her site has been littered by Miracle Whip
> astroturfers. As Glancy [cleans up the mess](https://meta.stackexchange.com/questions/259050/as-a-moderator-should-i-re-flag-spam-thats-already-flagged-or-just-delete-it/259117#259117), she notices that many
> of these spammers have accounts on multiple sites, where they've been
> dropping heathen sandwich spread everywhere.*
>
>
> *Glancy, sadly, can only
> take action on **her** site, so she spends even more of her valuable
> time rallying help in chat to get the rest of the accounts nuked. She
> feels like there **must** be some way for her actions to do more, since
> it's so blatant.*
>
>
>
I want to try to make this a reality, and I'm not talking about a site for mayonnaise (it's on-topic at Seasoned Advice). I'd like for per-site destructions of spammers to count more meaningfully when it comes to cleaning up network spam as a whole.
Here's what's blocking it:
* Mods are elected on a per-site basis, by individual communities. Are programmers willing to trust [car mechanics](http://mechanics.stackexchange.com) and [physicists](http://physics.stackexchange.com) to help keep Stack Overflow clean? (Along with the reverse)
* We've worked, quite extensively, at coming up with criteria for the system to notice and take action upon. E.g. if an *account* has more than X profiles destroyed for spam, and *all* profiles are eligible (less than 50 rep on any profile), automatically destroy them all. This works, but it turns out to be almost *as slow* as just waiting for the rest of the mods to notice in many cases. How can this be better, safely?
* While I am *certain* it would never come to pass, this sets up a system that if abused, could have some kind of awful consequences. We trust *every single one* of our moderators completely and extensively. It's just a possibility, however remote, that needs to be mentioned. What other guard rails could we put around it?
Please think about it. If you have ideas on how this could work, strong feelings on if it should or shouldn't be implemented, or just feedback in general - we'd love to hear it.
Part of my area of speciality at SE has been spam / abuse mitigation, and this keeps coming up. My response thus far has been *it's not a horrible idea, let's see if a time comes when we really need it.*
It's time to talk about it. | 2015/06/22 | [
"https://meta.stackexchange.com/questions/259123",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/50049/"
] | When we get spam, it is almost invariably by users with 1 rep point whose network profiles are also at or around 1 rep. I am reasonably certain that all spammers I've deleted should have been deleted network-wide.
This would suggest that it may well be a good idea to propagate deletions across multiple sites. At least as long as those users have very low reputation. Perhaps even under 10. I would also not object to mods from other sites having such powers in the communities I represent.
However, to avoid complications and protect against human error, we could always simply raise automatic flags. For example, I can imagine a system where
1. I destroy a user choosing spam as the reason.
2. An automatic flag is raised on that user on all sites where they have a profile.
3. In the flag review page, the mods of the target site get the option to delete the user or not.
This has the advantage that it greatly facilitates communication between different sites and *bona fide* spammers will be destroyed more efficiently while at the same time not allowing a mistake I might make to affect other sites. It sounds like the best of both worlds. | I suggest a *networked moderator review queue*, only accessible by moderators.
(Bear with me..it has good potential)
**TL;DR;**
Have a new review queue accessible by moderators only, which would be shown to all moderators across all sites.
When a user is marked as spammy, the system would raise a flag, add a new review in the moderator-only review queue, and then all moderators on all sites could see it and vote on what action to take (or add to a current review if user is already being reviewed).
Spam is not really site specific, so is ok for mods to vote on spam related things from other sites, imo.
---
Responses to your criteria (Tim)
--------------------------------
>
> Are programmers willing to trust car mechanics and physicists to help
> keep Stack Overflow clean? (Along with the reverse)
>
>
>
I don't think "spam" is site specific, however a review queue helps with this by requiring more than one vote to action something.
>
> if an account has more than X profiles destroyed for spam, and all
> profiles are eligible (less than 50 rep on any profile), automatically
> destroy them all.
>
>
>
This can easily be worked into a moderator review queue, and an auto action taken once vote thresholds are reached.
>
> While I am certain it would never come to pass, this sets up a system
> that if abused, could have some kind of awful consequences. We trust
> every single one of our moderators completely and extensively. It's
> just a possibility, however remote, that needs to be mentioned. What
> other guard rails could we put around it?
>
>
>
A review queue with multiple votes caters for this too.
And moderator decisions can be seen by all other mods, so anyone can nudge another mod and advise on their not-so-perfect decisions - "Hey, FYI, that was obvious spam because XYZ".
---
The basic setup
---------------
Again, this is all only accessible by moderators, and not even readable by non-mods.
Every Stack site would have a new "moderator review queue".
When a user is moderated for spammy actions by a mod on one site, the system raises a flag, and details of the actions would go into the moderator review queue on *all* sites.
If a flag has already been raised for that user, then there would already be a review in the queue, in that case this new flag would just be added to the current review of that user as additional data.
This would allow all mods on all sites to see current spam actions being made on other sites, by other mods. Moderators can then check the user account on *their* site and perform an action in that same (global) review.
It allows mods from any/all sites to cast votes as to how best to deal with this user, and not just based on their own site and own findings.
This makes it a fast process, and more than a single person making a decision.
When there's a review needing attention (i.e. without an outcome) there would be a notification on the top-bar (*like* the "suggested edits notification").
This would cater for the *fast action* requirement, especially as any mod on any site can cast a review vote, so an outcome would come quickly.
The review queue should be updated from various places where a mod deals with a spammy user.
e.g. A mod flags a user as spammy in an question or answer, the system adds it to the review (or a new review opened if none exists).
This stops mods having to manually raise or update a review - it's all just auto fed in based on their actions, and other mods from all sites can then review it.
The review
----------
Various useful data of the user would be in the review, such as:
* Links to all spam posts flagged by all mods/sites for the user
* Other "potential/suspected" accounts that user might have
* Previous moderation actions against the user
* A link in the review to the user's profile - but the link would be
different for each mod, and link to the site they are a mod for.
Allowing mods to quickly check if that user is spamming on *their*
site (instead of having to search for that user etc).
This allows a single place for all data to be studied about that user - instead of having to check other sites, chat to other mods, write stuff down, etc.
Review actions
--------------
Stack would set this up, and it's going to require more in-depth functions and consideration than I care to delve into here.
But for an example to illustrate how my idea would pan out:
1. Mod on *SiteA* flags spam from a user
2. System places data in the moderator review queue, all mods
on all sites can see it and are notified on the top-bar
3. Mods on *SiteB* see the user has also spammed on their site
(*SiteB*), they flag it and so it gets added to the review for that
user (same review). This updates the review to show the user has also
spammed on *SiteB* for all other mods on all other sites to see. A
picture is building up
4. Other actions can be performed, such as any mods voting to ban user,
suspend user, block account on one, some, or all sites, etc.
Or, point 3 might be non-existent, and user is only spamming on one site, so mods decide to vote to ban/suspend the user on that one site only.
The outcome will be determined by usual review queue criteria:
`X votes by mods for Z reason`
For example 5 mods vote "ban user site wide" and so the action is completed.
---
Complex review
--------------
For it to be useful, the moderator review won't be exactly like our current normal user review queues, where simply one action per user only, and when threshold met review is completed.
A moderator review should show various data about a flagged user, so a more concise and accurate decision can be made.
Such as the posts and sites the user has spammed on, and any suspected other accounts the user has.
So, while data is being gathered, new things come to light, so votes could change.
(These are moderators, so I expect that they won't just stupidly change votes for no good reason... or at least shouldn't.)
For example, changing one's vote:
1. UserA has a review up against them for spamming on *one* site
2. Mods start to vote "ban user on that one site"
3. A mod from another site flags spam on their site, which is fed into
the review. Now it shows the user is spamming on *two* sites
4. Mods can then change their vote from "ban on one site" to "ban on
two sites..or network wide" because more data is found
If votes are cast and review complete, and more data comes to light, mods want to change the outcome (re-vote).
There are two ways to tackle this. When a mod flags the newly found spam (from the same user but not previously flagged) the new data will either:
1. Resurrect the old review and reset the votes, so mods can vote
including with the new data
2. Or a new review can be made, with a link to the previous review so
previous data can be seen
There are pros and cons to both. I'm sure Stack would resolve this easily, perhaps with an option to re-open an old review if a user is seen to be "up to old tricks" etc.
---
I also suggest that different data within the review can be voted on separately.
This is because it's not going to be black and white "user has X spam posts - what should we do".
There will be other info and data to take into consideration.
For example:
1. Mods suspect the user of having multiple accounts, so the review
shows "potential/suspected other accounts for this user" (and a list
of the accounts)
2. Mods can investigate and gather data to confirm if the user has
multiple accounts
3. A mod finds one of those accounts *is* the same user, so marks the
"potential other account" as "confirmed" in the review queue
4. Other mods can see this, and vote accordingly, or change their
previous vote cast
This too will change voting, because a user with multiple bad accounts should perhaps be banned completely, whereas a user with one account and spammed on one site, might be simply "not knowing the rules" (etc).
---
Review done
-----------
The review will be done and moved out of the queue when all tasks are completed.
For example, if the voting is complete for banning, and the user is banned, but there are still some unconfirmed "potential/suspect other accounts", the review would stay in the queue until dealt with.
This is because those other accounts might not be yet banned, and it could be that same spammy user who is banned on one account. The entire task needs to be completed.
---
Advantages
----------
1. Fast outcomes - Any active mods from any site can jump in and
action the user
2. No one mod can invoke a network wide ban, takes multiple "opinions"
3. No one mod can ban a user from a site they are not a mod on, takes
multiple mods from various sites
4. While it would be new code, it will allow certain code re-use, and
hooks into the current systems and setup (rather than entire new system)
5. Staff and Stack devs have great knowledge of review queues now, with
tried and tested things, so you could fairly quickly set this up to
what works best (rather than entire new system)
6. A users previous moderation will be stored for future reference.
The system can pull out data to put in new reviews for the same
user
7. No need for "clunky" chat to tell each other about stuff, make
discuss, and a unanimous decision is made easily and without
discussions
8. There is a historical record of spam moderation, which means new
moderators, or those not so confident (small sites) can study the
previous decisions and learn good practices. Without having to chat
to or ask other mods
9. An outcome being from multiple moderators is more likely to make a
better decision
---
More than just spam
-------------------
This will take a fair bit of work, even re-using *some* current review code and knowledge of how reviewing works best (etc).
However, once this is up and running, tweaked, and bugs ironed out, other moderation things could be fed into here.
Not being a mod, I cannot suggest anything which would be useful, but there must surely be other things would would benefit a moderator-only review queue? |
259,123 | Here's the problem, in a nutshell:
>
> *Glancy T. Pony is a mod on our mayonnaise site, and wakes up in the
> afternoon to find that her site has been littered by Miracle Whip
> astroturfers. As Glancy [cleans up the mess](https://meta.stackexchange.com/questions/259050/as-a-moderator-should-i-re-flag-spam-thats-already-flagged-or-just-delete-it/259117#259117), she notices that many
> of these spammers have accounts on multiple sites, where they've been
> dropping heathen sandwich spread everywhere.*
>
>
> *Glancy, sadly, can only
> take action on **her** site, so she spends even more of her valuable
> time rallying help in chat to get the rest of the accounts nuked. She
> feels like there **must** be some way for her actions to do more, since
> it's so blatant.*
>
>
>
I want to try to make this a reality, and I'm not talking about a site for mayonnaise (it's on-topic at Seasoned Advice). I'd like for per-site destructions of spammers to count more meaningfully when it comes to cleaning up network spam as a whole.
Here's what's blocking it:
* Mods are elected on a per-site basis, by individual communities. Are programmers willing to trust [car mechanics](http://mechanics.stackexchange.com) and [physicists](http://physics.stackexchange.com) to help keep Stack Overflow clean? (Along with the reverse)
* We've worked, quite extensively, at coming up with criteria for the system to notice and take action upon. E.g. if an *account* has more than X profiles destroyed for spam, and *all* profiles are eligible (less than 50 rep on any profile), automatically destroy them all. This works, but it turns out to be almost *as slow* as just waiting for the rest of the mods to notice in many cases. How can this be better, safely?
* While I am *certain* it would never come to pass, this sets up a system that if abused, could have some kind of awful consequences. We trust *every single one* of our moderators completely and extensively. It's just a possibility, however remote, that needs to be mentioned. What other guard rails could we put around it?
Please think about it. If you have ideas on how this could work, strong feelings on if it should or shouldn't be implemented, or just feedback in general - we'd love to hear it.
Part of my area of speciality at SE has been spam / abuse mitigation, and this keeps coming up. My response thus far has been *it's not a horrible idea, let's see if a time comes when we really need it.*
It's time to talk about it. | 2015/06/22 | [
"https://meta.stackexchange.com/questions/259123",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/50049/"
] | If I as a mod on Stack Overflow destroy an account for spam, you could immediately put a brake onto any linked accounts to require either more "I am human" validation or just hobble to one post per week and then flag up that account to the site moderators as one that's posted spam elsewhere. You could also feed the spam posts into the anti-spam program as more data (if you're not already doing that).
Then when the other moderators come online they'll see these flags and be able to act and hopefully the hobbling etc. will prevent too much spam being spewed onto the system in the meantime.
If they have accounts destroyed on **multiple** sites then intensify the hobbling or if enough accounts (more than half) are destroyed then automatically destroy the rest. | Suspend the network user for a short time (a day or so) so there is a chance to do a 'review' of the account. (Was it a single time mistake, or is there more)
Then the SE Community Managers, or other moderators (on the same site or other sites) can review the account.
If a user gets 3 or more 'delete votes' against him, BANG! Delete the account. |
259,123 | Here's the problem, in a nutshell:
>
> *Glancy T. Pony is a mod on our mayonnaise site, and wakes up in the
> afternoon to find that her site has been littered by Miracle Whip
> astroturfers. As Glancy [cleans up the mess](https://meta.stackexchange.com/questions/259050/as-a-moderator-should-i-re-flag-spam-thats-already-flagged-or-just-delete-it/259117#259117), she notices that many
> of these spammers have accounts on multiple sites, where they've been
> dropping heathen sandwich spread everywhere.*
>
>
> *Glancy, sadly, can only
> take action on **her** site, so she spends even more of her valuable
> time rallying help in chat to get the rest of the accounts nuked. She
> feels like there **must** be some way for her actions to do more, since
> it's so blatant.*
>
>
>
I want to try to make this a reality, and I'm not talking about a site for mayonnaise (it's on-topic at Seasoned Advice). I'd like for per-site destructions of spammers to count more meaningfully when it comes to cleaning up network spam as a whole.
Here's what's blocking it:
* Mods are elected on a per-site basis, by individual communities. Are programmers willing to trust [car mechanics](http://mechanics.stackexchange.com) and [physicists](http://physics.stackexchange.com) to help keep Stack Overflow clean? (Along with the reverse)
* We've worked, quite extensively, at coming up with criteria for the system to notice and take action upon. E.g. if an *account* has more than X profiles destroyed for spam, and *all* profiles are eligible (less than 50 rep on any profile), automatically destroy them all. This works, but it turns out to be almost *as slow* as just waiting for the rest of the mods to notice in many cases. How can this be better, safely?
* While I am *certain* it would never come to pass, this sets up a system that if abused, could have some kind of awful consequences. We trust *every single one* of our moderators completely and extensively. It's just a possibility, however remote, that needs to be mentioned. What other guard rails could we put around it?
Please think about it. If you have ideas on how this could work, strong feelings on if it should or shouldn't be implemented, or just feedback in general - we'd love to hear it.
Part of my area of speciality at SE has been spam / abuse mitigation, and this keeps coming up. My response thus far has been *it's not a horrible idea, let's see if a time comes when we really need it.*
It's time to talk about it. | 2015/06/22 | [
"https://meta.stackexchange.com/questions/259123",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/50049/"
] | When we get spam, it is almost invariably by users with 1 rep point whose network profiles are also at or around 1 rep. I am reasonably certain that all spammers I've deleted should have been deleted network-wide.
This would suggest that it may well be a good idea to propagate deletions across multiple sites. At least as long as those users have very low reputation. Perhaps even under 10. I would also not object to mods from other sites having such powers in the communities I represent.
However, to avoid complications and protect against human error, we could always simply raise automatic flags. For example, I can imagine a system where
1. I destroy a user choosing spam as the reason.
2. An automatic flag is raised on that user on all sites where they have a profile.
3. In the flag review page, the mods of the target site get the option to delete the user or not.
This has the advantage that it greatly facilitates communication between different sites and *bona fide* spammers will be destroyed more efficiently while at the same time not allowing a mistake I might make to affect other sites. It sounds like the best of both worlds. | Suspend the network user for a short time (a day or so) so there is a chance to do a 'review' of the account. (Was it a single time mistake, or is there more)
Then the SE Community Managers, or other moderators (on the same site or other sites) can review the account.
If a user gets 3 or more 'delete votes' against him, BANG! Delete the account. |
25,050,894 | I have file of type unicode, I need to get the check the file if `^` is being used as a delimiter or not using batch script
Here is example of the file content:
```
Case Id^Subcase Id^Cr Date Cust^Case Title^Contact First Name^Contact Last Name^Customer Phone Number^Contact E Mail
```
The approach i tried using is to fetch the first line of the file, store to a variable and then do a findstr on the string for `^` character it seems to be not working here.
Here is the code snippet that i tried:
```
set /p var1= < C:\corvallis\diversionpl.csv
echo %var1% |findstr /lic:"^" >nul && set "isFormat=FOUND" || set "isFormat=NOT FOUND"
echo %isFormat%
```
Are there any options from the above approach that has been tried out? | 2014/07/31 | [
"https://Stackoverflow.com/questions/25050894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493117/"
] | You can try
```
@echo off
setlocal enableextensions disabledelayedexpansion
set "carets="
for /f %%a in (
'findstr /n /r /c:"^" data.txt ^| findstr /b /c:"1:" ^| find /c "^"'
) do set "carets=%%a"
echo %carets%
if "%carets%"=="7" ( echo FOUND ) else ( echo NOT FOUND )
```
How does it work? The first `findstr` just reads all the file, numbering the lines. The second `findstr` filters the data to only retrieve the first line. Until here, all the data flowing along the pipe is unicode. Now, `find /c` is used to converts this data to ansi, the nulls between characters into line feeds and count the number of lines containing `^`, that is, the number of separators (if found) inside the first line
But this will only work under the assumption that the file is unicode.
Why the `for` or `set /p` approach do not work? If the file is unicode (yes, relaxed usage of the term), there are two bytes per character, the "normal" one and a 0x00 (null) char. And in batch files, variables can not hold nulls. You can try to read the line, but the variable will not hold the readed data.
**edited** for a more concise way of doing it both in unicode or ansi file (this time just testing the presence of the `^` in the first line)
```
(type data.txt 2>nul|(set /p "data="&(set data|find "^">nul)))&& echo found || echo not found
```
or
```
(type data.txt 2>nul|(set /p "data="&(set data|find "^">nul)))
if errorlevel 1 (
echo not found
) else (
echo found
)
```
And yes, it uses `set /p`, because the `type` command will "convert" the file from unicode. | A for loop can process contents of a file and do lots of manipulations to it ... I'm not sure if this algorithm would work but it should atleast get you somewhere...
```
@echo off
For /f "tokens=*" %%a in (filename.extension) do (
Echo "%%a" ¦ find "^^"
)
Pause
``` |
25,050,894 | I have file of type unicode, I need to get the check the file if `^` is being used as a delimiter or not using batch script
Here is example of the file content:
```
Case Id^Subcase Id^Cr Date Cust^Case Title^Contact First Name^Contact Last Name^Customer Phone Number^Contact E Mail
```
The approach i tried using is to fetch the first line of the file, store to a variable and then do a findstr on the string for `^` character it seems to be not working here.
Here is the code snippet that i tried:
```
set /p var1= < C:\corvallis\diversionpl.csv
echo %var1% |findstr /lic:"^" >nul && set "isFormat=FOUND" || set "isFormat=NOT FOUND"
echo %isFormat%
```
Are there any options from the above approach that has been tried out? | 2014/07/31 | [
"https://Stackoverflow.com/questions/25050894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493117/"
] | You can try
```
@echo off
setlocal enableextensions disabledelayedexpansion
set "carets="
for /f %%a in (
'findstr /n /r /c:"^" data.txt ^| findstr /b /c:"1:" ^| find /c "^"'
) do set "carets=%%a"
echo %carets%
if "%carets%"=="7" ( echo FOUND ) else ( echo NOT FOUND )
```
How does it work? The first `findstr` just reads all the file, numbering the lines. The second `findstr` filters the data to only retrieve the first line. Until here, all the data flowing along the pipe is unicode. Now, `find /c` is used to converts this data to ansi, the nulls between characters into line feeds and count the number of lines containing `^`, that is, the number of separators (if found) inside the first line
But this will only work under the assumption that the file is unicode.
Why the `for` or `set /p` approach do not work? If the file is unicode (yes, relaxed usage of the term), there are two bytes per character, the "normal" one and a 0x00 (null) char. And in batch files, variables can not hold nulls. You can try to read the line, but the variable will not hold the readed data.
**edited** for a more concise way of doing it both in unicode or ansi file (this time just testing the presence of the `^` in the first line)
```
(type data.txt 2>nul|(set /p "data="&(set data|find "^">nul)))&& echo found || echo not found
```
or
```
(type data.txt 2>nul|(set /p "data="&(set data|find "^">nul)))
if errorlevel 1 (
echo not found
) else (
echo found
)
```
And yes, it uses `set /p`, because the `type` command will "convert" the file from unicode. | Try this ..
```
@echo off
Set string=<%~1
Echo %string% ¦ find "^^"
Pause
```
Drag the file onto the batch file so it becomes the first argument and set will declare an instance variable of it .... Long shot .. hope it helps |
25,050,894 | I have file of type unicode, I need to get the check the file if `^` is being used as a delimiter or not using batch script
Here is example of the file content:
```
Case Id^Subcase Id^Cr Date Cust^Case Title^Contact First Name^Contact Last Name^Customer Phone Number^Contact E Mail
```
The approach i tried using is to fetch the first line of the file, store to a variable and then do a findstr on the string for `^` character it seems to be not working here.
Here is the code snippet that i tried:
```
set /p var1= < C:\corvallis\diversionpl.csv
echo %var1% |findstr /lic:"^" >nul && set "isFormat=FOUND" || set "isFormat=NOT FOUND"
echo %isFormat%
```
Are there any options from the above approach that has been tried out? | 2014/07/31 | [
"https://Stackoverflow.com/questions/25050894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3493117/"
] | You can try
```
@echo off
setlocal enableextensions disabledelayedexpansion
set "carets="
for /f %%a in (
'findstr /n /r /c:"^" data.txt ^| findstr /b /c:"1:" ^| find /c "^"'
) do set "carets=%%a"
echo %carets%
if "%carets%"=="7" ( echo FOUND ) else ( echo NOT FOUND )
```
How does it work? The first `findstr` just reads all the file, numbering the lines. The second `findstr` filters the data to only retrieve the first line. Until here, all the data flowing along the pipe is unicode. Now, `find /c` is used to converts this data to ansi, the nulls between characters into line feeds and count the number of lines containing `^`, that is, the number of separators (if found) inside the first line
But this will only work under the assumption that the file is unicode.
Why the `for` or `set /p` approach do not work? If the file is unicode (yes, relaxed usage of the term), there are two bytes per character, the "normal" one and a 0x00 (null) char. And in batch files, variables can not hold nulls. You can try to read the line, but the variable will not hold the readed data.
**edited** for a more concise way of doing it both in unicode or ansi file (this time just testing the presence of the `^` in the first line)
```
(type data.txt 2>nul|(set /p "data="&(set data|find "^">nul)))&& echo found || echo not found
```
or
```
(type data.txt 2>nul|(set /p "data="&(set data|find "^">nul)))
if errorlevel 1 (
echo not found
) else (
echo found
)
```
And yes, it uses `set /p`, because the `type` command will "convert" the file from unicode. | Use `awk` with the field separator set to `^` which you will need to escape.
```
awk -F \^ '{ print NF; n+=1 }; END { print n }' temp.txt
```
Will print the number of fields on each line followed by the number of lines - I am sure that you could find a better usage but it gives you a starting point. |
27,574,596 | I am writing a document reading application using Node-Webkit. A document can be hundreds of pages long and the interface allows opening the document to a specific chapter. Once the initial chapter is displayed, I want to load the rest of the book asynchronously. Since I don't know what direction the reader will scroll, my strategy is to alternately load chapters before and then after the initial chapter:
load chapter x -> load chapter x-1 -> load chapter x+1 -> load x-2 -> load x+2 ...
I am displaying the book in a containing div element with each chapter being a div within the container. I'm using jquery .before() and .after() to insert each chapter as it is fetched.
My problem is that the browser automatically scrolls up when I add chapters earlier in the book. So if I start with chapter 10, the browser scrolls up when I add chapter 9 and again with chapter 8 and so forth.
One (unsatisfactory) solution to the problem is to make an anchor tag for each chapter and store the id of the first chapter loaded. Then after each chapter is fetched, runing the code:
```
window.location.href = #originalChapter
```
keeps the initial chapter in the browser viewport. Of course the problem with that is that the reader cannot scroll while the rest of the book is being loaded.
Ideally, I would like to disable scrolling, load a chapter and then re-enable until the next chapter is fetched. I'm so far unable to figure out how to do that. | 2014/12/19 | [
"https://Stackoverflow.com/questions/27574596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17870/"
] | The simple solution in my mind would be to not have the elements in the DOM until they are loaded. The user won't be able to scroll because there won't be content to scroll to. Then, it's just a matter of preserving the viewport when the elements are added.
Take the initial position of your scroll container and the height of the overflow container:
```
var scrollTop = $scroll.scrollTop(),
height = $container.height();
```
and use them to preserve the viewport when you `prepend` new elements. You don't have to do anything when you're doing the `append` operation.
```
var newHeight = $container.height(),
newScrollTop = scrollTop + newHeight - height;
$scroll.scrollTop(newScrollTop);
```
Here's a quick example: <http://jsfiddle.net/Wexcode/tfszaocz/> | If you're updating the DOM from the click handler of an anchor (`<a/>`) tag, make sure you return false from the callback function. |
87,239 | Suppose we have a singly connected but not necessarily convex polygon. Something like `shape = CountryData["Chad", "Coordinates"]`.
Is there a simple way to implement an approximate [dilation](https://en.wikipedia.org/wiki/Dilation_(morphology)) for this shape, and obtain the result as vector data (lists of coordinates) just like the input?
Here's what dilation does to images:
```
img = ImagePad[ColorNegate@Image@Graphics[Polygon[shape]], 30];
ImageCompose[Dilation[img, DiskMatrix[30]], {img, .5}]
```

What I need is the outline of the gray area, but as vector (not bitmap) data.
One way is to rasterize, dilate the image, then vectorize the outline again. This seems complicated, especially since I need to preserve the original coordinate system.
Is there a better way?
The result will be used for visualization purposes, so it need not be perfect. Approximations are okay. | 2015/06/30 | [
"https://mathematica.stackexchange.com/questions/87239",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/12/"
] | From 2016 and Version 11.0 we can use `ImageMesh`.
```
img = ImagePad[ColorNegate@Image@Graphics[Polygon[shape]], 30];
imgD = Dilation[img, DiskMatrix[30]];
mesh0 = ImageMesh@img; meshD = ImageMesh@imgD;
Graphics[{Green,
Arrow[Flatten[pts0 = MeshPrimitives[mesh0, 1][[All, 1]], 1]], Red,
Arrow@Flatten[ptsD = MeshPrimitives[meshD, 1][[All, 1]], 1]}]
```
[](https://i.stack.imgur.com/NKjai.png) | For *visualization* purposes only I propose a simple and robust approach using a thick boundary line:
```
shape = CountryData["Chad", "Coordinates"];
r = 2;
xmin = Min[shape[[1, ;; , 1]]] - r;
xmax = Max[shape[[1, ;; , 1]]] + r;
ymin = Min[shape[[1, ;; , 2]]] - r;
ymax = Max[shape[[1, ;; , 2]]] + r;
Graphics[{{FaceForm[Blue],
EdgeForm[{JoinForm["Round"], Thickness[2 r/(xmax - xmin)], Blue}],
Polygon[shape]},
{Red, Polygon[shape]},
Circle[shape[[1, 1]], r]
}, PlotRange -> {{xmin, xmax}, {ymin, ymax}}, Axes -> True]
```

There are two drawbacks:
* The dilated polygon is not given by an explicit set of points
* We should specify the plot range to obtain the thickness in terms of original coordinates. The circle is drawn to check the thickness. |
87,239 | Suppose we have a singly connected but not necessarily convex polygon. Something like `shape = CountryData["Chad", "Coordinates"]`.
Is there a simple way to implement an approximate [dilation](https://en.wikipedia.org/wiki/Dilation_(morphology)) for this shape, and obtain the result as vector data (lists of coordinates) just like the input?
Here's what dilation does to images:
```
img = ImagePad[ColorNegate@Image@Graphics[Polygon[shape]], 30];
ImageCompose[Dilation[img, DiskMatrix[30]], {img, .5}]
```

What I need is the outline of the gray area, but as vector (not bitmap) data.
One way is to rasterize, dilate the image, then vectorize the outline again. This seems complicated, especially since I need to preserve the original coordinate system.
Is there a better way?
The result will be used for visualization purposes, so it need not be perfect. Approximations are okay. | 2015/06/30 | [
"https://mathematica.stackexchange.com/questions/87239",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/12/"
] | ```
shape = First @ CountryData["Chad", "Coordinates"];
poly = Polygon @ shape;
srd = SignedRegionDistance @ poly;
ranges = Flatten /@ Transpose[{{x, y},
CoordinateBounds[ScalingTransform[1.4 {1, 1}, Mean @ shape] @ shape]}];
ContourPlot[srd[{x, y}], ranges[[1]], ranges[[2]],
Contours -> Thread[{{-1, -.5, -.25, .25, .5, 1},
ColorData["Rainbow"] /@ Subdivide[5]}],
ContourShading -> False,
Frame -> False, ImageSize -> 500,
Prolog -> {EdgeForm[Black], FaceForm[LightBlue], poly},
PlotLegends -> Placed[LineLegend[Automatic,
LegendLabel -> SignedRegionDistance], Top]]
```
[](https://i.stack.imgur.com/wliub.png) | For *visualization* purposes only I propose a simple and robust approach using a thick boundary line:
```
shape = CountryData["Chad", "Coordinates"];
r = 2;
xmin = Min[shape[[1, ;; , 1]]] - r;
xmax = Max[shape[[1, ;; , 1]]] + r;
ymin = Min[shape[[1, ;; , 2]]] - r;
ymax = Max[shape[[1, ;; , 2]]] + r;
Graphics[{{FaceForm[Blue],
EdgeForm[{JoinForm["Round"], Thickness[2 r/(xmax - xmin)], Blue}],
Polygon[shape]},
{Red, Polygon[shape]},
Circle[shape[[1, 1]], r]
}, PlotRange -> {{xmin, xmax}, {ymin, ymax}}, Axes -> True]
```

There are two drawbacks:
* The dilated polygon is not given by an explicit set of points
* We should specify the plot range to obtain the thickness in terms of original coordinates. The circle is drawn to check the thickness. |
478,065 | I'm building a PHP application using CodeIgniter. It is similar to `Let Me Google That For You` where you write a sentence into a text input box, click submit, and you are taken to a URL that displays the result. I wanted the URL to be human-editable, and relatively simple. I've gotten around the CodeIgniter URL routing, so right now my URLs can look something like this:
```
http://website.com/?q=this+is+a+normal+url
```
The problem right now is when the sentence contains a special character like a question mark, or a backslash. Both of these mess with my current `.htaccess` rewrite rules, and it happens even when the character is encoded.
```
http://website.com/?q=this+is+a+normal+url? OR
http://website.com/?q=this+is+a+normal+url%3F
```
What does work is double-encoding. For example, if I take the question mark, and encode it to `%253F` (where the ? is encoded to %3F and the % sign is encoded to %25). This url works properly.
```
http://website.com/?q=this+is+a+normal+url%253F
```
Does anyone have an idea of what I can do here? Is there a clever way I could double encode the input? Can I write a `.htaccess` rewrite rule to get around this? I'm at a loss here. Here are the rewrite rules I'm currently using for everyone.
```
RewriteEngine on
RewriteCond %{QUERY_STRING} ^q=(.*)$
RewriteRule ^(.*)$ /index.php/app/create/%{QUERY_STRING}? [L]
```
**Note**: The way CodeIgniter works is they have a `index/application/function/parameter` URL setup. I'm feeding the function the full query string right now. | 2009/01/25 | [
"https://Stackoverflow.com/questions/478065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If your’re using Apache 2.2 and later, you can use the [B flag](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriteflags) to force the backreference to be escaped:
```
RewriteCond %{QUERY_STRING} ^q=.*
RewriteRule ^ /index.php/app/create/%0? [L,B]
``` | I usually do human readable urls like this
```
$humanReadableUrl= implode("_",preg_split('/\W+/', trim($input), -1, PREG_SPLIT_NO_EMPTY));
```
It will remove any non-word characters and will add underscores beetween words |
56,382,117 | Here is my question - is there a way I can edit my code so that the RequestedDateTime1 time from query 1 remains aligned with the its corresponding EventDisplay1 from query 1?
Below is how I arrived with this question.
I have the following code:
```
SELECT [Financial Number], [Depart Date & Time],
(Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
[Event 1 Display],
[Event 1 Personnel - Completed],
[Requested 1 Date & Time],
[Completed 1 Date & Time],
ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RB,
ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Requested 1 Date & Time]) AS RN,
ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Completed 1 Date & Time]) AS RM,
ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Event 1 Personnel - Completed]) AS RO,
ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Arrival Date & Time]) as AD,
ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Depart Date & Time]) as DT
FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED
```
Which produces results that look like the following (this is abbreviated for space reasons):
```
[Financial Number] [Depart Date & Time] .. EventDisplay1 RequestedDateTime1
1 2018-01-01 10:19:11 EP Exam 2018-01-01 11:19
1 2018-01-01 10:19:11 Discharge 2018-01-01 12:20
2 2018-01-01 13:49:11 EP Exam 2018-01-01 12:20
```
I then add a query to the data query 1 produces:
```
Select [Financial Number],
MIN(CASE DT WHEN 1 THEN [Depart Date & Time] END) AS [Depart Date &
Time1],
MIN(CASE RB WHEN 1 THEN [Event 1 Display] END) AS EventDisplay1,
MIN(CASE RB WHEN 2 THEN [Event 1 Display] END) AS EventDisplay2,
MIN(CASE RB WHEN 3 THEN [Event 1 Display] END) AS EventDisplay3,
MIN(CASE RO WHEN 1 THEN [Event 1 Personnel - Completed] END) AS
EventPersonnelCompleted1,
MIN(CASE RO WHEN 2 THEN [Event 1 Personnel - Completed] END) AS
EventPersonnelCompleted2,
MIN(CASE RO WHEN 3 THEN [Event 1 Personnel - Completed] END) AS
EventPersonnelCompleted3,
MIN(CASE RN WHEN 1 THEN [Requested 1 Date & Time] END) AS RequestedDateTime1,
MIN(CASE RN WHEN 2 THEN [Requested 1 Date & Time] END) AS RequestedDateTime2,
MIN(CASE RN WHEN 3 THEN [Requested 1 Date & Time] END) AS RequestedDateTime3,
MIN(CASE RM WHEN 1 THEN [Completed 1 Date & Time] END) AS CompletedDateTime1,
MIN(CASE RM WHEN 2 THEN [Completed 1 Date & Time] END) AS CompletedDateTime2,
MIN(CASE RM WHEN 3 THEN [Completed 1 Date & Time] END) AS CompletedDateTime3,
FROM
(
SELECT [Financial Number], [Depart Date & Time],
(Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
[Event 1 Display],
[Event 1 Personnel - Completed],
[Requested 1 Date & Time],
[Completed 1 Date & Time],
ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RB,
ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Requested 1 Date & Time]) AS RN,
ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Completed 1 Date & Time]) AS RM,
ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Event 1 Personnel - Completed]) AS RO,
ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Arrival Date & Time]) as AD,
ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Depart Date & Time]) as DT
FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED
)sub group by [Financial Number]
```
This query produces results that concatenate each row so each row is one unique Financial Number; however in doing so it messes up the alignment of the RequestedDateTime1 variable with the EventDisplay1 variable. For example, using the sample data above, the RequestedDateTime1 of 2018-01-01 12:20, which was aligned with DISCHARGE is now aligned with EP EXAM. I believe this is because the code orders the newly created EventDisplay1, EventDisplay2, EventDisplay3 variables in alphabetical order.
Example Results which are incorrect because the Discharge RequestedDateTime1 is aligned with the EP RequestedDateTime1:
```
[Financial Number] [Depart Date & Time] EventDisplay1 EventDisplay2 RequestedDateTime1 RequestedDateTime2
1 2018-01-01 10:19:11 Discharge EP Exam 2018-01-01 11:19 2018-01-01 12:20
```
Long story short, is there a way I can edit my code so that the RequestedDateTime1 time from query 1 remains aligned with the its corresponding EventDisplay1 from query 1?
Desired Results:
```
[Financial Number] [Depart Date & Time] EventDisplay1 EventDisplay2 RequestedDateTime1 RequestedDateTime2
1 2018-01-01 10:19:11 EP Exam Discharge 2018-01-01 11:19 2018-01-01 12:20
``` | 2019/05/30 | [
"https://Stackoverflow.com/questions/56382117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10687615/"
] | In WebChat v4 you can add data to any outgoing activity's channel data through a custom store middleware; however, this approach does not work with the embedded iFrame. You have to either use a CDN or React.
For more details, take at the [Send Backchannel Welcome Event](https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/04.api/a.welcome-event) Web Chat sample and this [StackOverflow Question](https://stackoverflow.com/questions/56294722/how-can-i-send-some-initial-data-to-the-bot-before-the-user-start-chatting-with).
### Custom store without arrow functions
```js
function(ref) {
const dispatch = ref.dispatch;
return function (next) {
return function(action) {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: { language: window.navigator.language }
}
});
return next(action);
}
}
}
``` | Unfortunately, you can't currently send any hidden information through the Web Chat channel.
What you can do is use the `DirectLine` channel along with the [WebChat web control](https://github.com/microsoft/BotFramework-WebChat). Then you can pass arbitrary data like your name and ticket id in the channel data object like is described in this [sign-on experiences example](https://blog.botframework.com/2018/08/28/sign-in-experiences/). Here they are sending an authentication token, but you can put whatever you want in `channeldata`. You will need to parse it out in your bot, but it will be available. This is quite a bit more involved than the WebChat channel, but there isn't currently another way to do it. |
8,959,116 | I had this solution working happily and i added this attribute:
```
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
public class metadata : Attribute
{
string mid;
string mdescription;
Dictionary<string, string> mdata;
public string id
{
get
{
return mid;
}
}
public string description
{
get
{
return mdescription;
}
}
public Dictionary<string, string> data
{
get
{
return mdata;
}
}
public metadata(string thisid, string thisdescription, params KeyValuePair<string, string>[] thisdataarray)
{
mid = thisid;
mdescription = thisdescription;
mdata = new Dictionary<string, string>();
if (thisdataarray != null)
{
foreach (KeyValuePair<string, string> thisvaluepair in thisdataarray)
{
mdata.Add(thisvaluepair.Key, thisvaluepair.Value);
}
}
}
}
```
I added a few declarations of this attribute, all [metadata(null, null)] with no errors. Somehow, when I compile, for each [metadata(null, null)] an "error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type" occurs, however with no line or column or file, only the project. What went wrong? Thanks. | 2012/01/22 | [
"https://Stackoverflow.com/questions/8959116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/996992/"
] | The problem is that KeyValuePair is not supported as attribute parameter type.
According to the [C# Language specification](http://msdn.microsoft.com/en-us/library/aa664615%28v=vs.71%29.aspx):
The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:
* One of the following types: bool, byte, char, double, float, int,
long, sbyte, short, string, uint, ulong, ushort.
* The type object.
* The type System.Type.
* An enum type, provided it has public accessibility and the types in
which it is nested (if any) also have public accessibility.
* Single-dimensional arrays of the above types.
As a workaround you can pass an array of strings where the odd members are keys and even members are values. Then inside the attribute constructor you can create your Dictionary. | The way you declared the array is suspicious, I don't think you need the params keyword. I don't think you want 0 or more keyvaluepair arrays, I think you are looking for a single array with 0 or more entries. Remove the params keyword, and set the default value of thisdataarray to null. |
10,474 | How I can copy my `public` schema into the same database with full table structure, data, functions, fk, pk and etc.
My version of Postgres is 8.4
P.S. I need to copy **schema** NOT database | 2012/01/10 | [
"https://dba.stackexchange.com/questions/10474",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/5728/"
] | There's no simple way to do this in pg\_dump/pg\_restore itself. You could try the following if you are able to remove the database temporarily.
1. Take a dump of your public schema using [pg\_dump](http://www.postgresql.org/docs/8.4/static/app-pgdump.html)
2. run "ALTER SCHEMA public RENAME TO public\_copy"
3. Restore your dump of your public schema from step 1 using [pg\_restore](http://www.postgresql.org/docs/8.4/static/app-pgrestore.html) | You could use
```
CREATE DATABASE new_db TEMPLATE = old_db;
```
Then drop all schemas you don't need:
```
DROP SCHEMA public CASCADE;
DROP SCHEMA other CASCADE;
```
The only drawback is all connections to old\_db must be determinated before you can create the copy (so the process that runs the `CREATE DATABASE` statement must connect e.g. to template1)
If that is not an option, pg\_dump/pg\_restore is the only way to do it. |
10,474 | How I can copy my `public` schema into the same database with full table structure, data, functions, fk, pk and etc.
My version of Postgres is 8.4
P.S. I need to copy **schema** NOT database | 2012/01/10 | [
"https://dba.stackexchange.com/questions/10474",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/5728/"
] | There's no simple way to do this in pg\_dump/pg\_restore itself. You could try the following if you are able to remove the database temporarily.
1. Take a dump of your public schema using [pg\_dump](http://www.postgresql.org/docs/8.4/static/app-pgdump.html)
2. run "ALTER SCHEMA public RENAME TO public\_copy"
3. Restore your dump of your public schema from step 1 using [pg\_restore](http://www.postgresql.org/docs/8.4/static/app-pgrestore.html) | Using pgAdmin you can do the following. It's pretty manual, but might be all you need. A script based approach would be much more desirable. Not sure how well this will work if you don't have admin access and if your database is large, but should work just fine on a development database that you just have on your local computer.
1. Right-click schema name you want to copy and click Backup. (You can go deeper than this and choose to just backup the structure instead of both).
2. Give the backup file a name and also choose a format. (I usually use Tar.)
3. Click Backup.
4. Right-click the schema you backed up from and click properties and rename it to something else temporarily. (e.g. **temprename**)
5. Click the schemas root and right-click it in the object browser and click **create new schema** and give the schema the name **public**. This will be the schema you are copying into from your backup.
6. Right-click the new schema **public** from step 5. and click restore. Restore from the backup file in step 3.
7. Rename new schema **public** to a different name (e.g. **newschema**).
8. Rename schema **temprename** change from step 4 back to the original name.
Note: The new schema created in step 5 must have the same name as the schema you backed up, otherwise pgAdmin won't restore anything |
10,474 | How I can copy my `public` schema into the same database with full table structure, data, functions, fk, pk and etc.
My version of Postgres is 8.4
P.S. I need to copy **schema** NOT database | 2012/01/10 | [
"https://dba.stackexchange.com/questions/10474",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/5728/"
] | There's no simple way to do this in pg\_dump/pg\_restore itself. You could try the following if you are able to remove the database temporarily.
1. Take a dump of your public schema using [pg\_dump](http://www.postgresql.org/docs/8.4/static/app-pgdump.html)
2. run "ALTER SCHEMA public RENAME TO public\_copy"
3. Restore your dump of your public schema from step 1 using [pg\_restore](http://www.postgresql.org/docs/8.4/static/app-pgrestore.html) | >
>
> ```
> pg_dump -n schema_name > dump.sql
> vi dump.sql # edit the schema name
> psql: psql -f dump.sql
>
> ```
>
>
If you're stuck with php then use either back tics
```
`/usr/bin/pg_dump-n myschema mydb -U username > /tmp/dump.sql`
```
or the exec() command. For the change you can use sed the same way.
Here are 6 more chars |
10,474 | How I can copy my `public` schema into the same database with full table structure, data, functions, fk, pk and etc.
My version of Postgres is 8.4
P.S. I need to copy **schema** NOT database | 2012/01/10 | [
"https://dba.stackexchange.com/questions/10474",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/5728/"
] | There's no simple way to do this in pg\_dump/pg\_restore itself. You could try the following if you are able to remove the database temporarily.
1. Take a dump of your public schema using [pg\_dump](http://www.postgresql.org/docs/8.4/static/app-pgdump.html)
2. run "ALTER SCHEMA public RENAME TO public\_copy"
3. Restore your dump of your public schema from step 1 using [pg\_restore](http://www.postgresql.org/docs/8.4/static/app-pgrestore.html) | expanding on user1113185 [answer](https://dba.stackexchange.com/a/10475/78639), here's a full workflow using psql/pg\_dump.
The following exports all objects of `old_schema` and imports them into new `new_schema` schema, as `user`, in `dbname` database:
```
psql -U user -d dbname -c 'ALTER SCHEMA old_schema RENAME TO new_schema'
pg_dump -U user -n new_schema -f new_schema.sql dbname
psql -U user -d dbname -c 'ALTER SCHEMA new_schema RENAME TO old_schema'
psql -U user -d dbname -c 'CREATE SCHEMA new_schema'
psql -U user -q -d dbname -f new_schema.sql
rm new_schema.sql
``` |
51,563,702 | I have been banging my head at my desk for 3 days now and I am not sure what to do about this issue, so please if you have any idea of what is going on let me know.
**Issue:** When I am running a globally installed (outside of the virtual environment) jupyter notebook with a registered kernel (ipykernel installed in the virtual env) where the python3 -V of the virtual environment is 3.6.4 and the global python3 -V is 3.7.0, the jupyter notebook (is ran from wihin the active venv) crashes when I activate the venv kernel because it is trying to pick up site packages from the global python 3.7.0
```
[I 11:11:13.221 NotebookApp] Serving notebooks from local directory: /Users/cap/Desktop/Projects/lastresort
[I 11:11:13.221 NotebookApp] 0 active kernels
[I 11:11:13.221 NotebookApp] The Jupyter Notebook is running at:
[I 11:11:13.221 NotebookApp] http://localhost:8888/?token=cc92b513df1e586ce592bfc4fe641b9f2d76fdde480c6f07
[I 11:11:13.221 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 11:11:13.222 NotebookApp]
Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
http://localhost:8888/?token=cc92b513df1e586ce592bfc4fe641b9f2d76fdde480c6f07&token=cc92b513df1e586ce592bfc4fe641b9f2d76fdde480c6f07
[I 11:11:13.438 NotebookApp] Accepting one-time-token-authenticated connection from ::1
[I 11:11:16.385 NotebookApp] Kernel started: 2ad09f31-36f6-48cf-b859-7f78fdb6adb8
[I 11:11:17.014 NotebookApp] Adapting to protocol v5.1 for kernel 2ad09f31-36f6-48cf-b859-7f78fdb6adb8
[I 11:11:19.398 NotebookApp] Starting buffering for 2ad09f31-36f6-48cf-b859-7f78fdb6adb8:cda1e6c165f3482482d80df7d2664e9b
[I 11:11:19.609 NotebookApp] Kernel shutdown: 2ad09f31-36f6-48cf-b859-7f78fdb6adb8
[I 11:11:19.630 NotebookApp] Kernel started: 9b90f202-97bf-43b1-ba50-64d6a1323405
Traceback (most recent call last):
File "/Users/cap/.pyenv/versions/3.6.4/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/Users/cap/.pyenv/versions/3.6.4/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/lib/python3.7/site-packages/ipykernel_launcher.py", line 15, in <module>
from ipykernel import kernelapp as app
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/lib/python3.7/site-packages/ipykernel/__init__.py", line 2, in <module>
from .connect import *
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/lib/python3.7/site-packages/ipykernel/connect.py", line 18, in <module>
import jupyter_client
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/lib/python3.7/site-packages/jupyter_client/__init__.py", line 4, in <module>
from .connect import *
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/lib/python3.7/site-packages/jupyter_client/connect.py", line 23, in <module>
import zmq
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/vendor/lib/python3.7/site-packages/zmq/__init__.py", line 47, in <module>
from zmq import backend
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/vendor/lib/python3.7/site-packages/zmq/backend/__init__.py", line 40, in <module>
reraise(*exc_info)
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/vendor/lib/python3.7/site-packages/zmq/utils/sixcerpt.py", line 34, in reraise
raise value
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/vendor/lib/python3.7/site-packages/zmq/backend/__init__.py", line 27, in <module>
_ns = select_backend(first)
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/vendor/lib/python3.7/site-packages/zmq/backend/select.py", line 26, in select_backend
mod = __import__(name, fromlist=public_api)
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/vendor/lib/python3.7/site-packages/zmq/backend/cython/__init__.py", line 6, in <module>
from . import (constants, error, message, context,
ImportError: cannot import name 'constants'
```
As you can see from the few lines above, it is calling the wrong site-packages:
```
Traceback (most recent call last):
File "/Users/cap/.pyenv/versions/3.6.4/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/Users/cap/.pyenv/versions/3.6.4/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/lib/python3.7/site-packages/ipykernel_launcher.py", line 15, in <module>
from ipykernel import kernelapp as app
File "/usr/local/Cellar/jupyter/1.0.0_5/libexec/lib/python3.7/site-packages/ipykernel/__init__.py", line 2, in <module>
```
This is my setup:
* pyenv for managing multiple versions of python
* pipenv for virtualenvs (still not super happy with this one)
How I set it up:
1. Install global python (I don't like messing around with pyenv for my default python, I keep to the most up to date version)
`> brew install python3 # This install 3.7.0`
2. Install pyenv
`> brew install pyenv`
3. Install python 3.6.4 (I need this for tensorflow)
`> pyenv install 3.6.4`
4. Install pipenv (I am not using the pip installer here)
`> brew install pipenv`
5. Create a project (I have a WORKON\_HOME setup so my .venvs get
created in my ~/.venvs)
```
> cd Projects
> mkdire test_project
> cd test_project
> pipenv --python 3.6.4 #create the virtual env
```
6. Launch the virtual env
```
> pipenv shell
> python3 -V
> Python 3.6.4 # I have validated in another shell that global is still 3.7
> pyenv which python3
> /Users/cap/.pyenv/versions/3.6.4/bin/python3
```
7. Install ipykernel and setup
```
> pipenv install ipykernel
> ipython kernel install --user --name=lastresort-yyl8tfk8 --display-name "Python (lastresort-yyl8tfk8)"
```
8. Check if jupyter sees the new kernel (Note: I am still in the venv)
```
> jupyter kernelspec list
> lastresort-yyl8tfk8 /Users/cap/Library/Jupyter/kernels/lastresort-yyl8tfk8
```
9. Run the jupyter notebook and select the kernel
The jotebook runs fine, but when I get in and select the Python (lastresort-yyl8tfk8), the kernel restarts to load the lastresort-yyl8tfk8 kernel and I get the error from above, where it is getting confused with site-packages from 3.7.
I tried a bunch of things with paths. I also even resorted to ipython profile changes such as in here: [iptyhon profile virtual env](https://gist.github.com/henriquebastos/270cff100cb303f3d74370489022446b)
I really need some help at least with a direction of how to solve this...
My ultimate goal is simple:
Be able to have multiple versions of python with corresponding ipykernels that I can run from their virtual environments after registering them with jupyter where the jupyter install is global. In this way I can keep my code and notebook in their project folders with venvs for packages. It is pretty simple actually, I just don't know what I am messing up.
**Thank you all in advance!**
**UPDATE:**
I just verified that if I remove the global jupyter notebook and install it in the venv, it works properly. I did not expect it not to, but still.
**UPDATE:**
It seems to be some PYTHONPATH shenanigans but I don't know how to fix it.
**UPDATE:**
Tried to run using python -m as suggested in comments, but it produced the same results. For some reason when I call the jupyter notebook (installed outside of the virtual environment) with an activated virtual environment (with correctly set python3.6 in ipython in there) it does not call the right 3.6 site packages.
I have seen so many people using that setup. I really don't know where to go from here. | 2018/07/27 | [
"https://Stackoverflow.com/questions/51563702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10078580/"
] | TLDR
====
For me it worked installing `jupyter` in the virtual enviroment created by `pipenv` with the following command:
```
pipenv run pip install jupyter
```
Too Short, Wanna Read!
======================
I had the same problem with python 3 versions so I started using `pipenv` as you show, with a simple `Pipfile` configuration as follows:
```
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
numpy = "*"
pandas = "*"
matplotlib = "*"
[requires]
python_version = "3.7"
```
I thought that, as I specified python version to 3.7 in that config file, whenever I wanted to run `pipenv run jupyter notebook`, the kernel would be running under Python 3.7...
But when imported the librares indicated there from the notebook:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
```
I got the "non module installed error"
`ModuleNotFoundError: No module named 'matplotlib'`
And then in the same notebook, I checked in which version was the kernel running with the following code:
```
import sys
print(sys.version)
```
The output showed me that it was running under Python 3.6, so in that vesion I didn't have those modules installed, cause `pipenv` was intalling them for 3.7 version.
So I tried installing again jupyter but this time under the virtual enviroment created by `pipenv`, using the `run` command and `pip` tool:
```
pipenv run pip install jupyter
```
It worked for me! | To make `pipenv` use the `Pipfile` you want when running it from any path you want, you should add to your `~/.bashrc` and `~/.profile` the following env variable:
```
export PIPENV_PIPFILE="<path_to_the_Pipefile_you_want>"
```
Otherwise, `pipenv` will try to use a `Pipefile` from the path where it is being run. |
73,225,600 | I'm trying to plot a scatterplot, but instead of having points or triangles or other symbols, I want to plot numbers. For example, with these points:
```
centroidCoords = [Point(7.210123936676805, -0.0014481952154823),
Point(5.817327756517152, -1.0513260084561042),
Point(5.603133733696165, -2.7765635631249412),
Point(4.500525247710033, -0.8659667639805515),
Point(3.9999999999880367, -2.089987631283091),
```
I can plot in a scatterplot like:
```
# xs = [point.x for point in centroidCoords]
# ys = [point.y for point in centroidCoords]
# plt.scatter(xs, ys)
```
But instead of the little circular points, I'm wondering if I can plot numbers. The first point could be 1, the second point 2, etc. I tried using zip to assign the numbers like so:
```
num_label = range(0,len(centroidCoords),1)
numberedCentroids = zip(centroidCoords, num_label)
print(numberedCentroids)
```
but it doesn't print or plot how I imagined. All I want is a plot with the number 1 at point 1 coordinates, the number 2 at point 2 coordinates, etc. Eventually I will add polygons in the back and this is going to look like one of those "color the number" things.
I'm pretty new to python, so any help would be greatly appreciated! | 2022/08/03 | [
"https://Stackoverflow.com/questions/73225600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18486979/"
] | `console.log` is a void return (*i.e. returns `undefined`*), it doesn't return any Promise object to chain from. Just issue the imperative navigation after the log statement.
```
const handleSubmit = e => {
e.preventDefault();
console.log(inputs);
sendRequest()
.then(data =>
console.log(data);
navigate('/myBlogs/');
);
};
``` | i changed my code to
```
sendRequest().then((data) => console.log(data)).then(() => navigate('/myBlogs/'))
```
from this
```
sendRequest().then(data =>
console.log(data).then(() => navigate('/myBlogs/'))
);
```
and it works |
71,789,301 | ```
teams = ['Argentina', 'Australia', 'Belgium', 'Brazil', 'Colombia', 'Costa Rica', 'Croatia', 'Denmark', 'Egypt', 'England', 'France', 'Germany', 'Iceland', 'Iran', 'Japan', 'Mexico', 'Morocco', 'Nigeria', 'Panama', 'Peru', 'Poland', 'Portugal', 'Russia', 'Saudi Arabia', 'Senegal', 'Serbia', 'South Korea', 'Spain', 'Sweden', 'Switzerland', 'Tunisia', 'Uruguay']
wins = {"wins" : 0}
combined_data = dict.fromkeys(teams, wins)
combined_data["Russia"]['wins'] +=1
print(combined_data["Belgium"]['wins'])
```
should print 0 but all 'wins' go up by 1 and printout 1
I also tried 'wins' with 32 keys, but not working.
Many thanks in advance. | 2022/04/07 | [
"https://Stackoverflow.com/questions/71789301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18249677/"
] | The `wins` dictionary is shared across *all* keys inside the `combined_data` dictionary.
To resolve this issue, use a dictionary comprehension instead:
```py
combined_data = {team: {"wins" : 0} for team in teams}
``` | Your code is not creating a new dictionary for each country, it's putting a reference to *the exact same dictionary* in each key's value. You can see this by running `id()` on two separate keys of the dataframe:
```py
id(combined_data['Argentina']) # 5077746752
id(combined_data['Sweden']) # 5077746752
```
To do what you mean to do, you should use something like a dictionary expression:
```py
combined_data = {team: {"wins" : 0} for team in teams}
``` |
9,678,098 | In `SQL Server Reporting Services`, I was able to make a report that accessed `SQL Server` via a stored procedure. In this stored procedure, I passed along a parameter and the stored procedure returned only data related to that parameter. This worked correctly.
Is it possible to, take that same parameter and pass it to another stored procedure so that 2 different reports on queried and returned at the same time, while being displayed on the same report?
For example:
```
Stored Procedure 1:
Parameter passed to Stored Procedure 1: OrderID
Returns Data 1
Stored Procedure 2:
Parameter passed to Stored Procedure 1: OrderID
Returns Data 2
Report:
Data1
Data2
``` | 2012/03/13 | [
"https://Stackoverflow.com/questions/9678098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/854739/"
] | Yes, you can do this by [creating an additional dataset](http://msdn.microsoft.com/en-us/library/ms160345%28v=sql.90%29.aspx), so that you have one dataset for each stored procedure call.
If your report then contains two tables, each table could then reference one of the datasets. | If the columns returns are the same for both the stored procedures then.
You can also create one more stored procedure that takes this parameter's value.
Exec both the stored procedure1 and stored procedure2 based on the parameter value.
Advantage Here You dont need to create the two tables in the report.
LINK: [UNION the results of multiple stored procedures](https://stackoverflow.com/questions/5292069/union-the-results-of-multiple-stored-procedures)
This link helps in UNION of the two or more stored procedures result. |
49,549,403 | * [Chrome output](https://i.stack.imgur.com/J6nNn.png)
* [Firefox output](https://i.stack.imgur.com/639OS.png)
```css
.continue-btn {
border: 2px solid #000;
border-radius: 0px!important;
width: 100%;
text-align: center;
padding: 0px;
line-height: 55px;
color: #000;
margin: 6% 0%;
}
.heading-one {
font-size: 14pt;
font-family: Nexabold;
}
```
```html
<div class="" id="continue-page2" >
<a class="btn continue-btn heading-two" href="#"> CONTINUE <span class="fa fa-arrow-right "></span></a>
</div>
```
In Firefox, the span is displayed in next line in the button. If I make a change in CSS its affected in Chrome. | 2018/03/29 | [
"https://Stackoverflow.com/questions/49549403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1140153/"
] | The reason you couldn't find information on any other languages using checked exceptions is they learned from Java's mistake.
EDIT: So to clarify a little more checked exceptions were entirely a Java thing that in theory sounded like a really great idea, but in practice actually create a tight coupling between the consuming function and the function being consumed. It also makes it more tedious to handle an exception where it can be handled. Instead you have to catch and re-throw in every function in between where the exception was thrown and where it can actually be handled. I could rewrite it all here but I think this post does a magnificent job of explaining why checked exceptions are really not a good idea.
<https://blog.philipphauer.de/checked-exceptions-are-evil/> | Checked exceptions are not a common feature in mainstream languages due to bad experiences with them in Java. However, Java is not the only language that implements them, and just because Java's implementation was faulty does not mean that they are a bad feature in general.
[Nim](https://status-im.github.io/nim-style-guide/errors.exceptions.html#general) has checked exceptions.
Checked exceptions have been implemented as a [Purescript library](https://pursuit.purescript.org/packages/purescript-checked-exceptions/3.1.0/docs/Control.Monad.Except.Checked).
Checked exceptions can be implemented in [Koka](https://koka-lang.github.io/koka/doc/book.html) by making a custom defined effect for it.
Some common issues with checked exceptions in Java can be handled with better design.
Propogation of "throws" clauses in type signatures leading to potentially a lot of refactoring due to having to update method signatures can be solved via complete type inference. Haskell has a nice way of solving this for type classes (which propogate in the same way checked exceptions do in type signatures -- and can also be used to implement typed exceptions) with *partial type signatures* -- essentially leaving arbitrary parts of the type "blank" for the compiler to infer.
Issues with higher order functions/lambdas can be resolved via polymorphism/generics. In languages that implement checked exceptions via an effect system (like Koka) -- effect polymorphism is a particularly nice way to solve the problem.
Haskell, Koka, Purescript, and Nim are all highly functional languages that often make use of lambdas and higher order functions, and they don't have Java's issues with checked exceptions. |
3,381,936 | I have shown by tedious case analysis that any formula in the first order logic that does not contain the negation or implication symbol cannot be a contradiction (false under every interpretation). I am wondering if a there is a formula without the not symbol that is a contradiction, and if there is a formula with only the logical symbol of implication that is a contraction. | 2019/10/05 | [
"https://math.stackexchange.com/questions/3381936",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/287662/"
] | There is no such sentence, and this remains true if we allow $\wedge,\vee,\leftrightarrow$ as well (thus subsuming the previous result you mention).
In fact, fixing a first-order language $\Sigma$, the unique (up to isomorphism) one-element $\Sigma$-structure $\mathcal{A}\_\Sigma$ where every $n$-ary relation holds on the unique $n$-tuple satisfies *every* negation-free $\Sigma$-sentence.
This is a straightforward induction on complexity (and also a neat example of a situation where strengthening the induction hypothesis simplifies the argument):
* For the base case, note that every atomic $\Sigma$-formula is true in this structure under every (i.e., the unique) variable assignment.
* For the inductive case, quantifiers are essentially trivial, and all connectives except $\neg$ are "truth preserving" in the sense that whenever all inputs are true the result is true.
*Note that the nature of the structure $\mathcal{A}\_\Sigma$ is used in two places: the analysis of atomic formulas, and the triviality of the quantifiers.*
Incidentally, the point about propositional connectives above is also [the standard way to prove](https://math.stackexchange.com/questions/2046902/functional-completeness-proving-%e2%87%92-%e2%88%a7-%e2%88%a8-is-functionally-complete) that $\{\wedge,\vee,\rightarrow,\leftrightarrow\}$ is not [functionally complete](https://en.wikipedia.org/wiki/Functional_completeness). Meanwhile, note that the notion of "truth preserving" used here is incredibly weak; in particular, since "False implies False" is true but "True implies False" is false we see that it doesn't imply truth *monotonicity* (= "making the inputs more true makes the output more true"). As such I don't think it actually has an accepted name, it's too weak a condition in almost every context. | If such a formula existed, one with a minimal number of implications would contain at least one $\to$ (because you've already checked the case with none), and we could write some such contradiction as $a\to b$. (If $(a\to b)\lor c$ is a contradiction, so is $a\to b$; if $(a\to b)\land c$ is a contradiction, so is $(c\land a)\to b$.) We then need $a$ to be true and $b$ false in all interpretations. But then $b$ is an option with one fewer $\to$, a contradiction. |
169,865 | In my kitchen, all our drawers appear to use a wooden rail "hanger" (at the top of the drawer) to slide in and out:
[](https://i.stack.imgur.com/zcij6.jpg)
The problem is our utensil drawer is probably one of the heaviest, and it finally gave out, so I replaced it with a new rail and hanger kit from local home improvement store. However now, a month or so later, the drawer "drops down" when pushed in all the way, and the hanger seems to be worn down quite a bit:
[](https://i.stack.imgur.com/Re5mQ.jpg)
I could replace the hanger again, but it seems like something is inherently wrong here. I'm guessing the wood/plastic hanger system isn't quite meant for a heavy utensil drawer, and there's some better solution? A general contractor wanted an enormous sum to even come take a look, so I'm hoping you kind folks might have some advice. Thanks! | 2019/07/25 | [
"https://diy.stackexchange.com/questions/169865",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/1125/"
] | You're not answering what Ed Beal and Harper are asking. Is the breaker heating up? You can check that with an infrared thermometer which you can find for somewhere south of $30.00.
You also just revealed the the breaker is an AFCI (arc fault circuit interrupter). It trips when it senses something arcing. It is quite different from a GFCI (ground fault circuit interrupter) which trips when it senses current leakage between the hot and the neutral. So they both protect the circuit but for different problems.
Lets get back to your breaker. There could be a loose conductor attached to a device or a splice, causing an arc thus tripping your breaker. Before I start to check ever device and splice. If you have another AFCI breaker in the panel, I would swap it out to see if the problem moves with the breaker. If it moves then replace the breaker. If the new AFCI trips on the same circuit then we are back to opening boxes and looking for the problem.
Good Luck.
PS Also check out Harpers comments on receptacles that are wired by stabbing into the back of a receptacle instead of installing the conductor around the side screw. He's done it many times so you won't have to look through too many of his answers to find it. By the way, I agree with him. | Window AC draws more power than a fridge and *they* get a dedicated circuit by code. (mostly because the loss of power to a fridge is a big inconvenience)
That said: Breakers are not peas in a pod. Some will trip below rated capacity (rare) Replacing the breaker with a 20A, given that you have 12 ga wire is a cheap and easy first kick at the cat. Take the time to verify that you have 12 ga throughout the entire circuit.
There is a cute device called a kill-o-watt. It's a box you plug into the wall, then plug your device into. It gives you the current and power actually being used. A window AC can easily draw 1500 W on it's own, a TV a couple hundred, and chargers/wall warts 5-20w each. Add lights to that.
A clip on amp meter can measure the current at the panel. Clip around the supply branch line to the breaker, and check the draw of the entire circuit. Turn various things on and off, and see what the current is.
More to the point you can see if there is a demand when nothing is on. If this is the case, then you may have an intermittent short.
A compressor (AC's have a reefer type compressor) draws substantially more power on startup. This usually is only for a few seconds.
Check also that there are no other loads on that circuit. I know of one building where the south wall on all the bedrooms was on breaker 15, the west wall on 16, the north wall on 17. The idea was that if one room got converted to an office, there would be enough power for everything. |
169,865 | In my kitchen, all our drawers appear to use a wooden rail "hanger" (at the top of the drawer) to slide in and out:
[](https://i.stack.imgur.com/zcij6.jpg)
The problem is our utensil drawer is probably one of the heaviest, and it finally gave out, so I replaced it with a new rail and hanger kit from local home improvement store. However now, a month or so later, the drawer "drops down" when pushed in all the way, and the hanger seems to be worn down quite a bit:
[](https://i.stack.imgur.com/Re5mQ.jpg)
I could replace the hanger again, but it seems like something is inherently wrong here. I'm guessing the wood/plastic hanger system isn't quite meant for a heavy utensil drawer, and there's some better solution? A general contractor wanted an enormous sum to even come take a look, so I'm hoping you kind folks might have some advice. Thanks! | 2019/07/25 | [
"https://diy.stackexchange.com/questions/169865",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/1125/"
] | You're not answering what Ed Beal and Harper are asking. Is the breaker heating up? You can check that with an infrared thermometer which you can find for somewhere south of $30.00.
You also just revealed the the breaker is an AFCI (arc fault circuit interrupter). It trips when it senses something arcing. It is quite different from a GFCI (ground fault circuit interrupter) which trips when it senses current leakage between the hot and the neutral. So they both protect the circuit but for different problems.
Lets get back to your breaker. There could be a loose conductor attached to a device or a splice, causing an arc thus tripping your breaker. Before I start to check ever device and splice. If you have another AFCI breaker in the panel, I would swap it out to see if the problem moves with the breaker. If it moves then replace the breaker. If the new AFCI trips on the same circuit then we are back to opening boxes and looking for the problem.
Good Luck.
PS Also check out Harpers comments on receptacles that are wired by stabbing into the back of a receptacle instead of installing the conductor around the side screw. He's done it many times so you won't have to look through too many of his answers to find it. By the way, I agree with him. | You have a fault in the *wiring* in your wall, not the breaker
--------------------------------------------------------------
Most AFCIs, including your Homeline unit, also contain a ground fault trip in order to help them catch firestarting arc-to-ground type faults (note, that the "arcs" AFCIs catch don't have to be *clearance arcs* through air, but can and often are *creepage arcs* along contaminated insulating surfaces at a damage point), and your test results are showing that that's why the breaker's tripping: it's seeing the characteristic current imbalance of a ground fault, likely caused by a wiring error or a damaged cable in the wall, and your receptacle-type GFCIs aren't being hooked up appropriately to catch that sort of thing.
It sounds like you'll have to go through the wiring on that tripping circuit, trying to see if the breaker still trips as "branches" are disconnected from the circuit's wiring topology, in order to localize this fault to the culprit wiring run, which will then have to be dealt with appropriately, either by running a new cable, or by cutting out the culprit section of cable and installing junction boxes to splice a replacement length in. Basically, this entails a "turn the breaker off, disconnect some section inside a box and cap off any loose ends, turn the breaker back on, see if it trips" loop, working systematically from the far ends of the wiring tree up towards the homerun back to the panel. |
169,865 | In my kitchen, all our drawers appear to use a wooden rail "hanger" (at the top of the drawer) to slide in and out:
[](https://i.stack.imgur.com/zcij6.jpg)
The problem is our utensil drawer is probably one of the heaviest, and it finally gave out, so I replaced it with a new rail and hanger kit from local home improvement store. However now, a month or so later, the drawer "drops down" when pushed in all the way, and the hanger seems to be worn down quite a bit:
[](https://i.stack.imgur.com/Re5mQ.jpg)
I could replace the hanger again, but it seems like something is inherently wrong here. I'm guessing the wood/plastic hanger system isn't quite meant for a heavy utensil drawer, and there's some better solution? A general contractor wanted an enormous sum to even come take a look, so I'm hoping you kind folks might have some advice. Thanks! | 2019/07/25 | [
"https://diy.stackexchange.com/questions/169865",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/1125/"
] | You're not answering what Ed Beal and Harper are asking. Is the breaker heating up? You can check that with an infrared thermometer which you can find for somewhere south of $30.00.
You also just revealed the the breaker is an AFCI (arc fault circuit interrupter). It trips when it senses something arcing. It is quite different from a GFCI (ground fault circuit interrupter) which trips when it senses current leakage between the hot and the neutral. So they both protect the circuit but for different problems.
Lets get back to your breaker. There could be a loose conductor attached to a device or a splice, causing an arc thus tripping your breaker. Before I start to check ever device and splice. If you have another AFCI breaker in the panel, I would swap it out to see if the problem moves with the breaker. If it moves then replace the breaker. If the new AFCI trips on the same circuit then we are back to opening boxes and looking for the problem.
Good Luck.
PS Also check out Harpers comments on receptacles that are wired by stabbing into the back of a receptacle instead of installing the conductor around the side screw. He's done it many times so you won't have to look through too many of his answers to find it. By the way, I agree with him. | You have an arc fault breaker. It has two jobs:
* Detect current which is excessive
* Detect **arc faults**.
Arc faults are when arcing occurs (when it's not supposed to; obviously throwing a switch is an expected arc). Arcing is the blue-white flash you may have seen when plugging in certain things to certain places. The AFCI *literally listens* to the power line for the distinctive sound; it sounds like hooking up speakers or plugging in a headphone, the crinkle-snap sound.
AFCIs were originally required in bedrooms to detect electric-blanket fires. *Turns out, they're also fantastic at detecting **backstabs***.
A [backstab](https://www.handymanhowto.com/electrical-outlets-side-wire-versus-back-wire/) is a method of connecting electrical wires to switches and sockets, that is used by builders in a hurry, who don't care what happens after the closing papers are signed. The connections are very hokey (what do you expect from a spring clip that you get four for 50 cents?) and they are certainly the #1 source of problems we encounter.
Most likely the fault is somewhere in the wall wiring at the sockets or switches, though possibly also in the power strip or extension cords. This is a good time to change all those sockets and switches to screw-terminal or screw-to-clamp types. |
52,823,091 | I've been racking my brain for a couple of days to work out a series or closed-form equation to the following problem:
Specifically: given all strings of length *N* that draws from an alphabet of *L* letters (starting with 'A', for example {A, B}, {A, B, C}, ...), how many of those strings contain a substring that matches the pattern: 'A', more than 1 not-'A', 'A'. The standard regular expression for that pattern would be `A[^A][^A]+A`.
The number of possible strings is simple enough: *L^N* . For small values of *N* and *L*, it's also very practical to simply create all possible combinations and use a regular expression to find the substrings that match the pattern; in R:
```
all.combinations <- function(N, L) {
apply(
expand.grid(rep(list(LETTERS[1:L]), N)),
1,
paste,
collapse = ''
)
}
matching.pattern <- function(N, L, pattern = 'A[^A][^A]+A') {
sum(grepl(pattern, all.combinations(N, L)))
}
all.combinations(4, 2)
matching.pattern(4, 2)
```
I had come up with the following, which works for N < 7:
```
M <- function(N, L) {
sum(
sapply(
2:(N-2),
function(g) {
(N - g - 1) * (L - 1) ** g * L ** (N - g - 2)
}
)
)
}
```
Unfortunately, that only works while N < 7 because it's simply adding the combinations that have substrings A..A, A...A, A....A, etc. and some combinations obviously have multiple matching substrings (e.g., A..A..A, A..A...A), which are counted twice.
Any suggestions? I am open to procedural solutions too, so long as they don't blow up with the number of combinations (like my code above would). I'd like to be able to compute for values of N from 15 to 25 and L from 2 to 10.
For what it is worth, here's the number of combinations, and matching combinations for some values of N and L that are tractable to determine by generating all combinations and doing a regular expression match:
```
N L combinations matching
-- - ------------ --------
4 2 16 1
5 2 32 5
6 2 64 17
7 2 128 48
8 2 256 122
9 2 512 290
10 2 1024 659
4 3 81 4
5 3 243 32
6 3 729 172
7 3 2187 760
8 3 6561 2996
9 3 19683 10960
10 3 59049 38076
4 4 256 9
5 4 1024 99
6 4 4096 729
7 4 16384 4410
8 4 65536 23778
9 4 262144 118854
10 4 1048576 563499
``` | 2018/10/15 | [
"https://Stackoverflow.com/questions/52823091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9189482/"
] | It is possible to use dynamic programming approach.
For fixed `L`, let `X(n)` be number of strings of length `n` that contain given pattern, and let `A(n)` be number of strings of length `n` that contain given pattern and starts with A.
First derive recursion formula for `A(n)`. Lets count all strings in `A(n)` by grouping them by first 2-3 letters. Number of strings in `A(n)` with:
* "second letter A" is `A(n-1)`,
* "second letter non-A and third letter is A" is `A(n-2)`,
* "second and third letter non-A" is `(L^(n-3) - (L-1)^(n-3))`. That is because string 'needs' at least one A in remaining letters to be counted.
With that:
```
A(n) = A(n-1) + (L-1) * (A(n-2) + (L-1) * (L^(n-3) - (L-1)^(n-3)))
```
String of length `n+1` can start with A or non-A:
```
X(n+1) = A(n+1) + (L-1) * X(n)
X(i) = A(i) = 0, for i <= 3
```
Python implementation:
```
def combs(l, n):
x = [0] * (n + 1) # First element is not used, easier indexing
a = [0] * (n + 1)
for i in range(4, n+1):
a[i] = a[i-1] + (l-1) * (a[i-2] + (l-1) * (l**(i-3) - (l-1)**(i-3)))
x[i] = a[i] + (l-1) * x[i-1]
return x[4:]
print(combs(2, 10))
print(combs(3, 10))
print(combs(4, 10))
``` | This can be described as a state machine. (For simplicity, `x` is any letter other than `A`.)
```
S0 := 'A' S1 | 'x' S0 // ""
S1 := 'A' S1 | 'x' S2 // A
S2 := 'A' S1 | 'x' S3 // Ax
S3 := 'A' S4 | 'x' S3 // Axx+
S4 := 'A' S4 | 'x' S4 | $ // AxxA
```
Counting the number of matching strings of length `n`
```
S0(n) = S1(n-1) + (L-1)*S0(n-1); S0(0) = 0
S1(n) = S1(n-1) + (L-1)*S2(n-1); S1(0) = 0
S2(n) = S1(n-1) + (L-1)*S3(n-1); S2(0) = 0
S3(n) = S4(n-1) + (L-1)*S3(n-1); S3(0) = 0
S4(n) = S4(n-1) + (L-1)*S4(n-1); S4(0) = 1
```
Trying to reduce `S0(n)` to just `n` and `L` gives a really long expression, so it would be easiest to calculate the recurrence functions as-is.
For really large `n`, this could be expressed as a matrix expression, and be efficiently calculated.
```
n
[L-1 1 0 0 0 ]
[ 0 1 L-1 0 0 ] T
[0 0 0 0 1] × [ 0 1 0 L-1 0 ] × [1 0 0 0 0]
[ 0 0 0 L-1 1 ]
[ 0 0 0 0 L ]
```
In JavaScript:
```js
function f(n, L) {
var S0 = 0, S1 = 0, S2 = 0, S3 = 0, S4 = 1;
var S1_tmp;
while (n-- > 0) {
S0 = S1 + (L - 1) * S0;
S1_tmp = S1 + (L - 1) * S2;
S2 = S1 + (L - 1) * S3;
S3 = S4 + (L - 1) * S3;
S4 = S4 + (L - 1) * S4;
S1 = S1_tmp;
}
return S0;
}
var $tbody = $('#resulttable > tbody');
for (var L = 2; L <= 4; L++) {
for (var n = 4; n <= 10; n++) {
$('<tr>').append([
$('<td>').text(n),
$('<td>').text(L),
$('<td>').text(f(n,L))
]).appendTo($tbody);
}
}
```
```css
#resulttable td {
text-align: right;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="resulttable">
<thead>
<tr>
<th>N</th>
<th>L</th>
<th>matches</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
``` |
56,579,837 | i have an issue with an AJAX call to give the response to the main function. Right now i use async false which i know is odd and i try to solve it but fail all the time.
This works (async false):
```
function printTable(){
var $table = $('#Table');
var view_data;
$.ajax({
type: "GET",
url: '/api/getdata',
success: function(response) {
var TableData = [];
for(var i =0;i < response.length ;i++){
var item = response[i];
var sessionID = item.sessionID;
if(sessionID){
$.ajax({
async: false,
type: "POST",
url: '/api/getNickname',
dataType: "json",
data: {
id: sessionID,
},
success: function(response){
view_data = response;
}
});
}
TableData.push({
_id: item._id,
datum: item.datum,
uhrzeit: item.uhrzeit,
session: view_data,
});
}
$table.bootstrapTable({data: TableData});
$table.bootstrapTable('togglePagination');
}
})
}
```
I tried the suggestion from here: [Assigning ajax response to global variable without using async: false](https://stackoverflow.com/questions/39447107/assigning-ajax-response-to-global-variable-without-using-async-false) but it fails as view\_data is undefined.
```
function printTable(){
var $table = $('#Table');
var view_data;
$.ajax({
type: "GET",
url: '/api/getdata',
success: function(response) {
var TableData = [];
for(var i =0;i < response.length ;i++){
var item = response[i];
var sessionID = item.sessionID;
if(sessionID){
$.ajax({
type: "POST",
url: '/api/getNickname',
dataType: "json",
data: {
id: sessionID,
}
}).done(function(response){
test(response)
});
function test(response){
view_data = response;
return view_data;
}
}
}
TableData.push({
_id: item._id,
datum: item.datum,
uhrzeit: item.uhrzeit,
session: view_data,
});
}
$table.bootstrapTable({data: TableData});
$table.bootstrapTable('togglePagination');
}
})
}
```
What i realized is if i put alert(view\_data); before the push it works!? Im not that deep into JS/AJAX as is still learn it, so i hope someone might give me a hint or can help..
How can i pass var view\_data to the main function without using async false?
Thanks... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56579837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10320484/"
] | Yes, absolutely!
As ever, there is a trade-off, which you've already identified.
But this is a completely normal and sensible thing to do. If you don't need to compute these values every time, then don't.
In this particular case, I'd probably make these items static members of the encapsulating class, unless you have a strong need to delay instantiation (perhaps the functions are not invoked on every run and you deem these initialisations too "heavy" to perform when you don't need them).
In fact, that would render the entire function `getEndPointUrl()` obsolete. Just have it be a public member constant! Your rationale that the constant "is not used anywhere else" is a bit of a circular argument; you use the data wherever `getEndPointUrl()` is used. | It depends on your context. As you rightly point out you're trading memory usage for speed. So what's more important (if either even) in your context? Are you on the hot path of a low latency program? Are you on a low memory device? |
56,579,837 | i have an issue with an AJAX call to give the response to the main function. Right now i use async false which i know is odd and i try to solve it but fail all the time.
This works (async false):
```
function printTable(){
var $table = $('#Table');
var view_data;
$.ajax({
type: "GET",
url: '/api/getdata',
success: function(response) {
var TableData = [];
for(var i =0;i < response.length ;i++){
var item = response[i];
var sessionID = item.sessionID;
if(sessionID){
$.ajax({
async: false,
type: "POST",
url: '/api/getNickname',
dataType: "json",
data: {
id: sessionID,
},
success: function(response){
view_data = response;
}
});
}
TableData.push({
_id: item._id,
datum: item.datum,
uhrzeit: item.uhrzeit,
session: view_data,
});
}
$table.bootstrapTable({data: TableData});
$table.bootstrapTable('togglePagination');
}
})
}
```
I tried the suggestion from here: [Assigning ajax response to global variable without using async: false](https://stackoverflow.com/questions/39447107/assigning-ajax-response-to-global-variable-without-using-async-false) but it fails as view\_data is undefined.
```
function printTable(){
var $table = $('#Table');
var view_data;
$.ajax({
type: "GET",
url: '/api/getdata',
success: function(response) {
var TableData = [];
for(var i =0;i < response.length ;i++){
var item = response[i];
var sessionID = item.sessionID;
if(sessionID){
$.ajax({
type: "POST",
url: '/api/getNickname',
dataType: "json",
data: {
id: sessionID,
}
}).done(function(response){
test(response)
});
function test(response){
view_data = response;
return view_data;
}
}
}
TableData.push({
_id: item._id,
datum: item.datum,
uhrzeit: item.uhrzeit,
session: view_data,
});
}
$table.bootstrapTable({data: TableData});
$table.bootstrapTable('togglePagination');
}
})
}
```
What i realized is if i put alert(view\_data); before the push it works!? Im not that deep into JS/AJAX as is still learn it, so i hope someone might give me a hint or can help..
How can i pass var view\_data to the main function without using async false?
Thanks... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56579837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10320484/"
] | That seems like a viable option. I have one suggested change for your sample, and that is to call `getApiUrl()` within the second static's initializer, making it the only initializer... thusly:
```
static const QString endpointUrl = QString("%1/%2").arg(getApiUrl(), "endpoint");
```
That's one less object to keep around for the lifetime of your program.
There are a number of concerns when caching with statics:
1. You lose control over when that object's lifetime ends. This may or may not be a problem depending on whether or not that object needs a pointer/reference to something else in order to properly clean up after itself.
2. I don't believe there are any guarantees about static object deconstruction order... It may be necessary to further wrap things in `shared_ptr` to ensure resources aren't yanked out from under your static objects.
3. Caches in general often provide a way to flush out their stored values and be repopulated. No such mechanism exists for statics, particularly `const static`s.
EDIT: Rumor has it that thread safety is not a concern.
But if none of those concerns apply in your particular use case, then by all means, use `static`.
EDIT: Non-trivial comment reply:
I cannot advise strongly enough against depending on static object destruction order.
Imaging changing your program such that your resource loading system now starts before your logging system. You set a break point and step through the new code, whereupon you see that everything is fine. You end the debug session, run your unit tests, and they all pass. Check in the source, and the nightly integration tests fail... *if you're lucky*. If you're not, your program starts to crash on exit in front of customers.
It turns out your resource system tries to log something on shut down. Boom. But hey... everything still runs fine! Why bother fixing it, right?
Oh, and it turns out that thing your resource system was trying to log was an error condition that will only be a problem... for your biggest customer.
Ouch.
Don't be that guy. Don't depend on static destructor order.
(Okay, now imagine that the order of object construction/destruction isn't deterministic because some of those functions with static objects are called from different threads. Having nightmares yet?) | It depends on your context. As you rightly point out you're trading memory usage for speed. So what's more important (if either even) in your context? Are you on the hot path of a low latency program? Are you on a low memory device? |
56,579,837 | i have an issue with an AJAX call to give the response to the main function. Right now i use async false which i know is odd and i try to solve it but fail all the time.
This works (async false):
```
function printTable(){
var $table = $('#Table');
var view_data;
$.ajax({
type: "GET",
url: '/api/getdata',
success: function(response) {
var TableData = [];
for(var i =0;i < response.length ;i++){
var item = response[i];
var sessionID = item.sessionID;
if(sessionID){
$.ajax({
async: false,
type: "POST",
url: '/api/getNickname',
dataType: "json",
data: {
id: sessionID,
},
success: function(response){
view_data = response;
}
});
}
TableData.push({
_id: item._id,
datum: item.datum,
uhrzeit: item.uhrzeit,
session: view_data,
});
}
$table.bootstrapTable({data: TableData});
$table.bootstrapTable('togglePagination');
}
})
}
```
I tried the suggestion from here: [Assigning ajax response to global variable without using async: false](https://stackoverflow.com/questions/39447107/assigning-ajax-response-to-global-variable-without-using-async-false) but it fails as view\_data is undefined.
```
function printTable(){
var $table = $('#Table');
var view_data;
$.ajax({
type: "GET",
url: '/api/getdata',
success: function(response) {
var TableData = [];
for(var i =0;i < response.length ;i++){
var item = response[i];
var sessionID = item.sessionID;
if(sessionID){
$.ajax({
type: "POST",
url: '/api/getNickname',
dataType: "json",
data: {
id: sessionID,
}
}).done(function(response){
test(response)
});
function test(response){
view_data = response;
return view_data;
}
}
}
TableData.push({
_id: item._id,
datum: item.datum,
uhrzeit: item.uhrzeit,
session: view_data,
});
}
$table.bootstrapTable({data: TableData});
$table.bootstrapTable('togglePagination');
}
})
}
```
What i realized is if i put alert(view\_data); before the push it works!? Im not that deep into JS/AJAX as is still learn it, so i hope someone might give me a hint or can help..
How can i pass var view\_data to the main function without using async false?
Thanks... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56579837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10320484/"
] | For your specific example
=========================
In your example caching will make basically no performance difference, so using `static` is probably the only method that's worth it's effort.
If your calculation was actually expensive, here are some thoughts on this way of caching in general:
In General
==========
Pros:
-----
* It's automatically thread-safe
* It's very easy to use
Cons:
-----
* Maintenence
1. Effectively a singleton [with all of it's problems](https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons)
+ Might become a surprising bug if suddenly `getUrl()` needs to return different values
+ Not great for unit tests
+ etc.
2. A lot of people don't know what the static keyword does
3. (If you link against a static lib from multiple dynamic libraries, you will get multiple instances of the variable. Probably a [ODR violation](https://en.wikipedia.org/wiki/One_Definition_Rule))
* Function
+ Maybe it is undesired for the first call to the function to take longer
* Structural
+ Likely use after free if the cached object references something on the stack.
^ (Note that a lot of these don't apply in a certain circumstances)
Alternatives
------------
In order of preference:
1. Cache the value whenever the value of getUrl() is set/changed.
2. Cache the value in the object
3. Use a cache (some `map<string, shared_ptr<void>>` or something) that you [inject](https://en.wikipedia.org/wiki/Dependency_injection) (Overkill for this) | It depends on your context. As you rightly point out you're trading memory usage for speed. So what's more important (if either even) in your context? Are you on the hot path of a low latency program? Are you on a low memory device? |
56,579,837 | i have an issue with an AJAX call to give the response to the main function. Right now i use async false which i know is odd and i try to solve it but fail all the time.
This works (async false):
```
function printTable(){
var $table = $('#Table');
var view_data;
$.ajax({
type: "GET",
url: '/api/getdata',
success: function(response) {
var TableData = [];
for(var i =0;i < response.length ;i++){
var item = response[i];
var sessionID = item.sessionID;
if(sessionID){
$.ajax({
async: false,
type: "POST",
url: '/api/getNickname',
dataType: "json",
data: {
id: sessionID,
},
success: function(response){
view_data = response;
}
});
}
TableData.push({
_id: item._id,
datum: item.datum,
uhrzeit: item.uhrzeit,
session: view_data,
});
}
$table.bootstrapTable({data: TableData});
$table.bootstrapTable('togglePagination');
}
})
}
```
I tried the suggestion from here: [Assigning ajax response to global variable without using async: false](https://stackoverflow.com/questions/39447107/assigning-ajax-response-to-global-variable-without-using-async-false) but it fails as view\_data is undefined.
```
function printTable(){
var $table = $('#Table');
var view_data;
$.ajax({
type: "GET",
url: '/api/getdata',
success: function(response) {
var TableData = [];
for(var i =0;i < response.length ;i++){
var item = response[i];
var sessionID = item.sessionID;
if(sessionID){
$.ajax({
type: "POST",
url: '/api/getNickname',
dataType: "json",
data: {
id: sessionID,
}
}).done(function(response){
test(response)
});
function test(response){
view_data = response;
return view_data;
}
}
}
TableData.push({
_id: item._id,
datum: item.datum,
uhrzeit: item.uhrzeit,
session: view_data,
});
}
$table.bootstrapTable({data: TableData});
$table.bootstrapTable('togglePagination');
}
})
}
```
What i realized is if i put alert(view\_data); before the push it works!? Im not that deep into JS/AJAX as is still learn it, so i hope someone might give me a hint or can help..
How can i pass var view\_data to the main function without using async false?
Thanks... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56579837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10320484/"
] | Yes, absolutely!
As ever, there is a trade-off, which you've already identified.
But this is a completely normal and sensible thing to do. If you don't need to compute these values every time, then don't.
In this particular case, I'd probably make these items static members of the encapsulating class, unless you have a strong need to delay instantiation (perhaps the functions are not invoked on every run and you deem these initialisations too "heavy" to perform when you don't need them).
In fact, that would render the entire function `getEndPointUrl()` obsolete. Just have it be a public member constant! Your rationale that the constant "is not used anywhere else" is a bit of a circular argument; you use the data wherever `getEndPointUrl()` is used. | That seems like a viable option. I have one suggested change for your sample, and that is to call `getApiUrl()` within the second static's initializer, making it the only initializer... thusly:
```
static const QString endpointUrl = QString("%1/%2").arg(getApiUrl(), "endpoint");
```
That's one less object to keep around for the lifetime of your program.
There are a number of concerns when caching with statics:
1. You lose control over when that object's lifetime ends. This may or may not be a problem depending on whether or not that object needs a pointer/reference to something else in order to properly clean up after itself.
2. I don't believe there are any guarantees about static object deconstruction order... It may be necessary to further wrap things in `shared_ptr` to ensure resources aren't yanked out from under your static objects.
3. Caches in general often provide a way to flush out their stored values and be repopulated. No such mechanism exists for statics, particularly `const static`s.
EDIT: Rumor has it that thread safety is not a concern.
But if none of those concerns apply in your particular use case, then by all means, use `static`.
EDIT: Non-trivial comment reply:
I cannot advise strongly enough against depending on static object destruction order.
Imaging changing your program such that your resource loading system now starts before your logging system. You set a break point and step through the new code, whereupon you see that everything is fine. You end the debug session, run your unit tests, and they all pass. Check in the source, and the nightly integration tests fail... *if you're lucky*. If you're not, your program starts to crash on exit in front of customers.
It turns out your resource system tries to log something on shut down. Boom. But hey... everything still runs fine! Why bother fixing it, right?
Oh, and it turns out that thing your resource system was trying to log was an error condition that will only be a problem... for your biggest customer.
Ouch.
Don't be that guy. Don't depend on static destructor order.
(Okay, now imagine that the order of object construction/destruction isn't deterministic because some of those functions with static objects are called from different threads. Having nightmares yet?) |
56,579,837 | i have an issue with an AJAX call to give the response to the main function. Right now i use async false which i know is odd and i try to solve it but fail all the time.
This works (async false):
```
function printTable(){
var $table = $('#Table');
var view_data;
$.ajax({
type: "GET",
url: '/api/getdata',
success: function(response) {
var TableData = [];
for(var i =0;i < response.length ;i++){
var item = response[i];
var sessionID = item.sessionID;
if(sessionID){
$.ajax({
async: false,
type: "POST",
url: '/api/getNickname',
dataType: "json",
data: {
id: sessionID,
},
success: function(response){
view_data = response;
}
});
}
TableData.push({
_id: item._id,
datum: item.datum,
uhrzeit: item.uhrzeit,
session: view_data,
});
}
$table.bootstrapTable({data: TableData});
$table.bootstrapTable('togglePagination');
}
})
}
```
I tried the suggestion from here: [Assigning ajax response to global variable without using async: false](https://stackoverflow.com/questions/39447107/assigning-ajax-response-to-global-variable-without-using-async-false) but it fails as view\_data is undefined.
```
function printTable(){
var $table = $('#Table');
var view_data;
$.ajax({
type: "GET",
url: '/api/getdata',
success: function(response) {
var TableData = [];
for(var i =0;i < response.length ;i++){
var item = response[i];
var sessionID = item.sessionID;
if(sessionID){
$.ajax({
type: "POST",
url: '/api/getNickname',
dataType: "json",
data: {
id: sessionID,
}
}).done(function(response){
test(response)
});
function test(response){
view_data = response;
return view_data;
}
}
}
TableData.push({
_id: item._id,
datum: item.datum,
uhrzeit: item.uhrzeit,
session: view_data,
});
}
$table.bootstrapTable({data: TableData});
$table.bootstrapTable('togglePagination');
}
})
}
```
What i realized is if i put alert(view\_data); before the push it works!? Im not that deep into JS/AJAX as is still learn it, so i hope someone might give me a hint or can help..
How can i pass var view\_data to the main function without using async false?
Thanks... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56579837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10320484/"
] | Yes, absolutely!
As ever, there is a trade-off, which you've already identified.
But this is a completely normal and sensible thing to do. If you don't need to compute these values every time, then don't.
In this particular case, I'd probably make these items static members of the encapsulating class, unless you have a strong need to delay instantiation (perhaps the functions are not invoked on every run and you deem these initialisations too "heavy" to perform when you don't need them).
In fact, that would render the entire function `getEndPointUrl()` obsolete. Just have it be a public member constant! Your rationale that the constant "is not used anywhere else" is a bit of a circular argument; you use the data wherever `getEndPointUrl()` is used. | For your specific example
=========================
In your example caching will make basically no performance difference, so using `static` is probably the only method that's worth it's effort.
If your calculation was actually expensive, here are some thoughts on this way of caching in general:
In General
==========
Pros:
-----
* It's automatically thread-safe
* It's very easy to use
Cons:
-----
* Maintenence
1. Effectively a singleton [with all of it's problems](https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons)
+ Might become a surprising bug if suddenly `getUrl()` needs to return different values
+ Not great for unit tests
+ etc.
2. A lot of people don't know what the static keyword does
3. (If you link against a static lib from multiple dynamic libraries, you will get multiple instances of the variable. Probably a [ODR violation](https://en.wikipedia.org/wiki/One_Definition_Rule))
* Function
+ Maybe it is undesired for the first call to the function to take longer
* Structural
+ Likely use after free if the cached object references something on the stack.
^ (Note that a lot of these don't apply in a certain circumstances)
Alternatives
------------
In order of preference:
1. Cache the value whenever the value of getUrl() is set/changed.
2. Cache the value in the object
3. Use a cache (some `map<string, shared_ptr<void>>` or something) that you [inject](https://en.wikipedia.org/wiki/Dependency_injection) (Overkill for this) |
11,634,734 | ```
println("This program allows you to enter your exam results!");
int n0 = readInt("How many exam results do you have? ");
for (int n=1; n<=n0; n++) {
String r0 = "r"+n;
int result = readInt("Result "+n+": ");
println(r0);
}
```
I am new to java and I was wondering if it would be possible for me to set 'String r0' variable's contents as 'int result' variable's name (instead of result).
I wish to do so as my program will have multiple 'int result's and I will need to use each individual one later on for arithmetic purposes. | 2012/07/24 | [
"https://Stackoverflow.com/questions/11634734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270911/"
] | I think what you really need to do is have a collection or *array* of results. Anytime you think you need something like:
```
int r0 = ...;
int r1 = ...;
int r2 = ...;
```
etc. then it's good indication that you're looking at some sort of collection.
So in the above example, you'd build an array of *size number of exam results*, and then populate each element of the array in turn.
Here's the [Java array tutorial](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html). It's also worth looking at the [Java collection tutorial](http://docs.oracle.com/javase/tutorial/collections/intro/index.html), if only to compare/contrast. | Even if you could, I don't imagine that would be a very good idea! It would be a nightmare to get to them to refer back to them later on.
In your situation, I would just recommend using an array of `int`s for your results instead. |
11,634,734 | ```
println("This program allows you to enter your exam results!");
int n0 = readInt("How many exam results do you have? ");
for (int n=1; n<=n0; n++) {
String r0 = "r"+n;
int result = readInt("Result "+n+": ");
println(r0);
}
```
I am new to java and I was wondering if it would be possible for me to set 'String r0' variable's contents as 'int result' variable's name (instead of result).
I wish to do so as my program will have multiple 'int result's and I will need to use each individual one later on for arithmetic purposes. | 2012/07/24 | [
"https://Stackoverflow.com/questions/11634734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270911/"
] | Even if you could, I don't imagine that would be a very good idea! It would be a nightmare to get to them to refer back to them later on.
In your situation, I would just recommend using an array of `int`s for your results instead. | Below I have A program that will work. I would copy the code and try and rewrite it yourself to make sure you fully understand what is going on.
```
import java.util.Scanner;
public class Arrays
{
public static void main(String[] args)
{
// Initialize Variables
int examCount = 0;
double examSum = 0;
Scanner input = new Scanner(System.in);
// Prompt The user For Number Of Exams And Recieve Value
System.out.print("Number Of Exams? ");
examCount = input.nextInt();
// Create An Array That Is The Length Of The Number Of Exams And Holds Double Values
double[] exams = new double[examCount];
// Read In All Exam Scores. A For Loop Is Used Because You Know How Many Scores There Are
for (int i = 0; i < examCount; i++)
{
System.out.print("Exam Score: ");
exams[i] = input.nextDouble();
}
// Print Out All Of The Scores
for (int i = 0; i < examCount; i++)
System.out.println("Exam #" + (i+1) + "\t" + exams[i]);
// Sum All Of The Exam Scores
for (int i = 0; i < examCount; i++)
examSum += exams[i];
// Print Out An Average Of All Of The Scores
System.out.println("Exam Average: " + examSum / examCount);
}
}
``` |
11,634,734 | ```
println("This program allows you to enter your exam results!");
int n0 = readInt("How many exam results do you have? ");
for (int n=1; n<=n0; n++) {
String r0 = "r"+n;
int result = readInt("Result "+n+": ");
println(r0);
}
```
I am new to java and I was wondering if it would be possible for me to set 'String r0' variable's contents as 'int result' variable's name (instead of result).
I wish to do so as my program will have multiple 'int result's and I will need to use each individual one later on for arithmetic purposes. | 2012/07/24 | [
"https://Stackoverflow.com/questions/11634734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270911/"
] | I think what you really need to do is have a collection or *array* of results. Anytime you think you need something like:
```
int r0 = ...;
int r1 = ...;
int r2 = ...;
```
etc. then it's good indication that you're looking at some sort of collection.
So in the above example, you'd build an array of *size number of exam results*, and then populate each element of the array in turn.
Here's the [Java array tutorial](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html). It's also worth looking at the [Java collection tutorial](http://docs.oracle.com/javase/tutorial/collections/intro/index.html), if only to compare/contrast. | **1.** First **do not declare** `r0 as String` as you **intend to use it as** `integer`, but declare it as `int`, ya offcourse you can convert
**string to integer** using `Integer.parseInt()`.
**eg:**
```
String r0 = "10";
int r = Integer.parseInt(r0);
```
**2.** I will advice you to use **Collection framework** for storing of **mulitple data** in java as it gives great **flexibilty**. Use `ArrayList<Integer>`.
**eg:**
```
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int n=1; n<=10; n++) {
arr.add(n);
}
``` |
11,634,734 | ```
println("This program allows you to enter your exam results!");
int n0 = readInt("How many exam results do you have? ");
for (int n=1; n<=n0; n++) {
String r0 = "r"+n;
int result = readInt("Result "+n+": ");
println(r0);
}
```
I am new to java and I was wondering if it would be possible for me to set 'String r0' variable's contents as 'int result' variable's name (instead of result).
I wish to do so as my program will have multiple 'int result's and I will need to use each individual one later on for arithmetic purposes. | 2012/07/24 | [
"https://Stackoverflow.com/questions/11634734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270911/"
] | I think what you really need to do is have a collection or *array* of results. Anytime you think you need something like:
```
int r0 = ...;
int r1 = ...;
int r2 = ...;
```
etc. then it's good indication that you're looking at some sort of collection.
So in the above example, you'd build an array of *size number of exam results*, and then populate each element of the array in turn.
Here's the [Java array tutorial](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html). It's also worth looking at the [Java collection tutorial](http://docs.oracle.com/javase/tutorial/collections/intro/index.html), if only to compare/contrast. | Below I have A program that will work. I would copy the code and try and rewrite it yourself to make sure you fully understand what is going on.
```
import java.util.Scanner;
public class Arrays
{
public static void main(String[] args)
{
// Initialize Variables
int examCount = 0;
double examSum = 0;
Scanner input = new Scanner(System.in);
// Prompt The user For Number Of Exams And Recieve Value
System.out.print("Number Of Exams? ");
examCount = input.nextInt();
// Create An Array That Is The Length Of The Number Of Exams And Holds Double Values
double[] exams = new double[examCount];
// Read In All Exam Scores. A For Loop Is Used Because You Know How Many Scores There Are
for (int i = 0; i < examCount; i++)
{
System.out.print("Exam Score: ");
exams[i] = input.nextDouble();
}
// Print Out All Of The Scores
for (int i = 0; i < examCount; i++)
System.out.println("Exam #" + (i+1) + "\t" + exams[i]);
// Sum All Of The Exam Scores
for (int i = 0; i < examCount; i++)
examSum += exams[i];
// Print Out An Average Of All Of The Scores
System.out.println("Exam Average: " + examSum / examCount);
}
}
``` |
11,634,734 | ```
println("This program allows you to enter your exam results!");
int n0 = readInt("How many exam results do you have? ");
for (int n=1; n<=n0; n++) {
String r0 = "r"+n;
int result = readInt("Result "+n+": ");
println(r0);
}
```
I am new to java and I was wondering if it would be possible for me to set 'String r0' variable's contents as 'int result' variable's name (instead of result).
I wish to do so as my program will have multiple 'int result's and I will need to use each individual one later on for arithmetic purposes. | 2012/07/24 | [
"https://Stackoverflow.com/questions/11634734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270911/"
] | **1.** First **do not declare** `r0 as String` as you **intend to use it as** `integer`, but declare it as `int`, ya offcourse you can convert
**string to integer** using `Integer.parseInt()`.
**eg:**
```
String r0 = "10";
int r = Integer.parseInt(r0);
```
**2.** I will advice you to use **Collection framework** for storing of **mulitple data** in java as it gives great **flexibilty**. Use `ArrayList<Integer>`.
**eg:**
```
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int n=1; n<=10; n++) {
arr.add(n);
}
``` | Below I have A program that will work. I would copy the code and try and rewrite it yourself to make sure you fully understand what is going on.
```
import java.util.Scanner;
public class Arrays
{
public static void main(String[] args)
{
// Initialize Variables
int examCount = 0;
double examSum = 0;
Scanner input = new Scanner(System.in);
// Prompt The user For Number Of Exams And Recieve Value
System.out.print("Number Of Exams? ");
examCount = input.nextInt();
// Create An Array That Is The Length Of The Number Of Exams And Holds Double Values
double[] exams = new double[examCount];
// Read In All Exam Scores. A For Loop Is Used Because You Know How Many Scores There Are
for (int i = 0; i < examCount; i++)
{
System.out.print("Exam Score: ");
exams[i] = input.nextDouble();
}
// Print Out All Of The Scores
for (int i = 0; i < examCount; i++)
System.out.println("Exam #" + (i+1) + "\t" + exams[i]);
// Sum All Of The Exam Scores
for (int i = 0; i < examCount; i++)
examSum += exams[i];
// Print Out An Average Of All Of The Scores
System.out.println("Exam Average: " + examSum / examCount);
}
}
``` |
45,295,081 | Data set:

For the above data set I want to count the number of different entries in the fourth column. I have code in Python but not able to implement it in Java using Spark.
Python code:
```
user_data = sc.textFile(dataSet path)
//counting number of occupations
num_occupations = user_fields.map(lambda fields:
fields[3]).distinct().count()
``` | 2017/07/25 | [
"https://Stackoverflow.com/questions/45295081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8361502/"
] | You can create a custom `IHttpActionResult` which decorates a real one but exposes a way to manipulate the response:
```
public class CustomResult : IHttpActionResult
{
private readonly IHttpActionResult _decorated;
private readonly Action<HttpResponseMessage> _response;
public CustomResult(IHttpActionResult decorated, Action<HttpResponseMessage> response)
{
_decorated = decorated;
_response = response;
}
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = await _decorated.ExecuteAsync(cancellationToken);
_response(response);
return response;
}
}
```
Then use this in your action:
```
return new CustomResult(Content(HttpStatusCode.OK, loginResponse), res => res.Headers.AddCookies(new []{ cookie}));
``` | You can add header by using this code:
```
HttpContext.Current.Response.AppendHeader("Some-Header", value);
```
or this
```
response.Headers.Add("Some-Header", value);
``` |
45,295,081 | Data set:

For the above data set I want to count the number of different entries in the fourth column. I have code in Python but not able to implement it in Java using Spark.
Python code:
```
user_data = sc.textFile(dataSet path)
//counting number of occupations
num_occupations = user_fields.map(lambda fields:
fields[3]).distinct().count()
``` | 2017/07/25 | [
"https://Stackoverflow.com/questions/45295081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8361502/"
] | You can continue to use the `HttpResponseMessage` as you are accustom to and update the header. After which you can use the `IHttpActionResult ResponseMessage(HttpResponseMessage)` method to convert to `IHttpActionResult`
Simple example
```
public class MyApiController : ApiController {
public IHttpActionResult MyExampleAction() {
var LoginResponse = new object();//Replace with your model
var cookie = new CookieHeaderValue("name", "value");//Replace with your cookie
//Create response as usual
var response = Request.CreateResponse(System.Net.HttpStatusCode.OK, LoginResponse);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Headers.AddCookies(new[] { cookie });
//Use ResponseMessage to convert it to IHttpActionResult
return ResponseMessage(response);
}
}
``` | You can add header by using this code:
```
HttpContext.Current.Response.AppendHeader("Some-Header", value);
```
or this
```
response.Headers.Add("Some-Header", value);
``` |
59,781,296 | Why would I need to create a blob snapshot and incur additional cost if Azure already provides GRS(Geo redundant storage) or ZRS (Zone redundant storage)? | 2020/01/17 | [
"https://Stackoverflow.com/questions/59781296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1545193/"
] | Redundancy (ZRS/GRS/RAGRS) provides means to achieve high availability of your resources (blobs in your scenario). By enabling redundancy you are ensuring that a copy of your blob is available in another region/zone in case primary region/zone is not available. It also ensures against data corruption of the primary blob.
When you take a snapshot of your blob, a readonly copy of that blob in its current state is created and stored. If needed, you can restore a blob from a snapshot. This scenario is well suited if you want to store different versions of the same blob.
However, **please keep in mind that neither redundancy nor snapshot is backup** because if you delete base blob, all the snapshots associated with that blob are deleted and all the copies of that blob available in other zones/regions are deleted as well. | I guess you need to understand the difference between **Backup** and **Redundancy**.
Backups make sure if something is lost, corrupted or stolen, that a copy of the data is available at your disposal.
Redundancy makes sure that if something fails—your computer fails, a drive gets fried, or a server freezes and you are able to work regardless of the problem. Redundancy means that all your changes are replicated to another location. In case of a failover, your slave can theoretically function as a master and serve the (hopefully) latest state of your file system. |
59,781,296 | Why would I need to create a blob snapshot and incur additional cost if Azure already provides GRS(Geo redundant storage) or ZRS (Zone redundant storage)? | 2020/01/17 | [
"https://Stackoverflow.com/questions/59781296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1545193/"
] | I guess you need to understand the difference between **Backup** and **Redundancy**.
Backups make sure if something is lost, corrupted or stolen, that a copy of the data is available at your disposal.
Redundancy makes sure that if something fails—your computer fails, a drive gets fried, or a server freezes and you are able to work regardless of the problem. Redundancy means that all your changes are replicated to another location. In case of a failover, your slave can theoretically function as a master and serve the (hopefully) latest state of your file system. | You could also turn soft delete on. That would keep a copy of every blob for every change made to it, even if someone deletes it. Then you set the retention period for those blobs so they would be automatically removed after some period of time.
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-soft-delete> |
59,781,296 | Why would I need to create a blob snapshot and incur additional cost if Azure already provides GRS(Geo redundant storage) or ZRS (Zone redundant storage)? | 2020/01/17 | [
"https://Stackoverflow.com/questions/59781296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1545193/"
] | Redundancy (ZRS/GRS/RAGRS) provides means to achieve high availability of your resources (blobs in your scenario). By enabling redundancy you are ensuring that a copy of your blob is available in another region/zone in case primary region/zone is not available. It also ensures against data corruption of the primary blob.
When you take a snapshot of your blob, a readonly copy of that blob in its current state is created and stored. If needed, you can restore a blob from a snapshot. This scenario is well suited if you want to store different versions of the same blob.
However, **please keep in mind that neither redundancy nor snapshot is backup** because if you delete base blob, all the snapshots associated with that blob are deleted and all the copies of that blob available in other zones/regions are deleted as well. | You could also turn soft delete on. That would keep a copy of every blob for every change made to it, even if someone deletes it. Then you set the retention period for those blobs so they would be automatically removed after some period of time.
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-soft-delete> |
51,215,821 | I'm trying to invert and flip a two-dimensional array, but something goes wrong! Flipping works ok, but inverting is not.
Can't find a mistake right here:
```
public int[][] flipAndInvert(int[][] A) {
int row = -1;
int col = -1;
int[][] arr = A;
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length - 1; j >= 0; j--) {
col++;
arr[row][col] = A[i][j];
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 1) {
arr[i][j] = 0;
} else {
arr[i][j] = 1;
}
}
}
return arr;
}
int[][] A = { { 0, 1, 1 },{ 0, 0, 1 },{ 0, 0, 0 } };
```
After proceeding the output should be:
After inverting:
{1,1,0},{1,0,0},{0,0,0}
After flipping:
{0,0,1,},{0,1,1},{1,1,1}
Thanks to all a lot, the problem was here:
int[][] arr = A;
The reference of the array is being passed to arr. | 2018/07/06 | [
"https://Stackoverflow.com/questions/51215821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10043854/"
] | What I think is that since you are using this line:
```
int[][] arr = A;
```
The reference of the array is being passed to arr, and hence the line:
```
arr[row][col] = A[i][j];
```
is equivalent to:
```
A[row][col] = A[i][j];
```
as arr has an reference to A and they both now refer to the same memory location (or they are both different names to a single variable)
You can fix this by either using the new keyword with arr and then initializing it:
```
int[][] arr = new int[someRows][someCols];
//use for loop to assign the value to each element of arr
```
Or you can run the for loop till arr[i].length/2 - 1:
```
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length / 2 - 1; j >= 0; j--) { //here changed arr[i].length to arr[i].length / 2
col++;
arr[row][col] = A[i][j]; //for this you do not need arr and you can directly work on A and return it
}
}
``` | Using apache commons lang:
```
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 3 * i;
matrix[i][1] = 3 * i + 1;
matrix[i][2] = 3 * i + 2;
}
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
ArrayUtils.reverse(matrix);
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
```
Hope this helps. |
51,215,821 | I'm trying to invert and flip a two-dimensional array, but something goes wrong! Flipping works ok, but inverting is not.
Can't find a mistake right here:
```
public int[][] flipAndInvert(int[][] A) {
int row = -1;
int col = -1;
int[][] arr = A;
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length - 1; j >= 0; j--) {
col++;
arr[row][col] = A[i][j];
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 1) {
arr[i][j] = 0;
} else {
arr[i][j] = 1;
}
}
}
return arr;
}
int[][] A = { { 0, 1, 1 },{ 0, 0, 1 },{ 0, 0, 0 } };
```
After proceeding the output should be:
After inverting:
{1,1,0},{1,0,0},{0,0,0}
After flipping:
{0,0,1,},{0,1,1},{1,1,1}
Thanks to all a lot, the problem was here:
int[][] arr = A;
The reference of the array is being passed to arr. | 2018/07/06 | [
"https://Stackoverflow.com/questions/51215821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10043854/"
] | The problem of your code should be this line:
```
int[][] arr = A;
```
You are assigning the reference of array `A` to `arr` and from then when you modify one you modify both of the arrays or better they are modified together because they refer to the same address. | Using apache commons lang:
```
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 3 * i;
matrix[i][1] = 3 * i + 1;
matrix[i][2] = 3 * i + 2;
}
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
ArrayUtils.reverse(matrix);
System.out.println(Arrays.toString(matrix[0]));
System.out.println(Arrays.toString(matrix[1]));
System.out.println(Arrays.toString(matrix[2]));
```
Hope this helps. |
51,215,821 | I'm trying to invert and flip a two-dimensional array, but something goes wrong! Flipping works ok, but inverting is not.
Can't find a mistake right here:
```
public int[][] flipAndInvert(int[][] A) {
int row = -1;
int col = -1;
int[][] arr = A;
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length - 1; j >= 0; j--) {
col++;
arr[row][col] = A[i][j];
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 1) {
arr[i][j] = 0;
} else {
arr[i][j] = 1;
}
}
}
return arr;
}
int[][] A = { { 0, 1, 1 },{ 0, 0, 1 },{ 0, 0, 0 } };
```
After proceeding the output should be:
After inverting:
{1,1,0},{1,0,0},{0,0,0}
After flipping:
{0,0,1,},{0,1,1},{1,1,1}
Thanks to all a lot, the problem was here:
int[][] arr = A;
The reference of the array is being passed to arr. | 2018/07/06 | [
"https://Stackoverflow.com/questions/51215821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10043854/"
] | What I think is that since you are using this line:
```
int[][] arr = A;
```
The reference of the array is being passed to arr, and hence the line:
```
arr[row][col] = A[i][j];
```
is equivalent to:
```
A[row][col] = A[i][j];
```
as arr has an reference to A and they both now refer to the same memory location (or they are both different names to a single variable)
You can fix this by either using the new keyword with arr and then initializing it:
```
int[][] arr = new int[someRows][someCols];
//use for loop to assign the value to each element of arr
```
Or you can run the for loop till arr[i].length/2 - 1:
```
for (int i = 0; i < arr.length; i++) {
row++;
col = -1;
for (int j = arr[i].length / 2 - 1; j >= 0; j--) { //here changed arr[i].length to arr[i].length / 2
col++;
arr[row][col] = A[i][j]; //for this you do not need arr and you can directly work on A and return it
}
}
``` | The problem of your code should be this line:
```
int[][] arr = A;
```
You are assigning the reference of array `A` to `arr` and from then when you modify one you modify both of the arrays or better they are modified together because they refer to the same address. |
8,829,284 | I have no idea why this error is occurring after debugging the project even though the codes are default.
Controller
```
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
```
View
```
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
Hi
</div>
</body>
```
Somehow or rather, after debugging, the Requested URL is always /Views/Home/Index.cshtml but accessing Home via browser is fine. (http://localhost:58323/home)
I googled and solution hints that the problem lies in global. But thats weird, I dont remember making any changes to it.
Global
```
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
```
Appreciate any help. Thank you | 2012/01/12 | [
"https://Stackoverflow.com/questions/8829284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/502908/"
] | I think you just have your visual studio settings set so that the view is set to the start page. Right click on the project and go to properties, then to the web tab. Is the 'specific page' radio button selected with 'Views/Home/Index.cshtml' set as the value? Change it to use a start url. Personally I prefer not to have the debugger start up a browser and use Don't open a page. | Right click your web project -> Properties -> Web
check that you have the start action set to Specific Page with no value in the field.
My guess is that you have the start action set to current page. |
8,829,284 | I have no idea why this error is occurring after debugging the project even though the codes are default.
Controller
```
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
```
View
```
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
Hi
</div>
</body>
```
Somehow or rather, after debugging, the Requested URL is always /Views/Home/Index.cshtml but accessing Home via browser is fine. (http://localhost:58323/home)
I googled and solution hints that the problem lies in global. But thats weird, I dont remember making any changes to it.
Global
```
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
```
Appreciate any help. Thank you | 2012/01/12 | [
"https://Stackoverflow.com/questions/8829284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/502908/"
] | I think you just have your visual studio settings set so that the view is set to the start page. Right click on the project and go to properties, then to the web tab. Is the 'specific page' radio button selected with 'Views/Home/Index.cshtml' set as the value? Change it to use a start url. Personally I prefer not to have the debugger start up a browser and use Don't open a page. | This error might even cause if the hierarchy of the folder structure is incorrect in Views folder.
If you are adding views by right-click on Views folder.The new view added might be incorrectly placed in the folder hierarchy.
The way to troubleshoot the problem is:
Consider a view named index.ascx which is supposed to be linked to a Controller named HomeController.
Under the Views folder there should be a folder name Home (relating to the Controller) and the
index.ascx should reside in Home folder.
The best possible way to add view is to right-click just beside the public method which will show a Create View option in context-menu.If you crate view in such manner then folder hierarchy is automatically created. |
8,829,284 | I have no idea why this error is occurring after debugging the project even though the codes are default.
Controller
```
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
```
View
```
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
Hi
</div>
</body>
```
Somehow or rather, after debugging, the Requested URL is always /Views/Home/Index.cshtml but accessing Home via browser is fine. (http://localhost:58323/home)
I googled and solution hints that the problem lies in global. But thats weird, I dont remember making any changes to it.
Global
```
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
```
Appreciate any help. Thank you | 2012/01/12 | [
"https://Stackoverflow.com/questions/8829284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/502908/"
] | Right click your web project -> Properties -> Web
check that you have the start action set to Specific Page with no value in the field.
My guess is that you have the start action set to current page. | This error might even cause if the hierarchy of the folder structure is incorrect in Views folder.
If you are adding views by right-click on Views folder.The new view added might be incorrectly placed in the folder hierarchy.
The way to troubleshoot the problem is:
Consider a view named index.ascx which is supposed to be linked to a Controller named HomeController.
Under the Views folder there should be a folder name Home (relating to the Controller) and the
index.ascx should reside in Home folder.
The best possible way to add view is to right-click just beside the public method which will show a Create View option in context-menu.If you crate view in such manner then folder hierarchy is automatically created. |
47,056,387 | HTML5 audio does not seem to work on Firefox and Opera:
```
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
```
You can test it from [here](https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_audio_all).
Any ideas why and how to make it cross browsers?
I am on Ubuntu 17.10. | 2017/11/01 | [
"https://Stackoverflow.com/questions/47056387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413225/"
] | * Add this hibernate property in your `application.properties` file:
```
spring.jpa.hibernate.ddl-auto=create-drop
```
Or
```
spring.jpa.hibernate.ddl-auto=create
```
From [documentation](http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl) :
>
> **create-drop**
>
>
> Drop the schema and recreate it on SessionFactory startup.
> Additionally, drop the schema on SessionFactory shutdown.
>
>
> **create**
>
>
> Database dropping will be generated followed by database creation.
>
>
>
You may think twice before [using `hibernate.ddl-auto` in production](https://stackoverflow.com/questions/221379/hibernate-hbm2ddl-autoupdate-in-production).
* Rename `schema.sql` to `import.sql` or to `data.sql`, so spring boot [will initialize the database](https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-initialize-a-database-using-hibernate) (with data, by running your sql file) after its creation. | The thing that worked for me was adding this line to **application.properties**:
```
spring.datasource.initialize=false
``` |
47,056,387 | HTML5 audio does not seem to work on Firefox and Opera:
```
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
```
You can test it from [here](https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_audio_all).
Any ideas why and how to make it cross browsers?
I am on Ubuntu 17.10. | 2017/11/01 | [
"https://Stackoverflow.com/questions/47056387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413225/"
] | * Add this hibernate property in your `application.properties` file:
```
spring.jpa.hibernate.ddl-auto=create-drop
```
Or
```
spring.jpa.hibernate.ddl-auto=create
```
From [documentation](http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl) :
>
> **create-drop**
>
>
> Drop the schema and recreate it on SessionFactory startup.
> Additionally, drop the schema on SessionFactory shutdown.
>
>
> **create**
>
>
> Database dropping will be generated followed by database creation.
>
>
>
You may think twice before [using `hibernate.ddl-auto` in production](https://stackoverflow.com/questions/221379/hibernate-hbm2ddl-autoupdate-in-production).
* Rename `schema.sql` to `import.sql` or to `data.sql`, so spring boot [will initialize the database](https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-initialize-a-database-using-hibernate) (with data, by running your sql file) after its creation. | One of the reason could be, if your entity classes are in a completely different package than your main application package.
This could prevent your entities from being scanned. As there would be no scanned entities, no tables would be inserted to your database, meaning you wouldn't even see any obvious exceptions or error messages. Then the missing tables could cause the exception you pasted here.
If that is the case, you shall use @EntityScan annotation in your main application. For example
```
@EntityScan("your.package.with.annotated.entities")
public class SomeClassInOtherPackage{
// ...
}
``` |
47,056,387 | HTML5 audio does not seem to work on Firefox and Opera:
```
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
```
You can test it from [here](https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_audio_all).
Any ideas why and how to make it cross browsers?
I am on Ubuntu 17.10. | 2017/11/01 | [
"https://Stackoverflow.com/questions/47056387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413225/"
] | * Add this hibernate property in your `application.properties` file:
```
spring.jpa.hibernate.ddl-auto=create-drop
```
Or
```
spring.jpa.hibernate.ddl-auto=create
```
From [documentation](http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl) :
>
> **create-drop**
>
>
> Drop the schema and recreate it on SessionFactory startup.
> Additionally, drop the schema on SessionFactory shutdown.
>
>
> **create**
>
>
> Database dropping will be generated followed by database creation.
>
>
>
You may think twice before [using `hibernate.ddl-auto` in production](https://stackoverflow.com/questions/221379/hibernate-hbm2ddl-autoupdate-in-production).
* Rename `schema.sql` to `import.sql` or to `data.sql`, so spring boot [will initialize the database](https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-initialize-a-database-using-hibernate) (with data, by running your sql file) after its creation. | The data.sql gets initialized first in spring boot. So, it tries to insert the data before creating the table by @Entity...
To solve this issue, add this code to your application.properties.
*spring.jpa.defer-datasource-initialization = true* |
47,056,387 | HTML5 audio does not seem to work on Firefox and Opera:
```
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
```
You can test it from [here](https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_audio_all).
Any ideas why and how to make it cross browsers?
I am on Ubuntu 17.10. | 2017/11/01 | [
"https://Stackoverflow.com/questions/47056387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413225/"
] | The thing that worked for me was adding this line to **application.properties**:
```
spring.datasource.initialize=false
``` | The data.sql gets initialized first in spring boot. So, it tries to insert the data before creating the table by @Entity...
To solve this issue, add this code to your application.properties.
*spring.jpa.defer-datasource-initialization = true* |
47,056,387 | HTML5 audio does not seem to work on Firefox and Opera:
```
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
```
You can test it from [here](https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_audio_all).
Any ideas why and how to make it cross browsers?
I am on Ubuntu 17.10. | 2017/11/01 | [
"https://Stackoverflow.com/questions/47056387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413225/"
] | One of the reason could be, if your entity classes are in a completely different package than your main application package.
This could prevent your entities from being scanned. As there would be no scanned entities, no tables would be inserted to your database, meaning you wouldn't even see any obvious exceptions or error messages. Then the missing tables could cause the exception you pasted here.
If that is the case, you shall use @EntityScan annotation in your main application. For example
```
@EntityScan("your.package.with.annotated.entities")
public class SomeClassInOtherPackage{
// ...
}
``` | The data.sql gets initialized first in spring boot. So, it tries to insert the data before creating the table by @Entity...
To solve this issue, add this code to your application.properties.
*spring.jpa.defer-datasource-initialization = true* |
622,888 | I am using in my document the `concmath` package, but there is no blackboard bold font linked to the command `\mathbb{}` with this font package. I already asked this question elsewhere and I got this solution :
```
\makeatletter
\def\afterfi#1#2\fi{\fi#1}
\def\map#1#2{\mapA{}#1#2\@nnil}
\def\mapA#1#2#3{\ifx\@nnil#3\empty \afterfi{#1}\else \afterfi {\mapA{#1#2{#3}}#2}\fi}
\protected\def\mathbb#1{\leavevmode\textup{\map\mathbbA{#1}}}
\def\mathbbA#1{\setbox\z@\hbox{#1}\copy\z@\kern-\wd\z@ \kern.13em\box\z@}
\makeatother
$u=\{u(t)\}_{t\in\mathbb R^2} \quad \mathbb{NZQIRCOSABC}$
```
which slightly shifts the letter to produce the blackboard font, but this looks horrible for some letters.
**Is there a way to generate a decent looking blackboard bold font for concrete ?**
Thank you in advance for any advice. | 2021/11/17 | [
"https://tex.stackexchange.com/questions/622888",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/248264/"
] | An alternative is to use the [`ccfonts`](http://mirrors.ctan.org/macros/latex/contrib/ccfonts/ccfonts.pdf) package, which is still being updated. The `concmath` package is from last century.
```
\usepackage[T1]{fontenc}
\usepackage{amssymb}
\usepackage{ccfonts}
```
loads either the AMS or Concrete version of all the standard math alphabets.
Otherwise, you can pick a blackboard font you like from [`mathalpha`](http://mirrors.ctan.org/macros/latex/contrib/mathalpha/doc/mathalpha-doc.pdf) and load that after `ccfonts` or `concmath`.
Be aware, either of these will give you pixelated METAFONT math fonts, unless you pay money for the Micropress Concrete Math font in Type 1 format. You don’t need to do that, though: either you’re publishing in a journal that licenses the font, or you’re free to use a modern TeX engine that supports OpenType.
In LuaLaTeX or XeLaTeX, you might try pairing Concrete with the math symbols from the slab serif font GFS Neohellenic:
```
\documentclass{article}
\usepackage[math-style=upright]{unicode-math}
\usepackage[paperwidth=10cm]{geometry} % Format a MWE for TeX.SX
\setmainfont{CMU Concrete}[
Ligatures=Common,
UprightFont=cmunorm.otf,
BoldFont=cmunobx.otf,
ItalicFont=cmunoti.otf,
BoldItalicFont=cmunobi.otf ]
\setmathfont{GFS Neohellenic Math}[Scale=MatchLowercase]
\setmathfont{cmunoti.otf}[range=it]
\setmathfont{cmunorm.otf}[range=up]
\begin{document}
\noindent%
Let \( (x,y) \in \mathbb{R} \times \mathbb{R} \)
such that \( \sqrt{x^2 + y^2} \leq \varepsilon \).
\end{document}
```
[](https://i.stack.imgur.com/m5G1p.png)
Or load `unicode-math` without `math-style=upright` to get italic math symbols more like the legacy packages. Changing the option to `math-style=ISO` will slant your upright Greek letters, too.
```
\documentclass{article}
\usepackage[math-style=ISO]{unicode-math}
\usepackage[paperwidth=10cm]{geometry} % Format a MWE for TeX.SX
\setmainfont{CMU Concrete}[
Ligatures=Common,
UprightFont=cmunorm.otf,
BoldFont=cmunobx.otf,
ItalicFont=cmunoti.otf,
BoldItalicFont=cmunobi.otf ]
\setmathfont{GFS Neohellenic Math}[Scale=MatchLowercase]
\setmathfont{cmunoti.otf}[range=it]
\setmathfont{cmunorm.otf}[range=up]
\begin{document}
\noindent%
Let \( (x,y) \in \mathbb{R} \times \mathbb{R} \)
such that \( \sqrt{x^2 + y^2} \leq \varepsilon \).
\end{document}
```
[](https://i.stack.imgur.com/m3LbT.png)
In either case, you can swap in a different blackboard bold alphabet with a command like
```
\setmathfont{STIX Two Math}[range=bb,
Scale=MatchUppercase]
``` | From the documentation:
>
> The ‘amsfonts’ and ‘amssymb’ options: These options provide the functionality of the standard ‘amsfonts’ and ‘amssymb’ packages, but using the Concrete
> versions of the AMS symbol fonts and math alphabets.
>
>
>
```
\documentclass{article}
\usepackage[amssymb]{concmath}
\begin{document}
$\mathbb{ABCDEFGHIJKLMNOPQRSTUVWXYZ}$
\end{document}
```
[](https://i.stack.imgur.com/8tmdn.png) |
51,352,929 | today, suddendly, all my **Android Emulators** (on Win10 / IntelliJ IDEA),
started complaining about a missing library.
When i launch any emulator, during loading, i read on the console log:
**Emulator: Could not load library 'WinHvPlatform.dll'**
then, the emulator starts and seems to run OK.
But... does anyone have an idea what it could be the cause ?
What is that library ? | 2018/07/15 | [
"https://Stackoverflow.com/questions/51352929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8846877/"
] | Using a variable to check if header is added or not may be helpful. If header added it will not add second times
```
header_added = False
for team in team_list:
do_some stuff
with open('MLB_Active_Roster.csv', 'a', newline='') as fp:
f = csv.writer(fp)
if not header_added:
f.writerow(['Name','ID','Number','Hand','Height','Weight','DOB','Team'])
header_added = True
f.writerows(zip(names, ids, number, handedness, height, weight, DOB, team))
``` | Another method would be to simply do it before the for loop so you do not have to check if already written.
```
import requests
import csv
from bs4 import BeautifulSoup
team_list={'yankees','redsox'}
with open('MLB_Active_Roster.csv', 'w', newline='') as fp:
f = csv.writer(fp)
f.writerow(['Name','ID','Number','Hand','Height','Weight','DOB','Team'])
for team in team_list:
do_your_bs4_and_parsing_stuff
with open('MLB_Active_Roster.csv', 'a', newline='') as fp:
f = csv.writer(fp)
f.writerows(zip(names, ids, number, handedness, height, weight, DOB, team))
```
You can also open the document just once instead of three times as well
```
import requests
import csv
from bs4 import BeautifulSoup
team_list={'yankees','redsox'}
with open('MLB_Active_Roster.csv', 'w', newline='') as fp:
f = csv.writer(fp)
f.writerow(['Name','ID','Number','Hand','Height','Weight','DOB','Team'])
for team in team_list:
do_your_bs4_and_parsing_stuff
f.writerows(zip(names, ids, number, handedness, height, weight, DOB, team))
``` |
51,352,929 | today, suddendly, all my **Android Emulators** (on Win10 / IntelliJ IDEA),
started complaining about a missing library.
When i launch any emulator, during loading, i read on the console log:
**Emulator: Could not load library 'WinHvPlatform.dll'**
then, the emulator starts and seems to run OK.
But... does anyone have an idea what it could be the cause ?
What is that library ? | 2018/07/15 | [
"https://Stackoverflow.com/questions/51352929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8846877/"
] | Using a variable to check if header is added or not may be helpful. If header added it will not add second times
```
header_added = False
for team in team_list:
do_some stuff
with open('MLB_Active_Roster.csv', 'a', newline='') as fp:
f = csv.writer(fp)
if not header_added:
f.writerow(['Name','ID','Number','Hand','Height','Weight','DOB','Team'])
header_added = True
f.writerows(zip(names, ids, number, handedness, height, weight, DOB, team))
``` | Just write the header before the loop, and have the loop within the `with` context manager:
```
import requests
import csv
from bs4 import BeautifulSoup
team_list = {'yankees', 'redsox'}
headers = ['Name', 'ID', 'Number', 'Hand', 'Height', 'Weight', 'DOB', 'Team']
# 1. wrap everything in context manager
with open('MLB_Active_Roster.csv', 'a', newline='') as fp:
f = csv.writer(fp)
# 2. write headers before anything else
f.writerow(headers)
# 3. now process the loop
for team in team_list:
# Do everything else...
```
You could also define your headers similarily to `team_list` outside the loop, which leads to cleaner code. |
51,352,929 | today, suddendly, all my **Android Emulators** (on Win10 / IntelliJ IDEA),
started complaining about a missing library.
When i launch any emulator, during loading, i read on the console log:
**Emulator: Could not load library 'WinHvPlatform.dll'**
then, the emulator starts and seems to run OK.
But... does anyone have an idea what it could be the cause ?
What is that library ? | 2018/07/15 | [
"https://Stackoverflow.com/questions/51352929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8846877/"
] | Another method would be to simply do it before the for loop so you do not have to check if already written.
```
import requests
import csv
from bs4 import BeautifulSoup
team_list={'yankees','redsox'}
with open('MLB_Active_Roster.csv', 'w', newline='') as fp:
f = csv.writer(fp)
f.writerow(['Name','ID','Number','Hand','Height','Weight','DOB','Team'])
for team in team_list:
do_your_bs4_and_parsing_stuff
with open('MLB_Active_Roster.csv', 'a', newline='') as fp:
f = csv.writer(fp)
f.writerows(zip(names, ids, number, handedness, height, weight, DOB, team))
```
You can also open the document just once instead of three times as well
```
import requests
import csv
from bs4 import BeautifulSoup
team_list={'yankees','redsox'}
with open('MLB_Active_Roster.csv', 'w', newline='') as fp:
f = csv.writer(fp)
f.writerow(['Name','ID','Number','Hand','Height','Weight','DOB','Team'])
for team in team_list:
do_your_bs4_and_parsing_stuff
f.writerows(zip(names, ids, number, handedness, height, weight, DOB, team))
``` | Just write the header before the loop, and have the loop within the `with` context manager:
```
import requests
import csv
from bs4 import BeautifulSoup
team_list = {'yankees', 'redsox'}
headers = ['Name', 'ID', 'Number', 'Hand', 'Height', 'Weight', 'DOB', 'Team']
# 1. wrap everything in context manager
with open('MLB_Active_Roster.csv', 'a', newline='') as fp:
f = csv.writer(fp)
# 2. write headers before anything else
f.writerow(headers)
# 3. now process the loop
for team in team_list:
# Do everything else...
```
You could also define your headers similarily to `team_list` outside the loop, which leads to cleaner code. |
53,751,987 | I have a `.world` file in ROS for gazebo simulation which is an XML file.
How can I put on a dynamic home path instead of the static path in `<uri>` tag?
---
Here's my simplified `.world` file:
```
<?xml version="1.0" ?>
<sdf version='1.5'>
<world name='default'>
<visual name='base_link_visual_front_sonar'>
<pose>0.109 0 0.209 0 -0 0</pose>
<geometry>
<mesh>
<uri>/home/agn/catkin_ws/src/description/meshes/sonar.stl</uri> <!--Note-->
</mesh>
</geometry>
</visual>
</world>
</sdf>
```
---
How can I use `$HOME` instead of `/home/agn`?
I tried the following cases with the failed results:
```
<uri>~/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>$HOME/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>"$HOME/catkin_ws/src/description/meshes/sonar.stl"</uri>
<uri>${HOME}/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>"${HOME}/catkin_ws/src/description/meshes/sonar.stl"</uri>
<uri>"${sys:user.home}/catkin_ws/src/description/meshes/sonar.stl"</uri>
<uri>${sys:user.home}/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>${user.home}/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>"${user.home}/catkin_ws/src/description/meshes/sonar.stl"</uri>
``` | 2018/12/12 | [
"https://Stackoverflow.com/questions/53751987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3702377/"
] | Based on SCouto answer, I give you the complete solution that worked for me:
```
def myUDF: UserDefinedFunction = udf(
(s1: String, s2: String) => {
val splitted1 = s1.split(",")
val splitted2 = s2.split(",")
splitted1.intersect(splitted2).length
})
val spark = SparkSession.builder().master("local").getOrCreate()
import spark.implicits._
val df = Seq(("Author1,Author2,Author3","Author2,Author3,Author1")).toDF("source","target")
df.show(false)
+-----------------------+-----------------------+
|source |target |
+-----------------------+-----------------------+
|Author1,Author2,Author3|Author2,Author3,Author1|
+-----------------------+-----------------------+
val newDF: DataFrame = df.withColumn("nCommonAuthors", myUDF('source,'target))
newDF.show(false)
+-----------------------+-----------------------+--------------+
|source |target |nCommonAuthors|
+-----------------------+-----------------------+--------------+
|Author1,Author2,Author3|Author2,Author3,Author1|3 |
+-----------------------+-----------------------+--------------+
``` | That error means that your udf is returning unit ( no return at all, as void un Java )
Try this. You are applying the intersect over the original s1 and S2 rather than over the splitted ones.
`def myUDF = udf((s1: String, s2: String) =>{`
```
val splitted1 = s1.split(",")
val splitted2= s2.split(",")
splitted1.intersect(splitted2).length
```
`}
)` |
53,751,987 | I have a `.world` file in ROS for gazebo simulation which is an XML file.
How can I put on a dynamic home path instead of the static path in `<uri>` tag?
---
Here's my simplified `.world` file:
```
<?xml version="1.0" ?>
<sdf version='1.5'>
<world name='default'>
<visual name='base_link_visual_front_sonar'>
<pose>0.109 0 0.209 0 -0 0</pose>
<geometry>
<mesh>
<uri>/home/agn/catkin_ws/src/description/meshes/sonar.stl</uri> <!--Note-->
</mesh>
</geometry>
</visual>
</world>
</sdf>
```
---
How can I use `$HOME` instead of `/home/agn`?
I tried the following cases with the failed results:
```
<uri>~/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>$HOME/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>"$HOME/catkin_ws/src/description/meshes/sonar.stl"</uri>
<uri>${HOME}/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>"${HOME}/catkin_ws/src/description/meshes/sonar.stl"</uri>
<uri>"${sys:user.home}/catkin_ws/src/description/meshes/sonar.stl"</uri>
<uri>${sys:user.home}/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>${user.home}/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>"${user.home}/catkin_ws/src/description/meshes/sonar.stl"</uri>
``` | 2018/12/12 | [
"https://Stackoverflow.com/questions/53751987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3702377/"
] | Unless I misunderstood your problem, there are standard functions that can help you (so you don't have to write a UDF), i.e. `split` and `array_intersect`.
Given the following dataset:
```
val df = Seq(("Author1,Author2,Author3","Author2,Author3"))
.toDF("source","target")
scala> df.show(false)
+-----------------------+---------------+
|source |target |
+-----------------------+---------------+
|Author1,Author2,Author3|Author2,Author3|
+-----------------------+---------------+
```
You could write the following structured query:
```
val intersect = array_intersect(split('source, ","), split('target, ","))
val solution = df.select(intersect as "common_elements")
scala> solution.show(false)
+------------------+
|common_elements |
+------------------+
|[Author2, Author3]|
+------------------+
``` | That error means that your udf is returning unit ( no return at all, as void un Java )
Try this. You are applying the intersect over the original s1 and S2 rather than over the splitted ones.
`def myUDF = udf((s1: String, s2: String) =>{`
```
val splitted1 = s1.split(",")
val splitted2= s2.split(",")
splitted1.intersect(splitted2).length
```
`}
)` |
53,751,987 | I have a `.world` file in ROS for gazebo simulation which is an XML file.
How can I put on a dynamic home path instead of the static path in `<uri>` tag?
---
Here's my simplified `.world` file:
```
<?xml version="1.0" ?>
<sdf version='1.5'>
<world name='default'>
<visual name='base_link_visual_front_sonar'>
<pose>0.109 0 0.209 0 -0 0</pose>
<geometry>
<mesh>
<uri>/home/agn/catkin_ws/src/description/meshes/sonar.stl</uri> <!--Note-->
</mesh>
</geometry>
</visual>
</world>
</sdf>
```
---
How can I use `$HOME` instead of `/home/agn`?
I tried the following cases with the failed results:
```
<uri>~/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>$HOME/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>"$HOME/catkin_ws/src/description/meshes/sonar.stl"</uri>
<uri>${HOME}/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>"${HOME}/catkin_ws/src/description/meshes/sonar.stl"</uri>
<uri>"${sys:user.home}/catkin_ws/src/description/meshes/sonar.stl"</uri>
<uri>${sys:user.home}/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>${user.home}/catkin_ws/src/description/meshes/sonar.stl</uri>
<uri>"${user.home}/catkin_ws/src/description/meshes/sonar.stl"</uri>
``` | 2018/12/12 | [
"https://Stackoverflow.com/questions/53751987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3702377/"
] | Unless I misunderstood your problem, there are standard functions that can help you (so you don't have to write a UDF), i.e. `split` and `array_intersect`.
Given the following dataset:
```
val df = Seq(("Author1,Author2,Author3","Author2,Author3"))
.toDF("source","target")
scala> df.show(false)
+-----------------------+---------------+
|source |target |
+-----------------------+---------------+
|Author1,Author2,Author3|Author2,Author3|
+-----------------------+---------------+
```
You could write the following structured query:
```
val intersect = array_intersect(split('source, ","), split('target, ","))
val solution = df.select(intersect as "common_elements")
scala> solution.show(false)
+------------------+
|common_elements |
+------------------+
|[Author2, Author3]|
+------------------+
``` | Based on SCouto answer, I give you the complete solution that worked for me:
```
def myUDF: UserDefinedFunction = udf(
(s1: String, s2: String) => {
val splitted1 = s1.split(",")
val splitted2 = s2.split(",")
splitted1.intersect(splitted2).length
})
val spark = SparkSession.builder().master("local").getOrCreate()
import spark.implicits._
val df = Seq(("Author1,Author2,Author3","Author2,Author3,Author1")).toDF("source","target")
df.show(false)
+-----------------------+-----------------------+
|source |target |
+-----------------------+-----------------------+
|Author1,Author2,Author3|Author2,Author3,Author1|
+-----------------------+-----------------------+
val newDF: DataFrame = df.withColumn("nCommonAuthors", myUDF('source,'target))
newDF.show(false)
+-----------------------+-----------------------+--------------+
|source |target |nCommonAuthors|
+-----------------------+-----------------------+--------------+
|Author1,Author2,Author3|Author2,Author3,Author1|3 |
+-----------------------+-----------------------+--------------+
``` |
38,213,701 | I'm trying in regular expression to not match if '-' is at the end of a string.
Here's a partial of my regex (this is looking at domain part of url, which can't have symbols at beginning or end, but can have '-' in middle of string:
```
(([A-Z0-9])([A-Z0-9-]){0,61}([A-Z0-9]?)[\.]){1,8}
```
This also has to match 1-character domains - that's why I have ? on the end character & 0,61 on the center part.
So, in short is there a regex code to prevent matching for '-' if it's at the end of the string? And if you can prevent it for beginning, then that would be great too.
Matched input: site.
Invalid input: -site. or site-. | 2016/07/05 | [
"https://Stackoverflow.com/questions/38213701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1429261/"
] | >
> in short is there a regex code to prevent matching for '-' if it's at the end of the string? And if you can prevent it for beginning, then that would be great too.
>
>
>
Yes you can use negative lookaheads for this:
```
/^(?!-|.*(\.[.-]|-\.|-$))(?:[A-Z0-9-]{0,62}\.){1,8}[A-Z0-9]{3}$/gim
```
[RegEx Demo](https://regex101.com/r/oN2jB0/10) | Try:
```
^(([A-Z0-9^-])([A-Z0-9-]){0,61}([A-Z0-9]?)[\.^-]){1,8}$
```
I'm not 100% sure it will work with JS regexes. The idea is: `^` matches beginning of string, `$` matches end, and `^-` in a character class means "anything not a hyphen". |
1,687,282 | I have Google admanager and Jquery and Jquery UI.
But it takes a long time to load the Jquery because Google Admanager.
I have about 30 banners in Google Admanager.
Anybody know how to get the Jquery load first?
Thanks | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1102592/"
] | I don't think it'll do your folding, but if you're using SQL Server I'd highly recommend [SQL Prompt](http://www.red-gate.com/products/SQL_Prompt/index.htm) which includes a command to reformat SQL. I've found this to be a massive help when debugging/understanding huge and unwieldy stored procedures. | Edit: Nevermind, it doesn't work. `)` isn't being treated as close. Leaving the answer so nobody else wastes their time trying it.
If you're willing to split the lines so there's only one open or close parenthesis on a line, you can use the User Define Language in Notepad++ and make `(` and `)`the folder open and close, respectively. You can also define the SQL keywords and comment delimiters so they get colored. Notepad++ has SQL built in of course, but the built in definition doesn't fold on parentheses. |
1,687,282 | I have Google admanager and Jquery and Jquery UI.
But it takes a long time to load the Jquery because Google Admanager.
I have about 30 banners in Google Admanager.
Anybody know how to get the Jquery load first?
Thanks | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1102592/"
] | I have a need to do a similar thing. I posted a request for comments and suggests (an RFC you could say). The link to it is here: [Stack Overflow](https://stackoverflow.com/questions/3701317/feature-request-for-a-text-editor-with-support-for-literate-programming-closed). I'm surprised its not a standard feature in most editors.. I guess the issue is that it's harder than it looks to parse delimited blocks of text out of a stream of characters. Maybe XML and CSS will make it easier to do thins type of thing in the future. | Edit: Nevermind, it doesn't work. `)` isn't being treated as close. Leaving the answer so nobody else wastes their time trying it.
If you're willing to split the lines so there's only one open or close parenthesis on a line, you can use the User Define Language in Notepad++ and make `(` and `)`the folder open and close, respectively. You can also define the SQL keywords and comment delimiters so they get colored. Notepad++ has SQL built in of course, but the built in definition doesn't fold on parentheses. |
1,687,282 | I have Google admanager and Jquery and Jquery UI.
But it takes a long time to load the Jquery because Google Admanager.
I have about 30 banners in Google Admanager.
Anybody know how to get the Jquery load first?
Thanks | 2009/11/06 | [
"https://Stackoverflow.com/questions/1687282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1102592/"
] | See [HideShow mode](http://www.emacswiki.org/emacs/HideShow "HideShow mode") for emacs, which does exactly what you want in lisp-mode. | Edit: Nevermind, it doesn't work. `)` isn't being treated as close. Leaving the answer so nobody else wastes their time trying it.
If you're willing to split the lines so there's only one open or close parenthesis on a line, you can use the User Define Language in Notepad++ and make `(` and `)`the folder open and close, respectively. You can also define the SQL keywords and comment delimiters so they get colored. Notepad++ has SQL built in of course, but the built in definition doesn't fold on parentheses. |
16,049,020 | I'm a beginner in PHP. In my code, i want the php script to be executed only when the submit button is clicked (set). So when the page is refreshed, the isset() function should return false. Here is the code for test.php
```
<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
else{
$username = "";
}
?>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="test.php">
<Input Type = "text" Value ="<?php print $username?>" Name ="username">
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</form>
</body>
</html>
```
After clicking the login button the script is executed and the output is "You are not a member", but when i refresh the page,the message from the script still remains on the screen. I believe isset() should return false until i click the button again? What's wrong with the code.
Thanks. | 2013/04/16 | [
"https://Stackoverflow.com/questions/16049020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1917222/"
] | Realized that my comment was really an answer...
When you "refresh", you refresh the page INCLUDING the POST data (since that was the last "request" made). You would have to re-enter the address of the page to clear it. Sometimes you see "do you really want to send this form again?" prompt when you refresh - this is why... | Refreshing the page will post the already posted form variables again so every time you refresh your page you are re submitting your form and by this you will have always the `isset` condition to true :)
I f you need more explaining tell me :) |
16,049,020 | I'm a beginner in PHP. In my code, i want the php script to be executed only when the submit button is clicked (set). So when the page is refreshed, the isset() function should return false. Here is the code for test.php
```
<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
else{
$username = "";
}
?>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="test.php">
<Input Type = "text" Value ="<?php print $username?>" Name ="username">
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</form>
</body>
</html>
```
After clicking the login button the script is executed and the output is "You are not a member", but when i refresh the page,the message from the script still remains on the screen. I believe isset() should return false until i click the button again? What's wrong with the code.
Thanks. | 2013/04/16 | [
"https://Stackoverflow.com/questions/16049020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1917222/"
] | Realized that my comment was really an answer...
When you "refresh", you refresh the page INCLUDING the POST data (since that was the last "request" made). You would have to re-enter the address of the page to clear it. Sometimes you see "do you really want to send this form again?" prompt when you refresh - this is why... | Isset() is used to check if a variable example : $variable is actually "set" and is not null. Also when doing a refresh you also refresh the action you have committed and the form data that you have passed. You can think of it as this :
If you go to a shopping website and they tell you to not refresh while your order is processing that means that if you refresh your post data is submitted again meaning you buy 2 microwaves rather then 1 :)
So in coding it will look like this :
```
if (isset('$_POST['username']')) {
$username = $_POST['username'];
if($username == 'letmein') {
echo ("welcome back, friend!");
}
}
```
Hopefully this helps a bit. Good luck! Also if your ever on the "John" and need reading material take a look at the [php manual page!](http://php.net/manual/en/function.isset.php) |
16,049,020 | I'm a beginner in PHP. In my code, i want the php script to be executed only when the submit button is clicked (set). So when the page is refreshed, the isset() function should return false. Here is the code for test.php
```
<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
else{
$username = "";
}
?>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="test.php">
<Input Type = "text" Value ="<?php print $username?>" Name ="username">
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</form>
</body>
</html>
```
After clicking the login button the script is executed and the output is "You are not a member", but when i refresh the page,the message from the script still remains on the screen. I believe isset() should return false until i click the button again? What's wrong with the code.
Thanks. | 2013/04/16 | [
"https://Stackoverflow.com/questions/16049020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1917222/"
] | Isset() is used to check if a variable example : $variable is actually "set" and is not null. Also when doing a refresh you also refresh the action you have committed and the form data that you have passed. You can think of it as this :
If you go to a shopping website and they tell you to not refresh while your order is processing that means that if you refresh your post data is submitted again meaning you buy 2 microwaves rather then 1 :)
So in coding it will look like this :
```
if (isset('$_POST['username']')) {
$username = $_POST['username'];
if($username == 'letmein') {
echo ("welcome back, friend!");
}
}
```
Hopefully this helps a bit. Good luck! Also if your ever on the "John" and need reading material take a look at the [php manual page!](http://php.net/manual/en/function.isset.php) | Refreshing the page will post the already posted form variables again so every time you refresh your page you are re submitting your form and by this you will have always the `isset` condition to true :)
I f you need more explaining tell me :) |
71,240,356 | I prefer `df.plot.scatter()` rather than `plt.scatter()` when doing data exploration. However I'm unable
### Generate Data
```py
n = 1000
data = dict(
x = np.random.rand(n) + np.random.rand(1)[0],
y = np.random.rand(n) + np.random.rand(1)[0],
# color dimension
z = np.exp(np.random.rand(n)) - np.exp(np.random.rand(n)).mean(),
)
# throw it in a dataframe
df = pd.DataFrame(data)
```
### Plotting with `plt.scatter`
The left plot uses `CenteredNorm` to ensure its colorbar is centered around zero no matter the distribution skew.
```py
cmap='bwr'
fig, (ax1, ax2) = plt.subplots(figsize=(20, 8), ncols=2)
sc = ax1.scatter(x=data['x'], y=data['y'], c=data['z'], cmap=cmap, norm=colors.CenteredNorm())
fig.colorbar(sc, ax=ax1)
sc = ax2.scatter(x=data['x'], y=data['y'], c=data['z'], cmap=cmap)
fig.colorbar(sc, ax=ax2)
plt.show()
```
[](https://i.stack.imgur.com/qM9SO.png)
### Plotting with `df.plot.scatter`
```py
df = pd.DataFrame(data)
fig, (ax1, ax2) = plt.subplots(figsize=(10, 4), ncols=2)
df.plot.scatter(x='x', y='y', c='z', norm=colors.CenteredNorm(), cmap=cmap, ax=ax1)
df.plot.scatter(x='x', y='y', c='z', cmap=cmap, ax=ax2)
plt.show()
```
Attempting the same with pandas inbuilt plotting API, raises the error:
```py
TypeError: matplotlib.axes._axes.Axes.scatter() got multiple values for keyword argument 'norm'
```
### Using `kwargs` parameters
```py
kwargs = dict(norm=colors.CenteredNorm())
df.plot.scatter(x='x', y='y', c='z',
cmap=cmap,
ax=ax1
**kwargs)
```
After a code correction from [tdy](https://stackoverflow.com/users/13138364/tdy), the snippet raises the same error:
```py
TypeError: matplotlib.axes._axes.Axes.scatter() got multiple values for keyword argument 'norm'
```
Is there any way of setting the norm param via pandas inbuilt plotting API? | 2022/02/23 | [
"https://Stackoverflow.com/questions/71240356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5684214/"
] | **Update:**
Starting in pandas 1.5.0, the `norm` parameter will work as expected with `df.plot.scatter`. The bug got fixed in [PR #45966](http://github.com/pandas-dev/pandas/pull/45966).
---
**Original bug:**
[`df.plot.scatter`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.scatter.html) passes kwargs to [`df.plot`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html) which passes kwargs to [`ax.scatter`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.scatter.html).
The issue is that pandas already sets a `norm`:
>
> [`plotting/_matplotlib/core.py#L1114-L1122`](https://github.com/pandas-dev/pandas/blob/v1.4.1/pandas/plotting/_matplotlib/core.py#L1114-L1122)
>
>
>
> ```py
> scatter = ax.scatter(
> data[x].values,
> data[y].values,
> c=c_values,
> label=label,
> cmap=cmap,
> norm=norm,
> **self.kwds,
> )
>
> ```
>
>
This `norm` is defined as either a `BoundaryNorm` or `None`:
>
> [`plotting/_matplotlib/core.py#L1095-L1103`](https://github.com/pandas-dev/pandas/blob/v1.4.1/pandas/plotting/_matplotlib/core.py#L1095-L1103)
>
>
>
> ```py
> if color_by_categorical:
> # ...
> norm = colors.BoundaryNorm(bounds, cmap.N)
> else:
> norm = None
>
> ```
>
>
So passing another `norm` via kwargs will produce the "multiple values" error.
This can be reproduced in pure matplotlib:
```py
fig, ax = plt.subplots()
ax.scatter(0, 42, norm=None, **{'norm': colors.CenteredNorm()})
# TypeError: matplotlib.axes._axes.Axes.scatter() got multiple values for keyword argument 'norm'
``` | As mentioned by @tdy, unpacking kwargs doesn't do the trick.
The function [`df.plot.scatter`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.scatter.html) takes the parameters `x, y, s, c`. Additional kwargs are passed to [`df.plot`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html). The following parameters are supported:
* x
* y
* kind
* ax
* subplots
* sharex
* sharey
* layout
* figsize
* use\_index
* title
* grid
* legend
* style
* logx
* logy
* loglog
* xticks
* yticks
* xlim
* ylim
* rot
* fontsize
* colormap
* table
* yerr
* xerr
* secondary\_y
* sort\_columns
...but it will not take the parameter `norm`. That would require extending [pandas source code](https://github.com/pandas-dev/pandas/blob/v0.25.0/pandas/plotting/_core.py#L504-L1533). |
36,378 | We create PDF files as relevant to a customer's e-mail communication. These PDF's contain some personal information, specific to the client.
The client is emailed a link to the PDF. The link to the PDF contains a 40 byte unique string specific to this communication to ensure uniqueness and to avoid guessing.
Is there any best practice concerning this approach, may the PDF-files be placed on the webserver directly, or should additional steps be taken in order to prevent harvesting or any other attack on our customers privacy?
Would there be an additional security gain in storing the PDF's in a database, instead of placing them directly on the file-system of the webserver (assuming it is properly secured)? | 2013/05/23 | [
"https://security.stackexchange.com/questions/36378",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/26319/"
] | My suggestion would be as follows:
* Store the PDFs on a [LUKS](http://en.wikipedia.org/wiki/LUKS) partition (or GPG full-disk / TrueCrypt full-disk), so that theft of the physical disks should not yield the data.
* Run a secondary HTTP server whose sole job it is to serve these files. Configure your file permissions such that only that HTTP server can read the PDFs. This provides minimum attack surface for data theft, and prevents the main HTTP server from reading the files.
* Set up single sign-on or something similar to authenticate between the two servers.
* Only serve the files over HTTPS, with SSL 2.0 and older disabled, preferably with AES-GCM set as the preferred cipher.
Storing them in the database wouldn't make much sense, since access to the disk would still yield the files. | Regardless of the length and complexity of the unique string, a file name can be guessed or a compromised communication link may be intercepted to learn the file names.
Why aren't you utilizing a method like scp, if all you are doing is to make pdf files available to your client ? This way, you can either force the user(recipient) to enter a password or have a pre-authorized ssh key, to retrieve his/her files ? Since either way, the end user have a unique piece of identifying information, access can be limited to those, who has the right ID information. Hence making the whole scheme more secure.
Just a thought... |
36,755,755 | So I have a serializer that looks like this
```
class BuildingsSerializer(serializers.ModelSerializer):
masterlisting_set = serializers.PrimaryKeyRelatedField(many=True,
queryset=Masterlistings.objects.all())
```
and it works great
```
serializer = BuildingsSerializer(Buildings.objects.get(pk=1))
serializer.data
```
produces
```
OrderedDict([
("masterlistings_set", [
"0a06e3d7-87b7-4526-a877-c10f54fa5bc9",
"343643ac-681f-4597-b8f5-ff7e5be65eef",
"449a3ad2-c76c-4cb8-bb86-1be72fafcf64",
])
])
```
but if I change the queryset in the serializer to
```
class BuildingsSerializer(serializers.ModelSerializer):
masterlistings_set = serializers.PrimaryKeyRelatedField(many=True, queryset=[])
```
I still get the same exact result back.
```
OrderedDict([
("masterlistings_set", [
"0a06e3d7-87b7-4526-a877-c10f54fa5bc9",
"343643ac-681f-4597-b8f5-ff7e5be65eef",
"449a3ad2-c76c-4cb8-bb86-1be72fafcf64",
])
])
```
Is this supposed to be happening? Am I using querysets incorrectly?
I used [] as an easy example to show that no matter what I put in nothing changes.
Please any insight would be invaluable
It should be noted that masterlistings has a primary key relationship that points to buildings. So a masterlisting belong to a building. | 2016/04/20 | [
"https://Stackoverflow.com/questions/36755755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1401040/"
] | As pointed out by @zymud, queryset argument in PrimaryKeyRelatedField is used for validating field input for creating new entries.
Another solution for filtering out masterlistings\_set is to use serializers.SerializerMethodField() as follows:
```
class BuildingsSerializer(serializers.ModelSerializer):
masterlisting_set = serializers.SerializerMethodField()
def get_masterlisting_set(self, obj):
return MasterListing.objects.filter(building=obj).values_list('pk',flat=True)
``` | `queryset` in related field limits only acceptable values. So with `queryset=[]` you will not be able to add new values to `masterlisting_set` or create new `Buildings`.
**UPDATE. How to use queryset for filtering**
This is a little bi tricky - you need to rewrite `ManyRelatedField` and `many_init` method in your `RelatedField`.
```
# re-define ManyRelatedField `to_representation` method to filter values
# based on queryset
class FilteredManyRelatedField(serializers.ManyRelatedField):
def to_representation(self, iterable):
iterable = self.child_relation.queryset.filter(
pk__in=[value.pk for value in iterable])
return super(FilteredManyRelatedField, self).to_representation(iterable)
# use overridden FilteredManyRelatedField in `many_init`
class FilteredPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
@classmethod
def many_init(cls, *args, **kwargs):
kwargs['child_relation'] = cls(queryset=kwargs.pop('queryset'))
return FilteredManyRelatedField(*args, **kwargs)
``` |
21,084,292 | am trying to assign time duration to the playlist.... but as am using onend that function is calling after completing that video, but what i want is the video should play only on its assigned time duration after that it should stops and next video should play..am using following code...
```
<video id="myVideo" height="100%" width="100%" autoplay onended="run();">
<source id="ss" src="video/video1.ogg" type='video/ogg'>
</video>
<script type="text/javascript">
// num_files++;
//alert(num_files);
video_count =1;
videoPlayer = document.getElementById("ss");
video=document.getElementById("myVideo");
time2= Math.round(+new Date()/1000);
function run(){
for(i=1;i<=3;i++)
{
//alert(duration[i]);
time1= Math.round(+new Date()/1000);
// alert('ctime'+time1);
dur_time=parseInt(time2,10)+parseInt(duration[i],10);
// alert('dtime'+dur_time);
video_count++;
if(time1<dur_time)
{
video_count--;
//alert(video_count);
if (video_count > num_files) video_count = 1;
videoPlayer.setAttribute("src","video/video"+video_count+".ogg");
//alert(video_count);
video.pause();
video.load();
video.play();
time1= Math.round(+new Date()/1000);
}
}
}
</script>
``` | 2014/01/13 | [
"https://Stackoverflow.com/questions/21084292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3145475/"
] | Based on the comments on my first answer, here's a reworked one more suited to your needs.
Create a model, e.g. ServiceHours, that next to the data you want to collect (hours done, supervisor\_email, ...), has the following fields:
```
activation_key=models.CharField(_('activation key'), max_length=40, null=True, blank=True)
validated=models.BooleanField(default=False)
```
I'd suggest adding a [post\_save signal](https://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.post_save) to the Model, so that whenever a new ServiceHours instance is created (by saving the form), the email to the supervisor is sent.
```
# Add this to your models file
# Required imports
from django.db.models.signals import post_save
from django.utils.hashcompat import sha_constructor
import random
def _create_and_send_activation_key(sender, instance, created, **kwargs):
if created: # Only do this for newly created instances.
salt = sha_constructor(str(random.random())).hexdigest()[:5]
# Set activation key based on supervisor email
instance.activation_key = sha_constructor(salt+instance.supervisor_email).hexdigest()
instance.save()
# Create email
subject = "Please validate"
# In the message, you can use the data the volunteer has entered by accessing
# the instance properties
message = "Include instance hours, volunteer's name etc\n"
# Insert the activation key & link
messsage += "Click here: %s" % (reverse("validate_hours", kwargs={'id': instance.id, 'activation_key':instance.activation_key})
# Send the mail
from django.core.mail import send_mail # Move this import to top of your file ofcourse, I've just put it here to show what module you need
send_mail(subject, message, sender, recipients)
post_save.connect(_create_and_send_activation_key, sender=ServiceHours)
```
Define a view to validate service hours based on an activation key
```
# in views.py
def validate_hours(request, id, activation_key):
# find the corresponding ServiceHours instance
service_hours = ServiceHours.objects.get(id=id, activation_key=activation_key)
service_hours.validated = True
service_hours.save()
```
In your urls.py, define an url to your validate\_hours view:
```
urlpatterns += patterns('',
url(r'^validate-hours/(?P<id>[0-9]+)/(?P<activation_key>\w+)', validate_hours, name='validate_hours'),
```
This has all been off the top of my head, so please excuse any errors. I hope you get the gist of the process and can extend according to your exact needs. | You might want to set/unset the `is_active` flag on the user.
Conceptually:
* When a user registers succesfully, be sure to set the flag to False;
* Autogenerate a unique string that is tied to the user's ID and send the activation url via email;
* In the activation view, decompose the key into the user ID and set the is\_active flag to True;
* In your login view, check whether the user trying to log in has is\_active is True.
Then you'll be sure that users who are logged in have a confirmed email address.
The page in Django's documentation [on user authentication](https://docs.djangoproject.com/en/1.6/topics/auth/default/) provides all necessary information. For a sample login view, the chapter ["How to log a user in"](https://docs.djangoproject.com/en/1.6/topics/auth/default/#how-to-log-a-user-in) has one.
If you'd prefer to use a reusable app, [django-registration](https://django-registration.readthedocs.org/en/latest/) might fit your needs perfectly.
(Post-reply addition:) why not commit the data to the database? The "waste" of having unactivated users residing in your database does not outweigh the effort you'd need to implement a solution that does not commit the data to the database. Moreover, it might be more than interesting to have an idea of the amount of unactivated users (and act accordingly). |
492,956 | Was curious if you anyone had information as to why 5GHz wifi is more susceptible to walls and floors in buildings (as compared to 2.4Ghz) but the opposite seems to be true for VHF vs UHF. We tend to use VHF radios outdoors and UHF radios more indoors. Seems like 5GHz is to UHF (both higher freq) as 2.4GHz is to VHF (both lower freq); and yet seems like the penetrative properties are opposite. | 2020/04/14 | [
"https://electronics.stackexchange.com/questions/492956",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/247424/"
] | This is not the answer that you want to hear :-) :-(.
Propagation in buildings and tunnels and similar is complex.
During "911" they had disastrous results trying to use radios in buildings. A significant number of reports were written and they tended to conclude that around 800 Mhz was optimum. I read through the technical part of a number of these reports for essentially unrelated reasons\* trying to find out the basis for their calculations. I found that all who gave a basis cited a single report that used a formula that was appropriate in its original context but randomly related to its use elsewhere. The parameter related to "roughness" of surfaces which tend to rotate the polarisation of the original wave with distance.
SO
You need to look at the equations for propagation and then decide what parameters are relevant and what they should be set to.
Conclusion: Magic is required - there are too many variables with semi random values that vary case by case. Obviously (or luckily) there must be frequencies that work somewhat better in some typical sets of cases to be useful generalisations.
---
Not all the papers over time did as I claim above - but whether they are useful in practice is moot. Most deal with internal space as tunnels - buildings tend to be tunnels with reflective attenuators (aka walls) in them to increase the fun level.
Here is one reference which comes to hand
[**ATTENUATION CONSTANTS OF RADIO WAVES IN
LOSSY-WALLED RECTANGULAR WAVEGUIDES**](http://www.jpier.org/PIER/pier.php?paper=13061709) 2013 31pp.
So you know what you're in for :-)
* Abstract:
At the ultra-high frequencies (UHF) common to portable radios, the mine tunnel acts as a dielectric waveguide, directing and absorbing energy as a radio signal propagates. Understanding radio propagation behavior in a dielectric waveguide is critical for designing reliable, optimized communication systems in an underground mine. One of the major parameters used to predict the power attenuation in lossy waveguides is the attenuation constant. In this paper, we theoretically and experimentally investigate the attenuation constants for a rectangular waveguide with dielectric walls. We provide a new derivation of the attenuation constant based on the classic Fresnel reflection coefficients. The new derivation takes advantage of ray representation of plane waves and provides more insight into understanding radio attenuation in tunnels. We also investigate the impact of different parameters on the attenuation constant, including the tunnel transverse dimensions, permittivity, conductivity, frequency, and polarization, with an aim to find their theoretical optimal values that result in the minimum power loss. Additionally, measurements of the attenuation constants of the dominant mode at different frequencies (455, 915, 2450, and 5800 MHz) for a straight concrete tunnel are presented and compared to theoretical predictions. It is shown that the analytical results match the measured results very well at all four frequencies.
---
Mother lode - maybe:
Here are references to a months plus solid reading while in self isolation. How useful they will be is tbd. This link will work after my PC next boots as Dropbox says it is not sinking at present. It is an RTF file containing 50+ live links and 30 or so citations - all of variable relevance.
[Tunnel {&building} communications](https://www.dropbox.com/s/u6esyecuv1uiy28/TUCO_TunnelCommunications.rtf?dl=0)
I tried to use
bit.ly/tunnelcoms <- please use
which allows me to see how many people accessed the link but the stupid SE system abhors such an equally good method (for reasons which are understood bu inlaid in cases like this one).
People interested enough to look at the references would do themselves and me a favour by using the bit.ly link. | It’s used because it’s an available unlicensed spectrum (same for 2.4GHz and 929-933 MHz.)
But, yes, range through obstructions for these Wi-Fi bands is poor. |
4,431,819 | What are the differences between a program and an application?
I am trying to understand this to form a concept in ontology. Can anyone explain? | 2010/12/13 | [
"https://Stackoverflow.com/questions/4431819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540863/"
] | My understanding is this:
* A **[computer program](http://en.wikipedia.org/wiki/Computer_program)** is a set of instructions that can be executed on a computer.
* An **[application](http://en.wikipedia.org/wiki/Application_software)** is software that directly helps a user perform tasks.
* The two intersect, but are not synonymous. A program with a user-interface is an application, but many programs are not applications. | i guess you mean System Programs and Application programs
System Programs makes the hardware run , Applications are for specific tasks
an Example for System Programs are Device Drivers
as for the Applications you can say web browsers , word porcessros etc |
4,431,819 | What are the differences between a program and an application?
I am trying to understand this to form a concept in ontology. Can anyone explain? | 2010/12/13 | [
"https://Stackoverflow.com/questions/4431819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540863/"
] | My understanding is this:
* A **[computer program](http://en.wikipedia.org/wiki/Computer_program)** is a set of instructions that can be executed on a computer.
* An **[application](http://en.wikipedia.org/wiki/Application_software)** is software that directly helps a user perform tasks.
* The two intersect, but are not synonymous. A program with a user-interface is an application, but many programs are not applications. | A "program" can be as simple as a "set of instructions" to implement a logic.
It can be part of an "application", "component", "service" or another "program".
Application is a possibly a collection of coordinating program instances to solve a user's purpose. |
4,431,819 | What are the differences between a program and an application?
I am trying to understand this to form a concept in ontology. Can anyone explain? | 2010/12/13 | [
"https://Stackoverflow.com/questions/4431819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540863/"
] | When I studied IT in college my prof. made it simple for me:
"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same.
The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."
Got it right on the exam.
So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.
Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :( | A "program" can be as simple as a "set of instructions" to implement a logic.
It can be part of an "application", "component", "service" or another "program".
Application is a possibly a collection of coordinating program instances to solve a user's purpose. |
4,431,819 | What are the differences between a program and an application?
I am trying to understand this to form a concept in ontology. Can anyone explain? | 2010/12/13 | [
"https://Stackoverflow.com/questions/4431819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540863/"
] | My understanding is this:
* A **[computer program](http://en.wikipedia.org/wiki/Computer_program)** is a set of instructions that can be executed on a computer.
* An **[application](http://en.wikipedia.org/wiki/Application_software)** is software that directly helps a user perform tasks.
* The two intersect, but are not synonymous. A program with a user-interface is an application, but many programs are not applications. | I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :) |
4,431,819 | What are the differences between a program and an application?
I am trying to understand this to form a concept in ontology. Can anyone explain? | 2010/12/13 | [
"https://Stackoverflow.com/questions/4431819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540863/"
] | When I studied IT in college my prof. made it simple for me:
"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same.
The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."
Got it right on the exam.
So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.
Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :( | Without more information about the question, the terms 'program' and 'application' are nearly synonymous.
As Saif has indicated, 'application' tends to be used more for non-system related programs. That being said, I don't think it's wrong to describe the operating system as an special application that provides an environment in which to run other applications. |
4,431,819 | What are the differences between a program and an application?
I am trying to understand this to form a concept in ontology. Can anyone explain? | 2010/12/13 | [
"https://Stackoverflow.com/questions/4431819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540863/"
] | Without more information about the question, the terms 'program' and 'application' are nearly synonymous.
As Saif has indicated, 'application' tends to be used more for non-system related programs. That being said, I don't think it's wrong to describe the operating system as an special application that provides an environment in which to run other applications. | I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :) |
4,431,819 | What are the differences between a program and an application?
I am trying to understand this to form a concept in ontology. Can anyone explain? | 2010/12/13 | [
"https://Stackoverflow.com/questions/4431819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540863/"
] | My understanding is this:
* A **[computer program](http://en.wikipedia.org/wiki/Computer_program)** is a set of instructions that can be executed on a computer.
* An **[application](http://en.wikipedia.org/wiki/Application_software)** is software that directly helps a user perform tasks.
* The two intersect, but are not synonymous. A program with a user-interface is an application, but many programs are not applications. | Without more information about the question, the terms 'program' and 'application' are nearly synonymous.
As Saif has indicated, 'application' tends to be used more for non-system related programs. That being said, I don't think it's wrong to describe the operating system as an special application that provides an environment in which to run other applications. |
4,431,819 | What are the differences between a program and an application?
I am trying to understand this to form a concept in ontology. Can anyone explain? | 2010/12/13 | [
"https://Stackoverflow.com/questions/4431819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540863/"
] | My understanding is this:
* A **[computer program](http://en.wikipedia.org/wiki/Computer_program)** is a set of instructions that can be executed on a computer.
* An **[application](http://en.wikipedia.org/wiki/Application_software)** is software that directly helps a user perform tasks.
* The two intersect, but are not synonymous. A program with a user-interface is an application, but many programs are not applications. | When I studied IT in college my prof. made it simple for me:
"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same.
The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."
Got it right on the exam.
So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.
Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :( |
4,431,819 | What are the differences between a program and an application?
I am trying to understand this to form a concept in ontology. Can anyone explain? | 2010/12/13 | [
"https://Stackoverflow.com/questions/4431819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540863/"
] | When I studied IT in college my prof. made it simple for me:
"A computer "program" and an "application" (a.k.a. 'app') are one-in-the-same.
The only difference is a technical one. While both are the same, an 'application' is a computer program launched and dependent upon an operating system to execute."
Got it right on the exam.
So when you click on a word processor, for example, it is an application, as is that hidden file that runs the printer spooler launched only by the OS. The two programs depend on the OS, whereby the OS itself or your internal BIOS programming are not 'apps' in the technical sense as they communicate directly with the computer hardware itself.
Unless the definition has changed in the past few years, commercial entities like Microsoft and Apple are not using the terms properly, preferring sexy marketing by making the term 'apps' seem like something popular market and 'new', because a "computer program" sounds too 'nerdy'. :( | I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :) |
4,431,819 | What are the differences between a program and an application?
I am trying to understand this to form a concept in ontology. Can anyone explain? | 2010/12/13 | [
"https://Stackoverflow.com/questions/4431819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540863/"
] | A "program" can be as simple as a "set of instructions" to implement a logic.
It can be part of an "application", "component", "service" or another "program".
Application is a possibly a collection of coordinating program instances to solve a user's purpose. | I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.