text:
Q: java convert resultset to a list I want to convert my Resultset to List of object . This is my query:
 String querystring1= "SELECT userID, privilege"
               + "FROM dbo.User order by userID, privilege";

 userID  privilege
 ------------------
 1001    read
 1001   write
 1001   execute
 1001   delete
 1006    execute
 1006    read
 1006    write
 1007   read
 1007    write

I have a class User defined like :
public class User {
   private int userID;
   private List<String> userPrivelege;
}

I want to have as an output to a list of Users, and this is my implemented code:
   String previousId = null;
   List<String> PrivList= new ArrayList<String>();
   List<User> allUserList= new ArrayList<User>();

   while(result_set.next()) {
      String userID = result_set.getString("userID");
      String privilege = result_set.getString("privilege");
      if (previousId == null) { // first time
         User user = new User();
         PrivList.add(privilege);
         previousId=userID;
      } else if (previousId.equals(userID) {
         PrivList.add(privilege);
      } else {
         user.setUserPrivilege(PrivList);
         allUserList.add(user);
         PrivList.clear();
         previousId=null;
      }
   }

The problem is,  other than the first user object created, all the next one are always missing the first value which means user 1006 will have 2 privileges other than 3.
Any idea?

A: All  User objects refer the same object List of privileges as you don't create a new instance for each User. Instead you clear only the List.
Consequently, all Users are set with 2 privileges as the last User that you handle has 2 privileges.
So replace :
 PrivList.clear();

by :
 PrivList = new ArrayList<>();

A: That's because You Miss the First privilege of the New User here,
  else {
             user.setUserPrivilege(PrivList);
             allUserList.add(user);
             PrivList.clear();
             previousId=null;
    }

Do the privilege initialization for the next user here.
PrivList = new ArrayList<>();
PrivList.add(privilege);

A: *

*As far as I can see, you are never assigning the user ID to the User object?

*PrivList.clear(); clears the list that you have just assigned to a user. Instead create a new list, as davidxxx also said.

*As anchreg said, after you have created a user and added it to the list, you need to initialize the next user in the same way as you did the first time.

*After your loop terminates, if previousId is not null (that is, any user previlege was processed at all), you need to assign values to the last user and add it to the list in the same way as in the last else case in the loop.

All of this said a more elegant solution could be coded using streams.

A: You need to create a new instance of PrivList  for each user.
Additionnaly, you need to add a privilege for the next user, otherwise you lose that information on the loop.
Edits shown by the <-- comments.
while(result_set.next()) {
    String userID = result_set.getString("userID");
    String privilege = result_set.getString("privilege");
    if (previousId == null) { // first time
        User user = new User();
        PrivList.add(privilege);
        previousId=userID;
    } else if (previousId.equals(userID) {
        PrivList.add(privilege);
    } else {
        // nex user
        user.setUserPrivilege(PrivList);
        allUserList.add(user);
        PrivList = new ArrayList<>();  // <--
        PrivList.add(privilege);       // <--
        previousId=null;
    }
}

A: In m y opinion, I think that is not a good model. You should have a second table with privileges related with an user. But to solve your question:
List<String> privList= new ArrayList<String>();
Map<Integer, List<String>> hmUserPrivileges = HashMap<Integer, String>();

while(result_set.next()) {
    int userID = result_set.getInt("userID");
    String privilege = result_set.getString("privilege");

    if (!hmUserPrivileges.contains(userID)) {
        privList= new ArrayList<String>();
    }

    privList.add(privilege);
    hmUserPrivileges.put(userID, privList);
}

List<User> allUserList = new ArrayList<User>();
Iterator<Entry<Integer, List<String>>> iterator = hmUserPrivileges.entrySet().iterator();
while(iterator.hasNext()) {
    Entry<Integer, List<String>> entry = iterator.next();
    User user = new User()

    user.setUserID(entry.getKey());
    user.setUserPrivelege(entry.getValue());

    allUserList.add(user);
}


text:
Q: Datatables Filtering with YADCF - Custom button triggers I am tying to use the YADCF extension so that I can sort the data in my table by it's status. I want to be able to click a button (bootstrap pills) and for that to then be the trigger for filtering the data, however I can't figure out how to do so. Below you can see an example from WHMCS, this is what I wish to happen

Currently I have been able to filter the data but only by using a select drop down. As you can see below, this is how my table and buttons look (including the added Select element from YADCF)

I was able to have the Select element work fully, but what I am asking is: how can I get each individual button/pill trigger a filter for each type of status?
This is the code I have for the table so far
yadcf.init(ticketsTable, [
    {
        column_number: 2,
        filter_container_id: 'test_container_0',
        column_data_type: "html",
        html_data_type: "text",
        filter_default_label: "Select Status"

    },
],
    {
        externally_triggered: false
    }
);

Any help at all would be greatly appreciated.

A: If all you want to achieve is custom pills you don't need to use my yadcf plugin at all, you can use the simple Datatables api alone, see the following jsbin sample and see code snippet:
var oTable;
function myPillFilter(data) {
  oTable.columns(0).search(data).draw();
}
$(document).ready(function(){
  oTable = $('#example').DataTable();
});

But if you want to use the yadcf plugin...
Your should add a filter for that column and make it hidden and add several buttons / spans / etc with onclick event that will call yadcf external api exFilterColumn
See the following quick jsbin sample I made
code snippets:
var oTable;
function myPillFilter(data) {
    yadcf.exFilterColumn(oTable, [[0, data]]);
}
$(document).ready(function(){
  oTable = $('#example').dataTable().yadcf([
    {column_number : 0, filter_container_id: "some_data"}]);
});

   some-1

   some-2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript function adds a space I have this code:
var ii='"'+'c0'+thecid+'"';
var newcommhtml = '
';
newcommhtml = newcommhtml + '
';
newcommhtml = newcommhtml + 'x';
newcommhtml = newcommhtml + '
'+nl2br(textval)+'

';

Basically when some conditions met it adds a section to the page with some text. To this section (row number 4 in the code above) adds a x to the section.
I would like to do so that when that x is clicked the section disappears.
When I run this code on a webpage it doesn't work. I checked the id of the getElementById(), there something weird happens: A space is added before the id of the element, I don't know where it came from.
I'm unable to solve the problem, does anybody know why this happens?
Pictures of the result:

*

*http://s8.postimg.org/xq9xsykyd/image.png

*http://s4.postimg.org/79q82e6i5/image.png

A: Use this:
var ii = 'c0'+thecid;
var newcommhtml = '
';
newcommhtml += '
';
newcommhtml += 'x';
newcommhtml += '
'+nl2br(textval)+'

';

So:

*

*Don't add quotes to the ii variable

*Use ii for the id instead of recalculating it

*In the onclick the double quotes around none were wrong

*You could use += for extending the string

A: Try this:
var ii='c0'+thecid;
var newcommhtml = '
';
newcommhtml = newcommhtml + '
';
newcommhtml = newcommhtml + 'x';
newcommhtml = newcommhtml + '
'+nl2br(textval)+'

';

A: Main reason for the problem is the double quotes adding with id name like "c04".
Just remove double quotes from your first line var ii='"'+'c0'+thecid+'"';
Change it to - var ii = 'c0'+ thecid;


text:
Q: Blank White screen after opening Flutter app I am pretty new to flutter and I recently created a weather app with the help of an online course . The app runs and works fine on the android emulator and when I run it on my phone. But I wanted to share the app so i created a release apk using flutter build apk --split-per-abi but after installing the app on their mobiles the first screen loads and immediately a blank white screen appears and nothing happens.
Such error doesn't arise when i run the app in android studio
My first loading screen page
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import '../services/weather.dart';
import 'location_screen.dart';
import 'package:location_permissions/location_permissions.dart';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {

  @override
  void initState() {
    getWeatherData();
    super.initState();
  }

  void getWeatherData () async {
    PermissionStatus permission = await LocationPermissions().requestPermissions();
    var weatherData =  await WeatherModel().getWeather();
    Navigator.push(context, MaterialPageRoute(builder: (context){
      return LocationScreen(weatherData: weatherData);
    }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SpinKitFoldingCube(
        color: Colors.blueAccent,
        size: 100,
        ),
    )
    );
    }
  }

My second Weather location screen
import 'package:clima/services/weather.dart';
import 'package:flutter/material.dart';
import 'package:clima/utilities/constants.dart';
import 'city_screen.dart';
import '../services/weather.dart';

class LocationScreen extends StatefulWidget {
  final weatherData;
  LocationScreen({this.weatherData});
  @override
  _LocationScreenState createState() => _LocationScreenState();
}

class _LocationScreenState extends State<LocationScreen> {
  int temperature;
  String icon;
  String message;
  String cityName;
  String summary;

  TimeOfDay t = TimeOfDay.now();
  @override
  void initState() {
    super.initState();
    updateScreen(widget.weatherData);
  }

  AssetImage setBackground(){
    print(t.hour);
    if(t.hour >18 || t.hour < 6)
      return AssetImage("images/night.png");
    else
      return AssetImage('images/after_noon.png');
  }
  void updateScreen(dynamic weatherData) {
    setState(() {
      if (weatherData == null) {
        temperature = 0;
        icon = 'error';
        message = 'Sorry Coudnt load Weather ';
        cityName = '';
        summary='';
      } else {
        double temp = (weatherData['main']['temp']);
        temperature = temp.toInt();
        icon = WeatherModel().getWeatherIcon(weatherData['weather'][0]['id']);
        message = WeatherModel().getMessage(temperature);
        cityName = weatherData['name'];
        summary=weatherData['weather'][0]['description'];
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: setBackground(),
            fit: BoxFit.cover,
            colorFilter: ColorFilter.mode(
                Colors.white.withOpacity(0.8), BlendMode.dstATop),
          ),
        ),
        constraints: BoxConstraints.expand(),
        child: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  FlatButton(
                    onPressed: () async {
                      updateScreen(WeatherModel().getWeather());
                    },
                    child: Icon(
                      Icons.near_me,
                      size: 50.0,
                    ),
                  ),
                  FlatButton(
                    onPressed: () async{
                      var cityName = await Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) {
                            return CityScreen();
                          },
                        ),
                      );

                      if(cityName != null)
                        {
                          var weatherData = await WeatherModel().getCityWeather(cityName);
                          updateScreen(weatherData);
                        }
                    },
                    child: Icon(
                      Icons.location_city,
                      size: 50.0,
                    ),
                  ),
                ],
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(left: 15.0),
                    child: Row(
                      children: <Widget>[
                        Text(
                          '$temperature',
                          style: kTempTextStyle,
                        ),
                        Text(
                          '$icon',
                          style: kConditionTextStyle,
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 15.0),
                    child: Text(
                      "$summary",
                      style: TextStyle(
                        fontSize: 30,
                        fontFamily: 'Spartan MB',
                        fontStyle: FontStyle.italic,
                      ),
                    ),
                  ),
                ],
              ),
              Padding(
                padding: EdgeInsets.only(right: 15.0),
                child: Text(
                  "$message in $cityName",
                  textAlign: TextAlign.right,
                  style: kMessageTextStyle,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

A: You need to call the function below after the imports in your root route or main page
void main() => runApp(LoadingScreen());


text:
Q: Como "Zipar" arquivos ou diretórios no codeigniter Eu já vi na documentação, mas eles falam de maneira muito rasa, e o entendimento não fica bom. Então, alguém pode me explicar de uma forma mais prática de como eu posso zipar arquivos no codeigniter? obrigado.
Link para a documentação: https://www.codeigniter.com/user_guide/libraries/zip.html
Eu não entendi quase nada, a respeito do processo de zipagem.

A: Vou tentar explicar o que tem na documentação:
1 - Você deve carregar a lib zip no seu controller.
$this->load->library('zip');

2 - Você declara os valores que vai utilizar
$filepath = 'mydata1.txt'; // Diretório do Arquivo
$data = 'A Data String!'; // Conteúdo do Arquivo

3 - Você vai utilizar o método: add_data
$this->zip->add_data( $filepath, $data ); // Essa função vai receber 2 parâmetros, o primeiro é o caminho do arquivo e o segundo é o conteúdo desse arquivo.

Agora se você já tem o arquivo em algum lugar no seu servidor, você vai utilizar a função abaixo:
$this->zip->archive( $path, $archive_filepath ); // Primeiro parâmetro você vai passar o caminho do arquivo, o segundo é opcional caso queira que o zip tenha outro nome ou salvar em outro local.


text:
Q: Getting non-greedy sequence as a string with ANTLR I have a problem with getting sequence as a string. I have a file with strings like:
{TEXT="

some text
"}

I want to get and use text that exactly between first and last quotes. First i tried:
parse : line+;
line : '{TEXT="' SEQUENCE '"}' {System.out.println($SEQUENCE.getText())};
SEQUENCE : .+?;

But it failed, SEQUENCE get only one symbol in that way. I tried:
parse : line+;
line : '{TEXT="' (a+=SEQUENCE)*? '"}' {System.out.println($a.getText())};
SEQUENCE : .;

And I got List of Tokens, so i can't use getText.

A: if you want to do it in this way, you can do it like this:
grammar Sequence;

parse : line+;
line : '{TEXT="' a=sequence '"}' {System.out.println(((LineContext)_localctx).a.getText());};
sequence : .+?;

ANY:.;

But there also other mechanisms in ANTLR4 like listeners and visitors.


text:
Q: Is premature optimization in SQL as "evil" as it is in procedural programming languages? I'm learning SQL at the moment and I've read that joins and subqueries can potentially be performance destroyers. I (somewhat) know the theory about algorithmic complexity in procedural programming languages and try to be mindful of that when programming, but I don't know how expensive different SQL queries can be. I'm deciding whether I should invest time in learning about SQL performance or just notice it when my queries run slow. The base question for me then is: is premature optimization for SQL as evil as it is for procedural languages?
As added information, I work in an environment where, most of the time, high performance is not an issue and the biggest tables I have to work with have some 150k rows.
Here's the Donald Knuth quote I refer to when saying "evil":

We should forget about small
  efficiencies, say about 97% of the
  time: premature optimization is the
  root of all evil. Yet we should not
  pass up our opportunities in that
  critical 3%.

A: I would say that some general notions about performance are a must-have : it'll prevent you from writing really bad queries that can hurt your application (Even if you don't have millions of rows in your tables).
It'll also help you design your database so it's more officient-oriented : you'll have some ideas about where to put indexes, for instance.
But you shouldn't have performance as a first goal : the first thing is to have an application that works ; and, then, if needed, you'll optimize it (having some performance notions while developping will help you have an application that's easier to optimize, though).
Note I would not say that "having notions about performances" is "premature optimization", as long as you don't just "optimize", but just "write correctly" ; I would rather call it good practice that'll help to write better quality code ;-)

A: What Knuth means is: it's really, really important to know about SQL optimisation but only when you need to. As you say, "most of the time ... high performance is not an issue."
It's that 3% of times when you do need high performance that it's important to know what rules to break and why.
However, unlike procedural languages, even for 150k rows it can be important to know a little about how your query is processed. For instance free text searching will be very slow compared with searching through exact matches on indexed columns. It's going the final steps into e.g. sharding or full denormalisation where most DBAs and developers draw the line.

A: I would say that you should make the SQL as easily readeble as possible, and only worry about the performance once it hits you.
That said.
Be mindfull of standard things as you develop, such as indexes, sub selects, use of cursors where a standard query would do the job, etc.
It will not hurt to develop the original correctly, and you can optimize the problems later when it is needed.
EDIT
Also remeber that maintainability of your SQL code is very important, and that debugging SQL is slightly more difficult than normal coding.

A: I wouldn't say that SQL optimization has as many pitfalls as premature programming optimization. Designing your schema and queries ahead of time with performance in mind can help you avoid some really nasty redesigns later on. That being said, spending a day getting rid of a table scan can be utterly worthless to you in the long run if that query isn't a slow query, can be cached, or is rarely called in a manner that would impact your application.
I personally profile my queries and focus on the worst, and most used queries. Careful design ahead of time cuts out most of the worst.

A: Knuth says "forget about 97%" but for a typical web app it's in the database IO where 97% of the request time is spent. This is where a little optimization effort can yield greatest results.
If this is the kind of apps you're writing I strongly suggest learning as much of how RDBMSes work as you can afford. Other people give you excellent suggestions, and I'd add that I usually follow this list top-down when deciding how to spent my "optimization budget":

*

*Schema design. Think twelve times
        about normalizaton and access
        strategies. This will save you many
        painful hours later.

*Query readability. Related to #1,
    sometimes trying to reogranize your
    queries gives a better understanding
    of how schema should look. Also it'll
    help later when you ask for
    help.

*Avoid subqueries in SELECT list, use
JOINs.

*If there are slow queries reach for
Profiler. Check for missing indexes
first And finally, if there are
still slow queries, try to rewrite
it.
Keep in mind also, that database performance very much depends on data distribution and number of simultaneous requests (because of locking). Even though a query completes in 1 sec. on your underpowered netbook it could take 15 seconds on the 8-core server. If possible, check your queries on actual data. If you know that concurrency is going to be high it's (paradoxically) better to use many small queries than one big one.

A: I agree with everything that's said here, and I'd like to add: make sure that your SQL is well-encapsulated so that, when you discover what needs to be optimized, there's only one place you need to change it, and the change will be transparent to whatever code calls it.
Personally, I like to encapsulate all of my SQL in PL/SQL procedures, but there are some who disagree with that.  Whatever you do, I recommend trying to avoid putting your SQL "inline" with other sourcecode.  That seems to always lead to cut-and-pasting and quickly becomes hard to maintain.  Put your SQL elsewhere, and try to re-use it as much as possible.
Also, read up on indexes, how they really work, and when you should and shouldn't use them.  A lot of people's first instinct, when they get a slow query, is to index the table to death.  That might solve the problem in the short term, but long-term an over-index table will be slow to insert and update into.  A few well-chosen indexes are much better than indexing every field.  Try reading "Refactoring SQL Applications" by Stephane Faroult.
Finally, as said above, a properly normalized database design will help avoid 99% of your slow queries.  Denormalization is neccesary sometimes, but it's important that you know the rules, before you break them.
Good luck!


text:
Q: Prevent same files/photos select Is there any way to prevent adding already selected files? For instance, detect if same name already exist in previously added files? Any checks before form posting or sending to the server?

A: Here's the solution I've used with a Filepond instance called "pond":
var filenames = [];
pond.on('addfile',
    function(error, file){
        if(filenames.includes(file.filename)){
            error = {
                main: 'duplicate',
                sub: 'A file with that name already exists in the pond.'
            }
            handleFileError(error, file);
        }
        if(error) handleFileError(error, file);
        filenames.push(file.filename);
    });

pond.on('removefile',
    function(error, file){
        var index = filenames.indexOf(file.filename);
        filenames.splice(index, 1);
    });

function handleFileError(error, file){
    var err = document.querySelector(".filepond-error");
    err.innerHTML = file.filename + " cannot be loaded " + error.sub;
    pond.removeFile(file);
}


text:
Q: When I switch on GPS or network provider new, my program doesn't get latitude and longitude I have a program that gets latitude and longitude of the user.
 LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // Create a criteria object to retrieve provider
        Criteria criteria = new Criteria();
        // Get the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);
        // Get Current Location
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
        }
        Location myLocation = locationManager.getLastKnownLocation(provider);
    Location myLocation = locationManager.getLastKnownLocation(provider);
                boolean netEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (netEnabled) {
                    if (isGPSEnabled) {
                        latitude = myLocation.getLatitude();

                        longitude = myLocation.getLongitude()
                    } else if (!isGPSEnabled) {
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
                        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();

                        } else {

                            // displayPromptForEnablingGPS(MapsActivity.this);
                        }
                    }
                } else if (!netEnabled) {

                    if (isGPSEnabled) {
                        latitude = myLocation.getLatitude();

                        // Get longitude of the current location
                        longitude = myLocation.getLongitude();

                    } else {
                        // displayPromptForEnablingGPS(MapsActivity.this);
                    }

                }

(displayPromptForEnablingGPS is for ACTION_LOCATION_SOURCE_SETTINGS)
In the program, if GPS and network providers are off, a window is opened for switching on them. When i switch GPS on in the first time, it gives error in first if(GPSEnabled) method(error on latitude=myLocation.getLatitude()). I can't get latitude and longitude. It is also same when i switch on only network provider. It gives "location" variable null. But if i open Google Maps, it starts to get latitude and longitude.
What can the problem be? It is problem of phone or i must make GPS run by writing any code?
Thanks for your help.

A: The method will return null value in case there's no location information previously.
It's better to get last known location iterate over all of the enabled providers, because this is the case that
there's no GPS and Network provider. >> link on SO
It's just better to add handling that case
if(!netEnabled && isGPSEnabled ){
//no network provider is enabled
Above sample code : here


text:
Q: how to calculate multipath signal, delay, angle between 2 signal? I am trying to understand how to calculate the phase angle, delay, and multipath signal. I hope everyone can help me for ideas.
My scenario: I have a radio hardware (SDR) with rx1 and rx2, and the TV station (center frequency = 533MHZ, bandwidth = 6MHz), with 4.8 km distance away from me (from google map to measure a distance). From FCC data base that I have information for the TX (latitude, longitude, antenna height, and model...).
First, I calculate the phase between 2 antennas:
%%%%%%
x = .... ; % complex data from rx1

y = .... ; % complex data from rx2

x = x - mean(x);  X = fft(x);
y = y - mean(y);  Y = fft(y);

[mag_x idx_x] = max(abs(X));
[mag_y idx_y] = max(abs(Y));

px = angle(X(idx_x));
py = angle(Y(idx_y));
phase_lag = py - px;

%%%%%
is it correct? then trying to calculate the multipath signal:
speed_of_light = 3e8 ; % m/s
distance = 3 * 1.6;
freq = 533e6;
lamda = speed_of_light / freq;
k = 2 * pi / lamda;
x = distance / 2;
y = 0;
w = 2 * pi * freq;
phase = 0;
delta = 1e-6; % delay
i = sqrt(-1);
t = 0:0.01:1;
degree = 0;
mutilpath = zeros(1,length(t));

index = 10;

for j = 1: index

   mutilpath  = mutilpath + exp(i * (k * (x * cos(phase+degree) + y * sin(phase+degree)) - w * (t - delta)));
    degree    = degree + pi/6;

end

figure(1), plot(t,abs(mutilpath));
figure(2), plot(t,angle(mutilpath));

%figure(3), plot(t,abs(mutilpath));
%figure(4), plot(t,angle(mutilpath));

%%%%%%%%%
when i set index = 1; i have a plot abs(mutilpath) is a straight line (figure1)
when i set index = ! 1; i have a plot abs(mutilpath) is a different line (figure3)
I have a bad feeling that i am not doing right.
If everyone have ideas, please recommend.
Thank you very much.


text:
Q: How do I implement login in a RESTful web service? I am building a web application with a services layer.  The services layer is going to be built using a RESTful design.  The thinking is that some time in the future we may build other applications (iPhone, Android, etc.) that use the same services layer as the web application.  My question is this - how do I implement login?  I think I am having trouble moving from a more traditional verb based design to a resource based design.  If I was building this with SOAP I would probably have a method called Login.  In REST I should have a resource.  I am having difficulty understanding how I should construct my URI for a login.  Should it be something like this:
http://myservice/{username}?p={password}
EDIT: The front end web application uses the traditional ASP.NET framework for authentication.  However at some point in the authentication process I need to validate the supplied credentials. In a traditional web application I would do a database lookup. But in this scenario I am calling a service instead of doing a database lookup.  So I need something in the service that will validate the supplied credentials.  And in addition to validating the supplied credentials I probably also need some sort of information about the user after they have successfully authenticated - things like their full name, their ID, etc.  I hope this makes the question clearer.
Or am I not thinking about this the right way?  I feel like I am having difficulty describing my question correctly.
Corey

A: As S.Lott pointed out already, we have a two folded things here: Login and authentication
Authentication is out-of-scope here, as this is widely discussed and there is common agreement. However, what do we actually need for a client successfully authenticate itself against a RESTful web service? Right, some kind of token, let's call it access-token.
Client) So, all I need is an access-token, but how to get such RESTfully?
Server) Why not simply creating it?
Client) How comes?
Server) For me an access-token is nothing else than a resource. Thus, I'll create one for you in exchange for your username and password.
Thus, the server could offer the resource URL "/accesstokens", for POSTing the username and password to, returning the link to the newly created resource "/accesstokens/{accesstoken}".
Alternatively, you return a document containing the access-token and a href with the resource's link:

<access-token
  id="{access token id goes here; e.g. GUID}"
  href="/accesstokens/{id}"
/>

Most probably, you don't actually create the access-token as a subresource and thus, won't include its href in the response.
However, if you do so, the client could generate the link on its behalf or not? No!
Remember, truly RESTful web services link resources together in a way that the client can navigate itself without the need for generating any resource links.
The final question you probably have is if you should POST the username and password as a HTML form or as a document, e.g. XML or JSON - it depends... :-)

A: You don't "login".  You "authenticate".  World of difference.
You have lots of authentication alternatives.
HTTP Basic, Digest, NTLM and AWS S3 Authentication

*

*HTTP Basic and Digest authentication.  This uses the HTTP_AUTHORIZATION header.  This is very nice, very simple.  But can lead to a lot of traffic.

*Username/Signature authentication.  Sometimes called "ID and KEY" authentication.  This can use a query string.
?username=this&signature=some-big-hex-digest
This is what places like Amazon use.  The username is the "id".  The "key" is a digest, similar to the one used for HTTP Digest authentication.  Both sides have to agree on the digest to proceed.

*Some kind of cookie-based authentication.  OpenAM, for example, can be configured as an agent to authenticate and provide a cookie that your RESTful web server can then use.  The client would authenticate first, and then provide the cookie with each RESTful request.

A: Great question, well posed. I really like Patrick's answer. I use something like
-/users/{username}/loginsession
With POST and GET being handled. So I post a new login session with credentials and I can then view the current session as a resource via the GET.
The resource is a login session, and that may have an access token or auth code, expiry, etc.
Oddly enough, my MVC caller must itself present a key/bearer token via a header to prove that it has the right to try and create new login sessions since the MVC site is a client of the API.
Edit
I think some other answers and comments here are solving the issue with an out-of-band shared secret and just authenticating with a header. That's fine in many situations or for service-to-service calls.
The other solution is to flow a token, OAuth or JWT or otherwise, which means the "login" has already taken place by another process, probably a normal login UI in a browser which is based around a form POST.
My answer is for the service that sits behind that UI, assuming you want login and auth and user management placed in a REST service and not in the site MVC code. It IS the user login service.
It also allows other services to "login" and get an expiring token, instead of using a pre-shared key, as well as test scripts in a CLI or Postman.

A: Since quite a bit has changed since 2011...
If you're open to using a 3rd party tool, and slightly deviating from REST slightly for the web UI, consider http://shiro.apache.org.
Shiro basically gives you a servlet filter purposed for authentication as well as authorization. You can utilize all of the login methods listed by @S.Lott, including a simple form based authentication.
Filter the rest URLs that require authentication, and Shiro will do the rest.
I'm currently using this in my own project and it has worked pretty well for me thus far.
Here's something else people may be interested in.
https://github.com/PE-INTERNATIONAL/shiro-jersey#readme

A: The first thing to understand about REST is that its a Token based resource access.Unlike traditional ways, access is granted based on token validation. In simple words if you have right token, you can access resources.Now there is lot of whole other stuff for token creation and manipulation.
For your first question, you can design a Restfull API. Credentials(Username and password) will be passed to your service layer.Service layer then validates these credentials and grant a token.Credentials can be either simple username/password or can be SSL certificates. SSL certificates uses the OAUTH protocol and are more secure.
You can design your URI like this-
URI for token request-> http://myservice/some-directory/token?
(You can pass Credentilals in this URI for Token)
To use this token for resource access you can add this [Authorization:Bearer (token)] to your http header.
This token can be utilized by the customer to access different component of your service layer. You can also change the expiry period of this token to prevent misuse.
For your second question one thing you can do is that you grant different token to access different resource components of your service layer. For this you can specify resource parameter in your token, and grand permission based on this field.
You can also follow these links for more information-
http://www.codeproject.com/Articles/687647/Detailed-Tutorial-for-Building-ASP-NET-WebAPI-REST
http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

A: I have faced the same problem before. Login does not translate nicely to resource based design.
The way I usually handle it is by having Login resource and passing username and password on the parameter string, basically doing
GET on http://myservice/login?u={username}&p={password}
The response is some kind of session or auth string that can then be passed to other APIs for validation.
An alternative to doing GET on the login resource is doing a POST, REST purists will probably not like me now :), and passing in the creds in the body. The response would be the same.


text:
Q: Odoo8.0, cannot valid the csv file when try to import it I have problem when i was try to import .csv file. I was try to convert image to base64 and also i was try to create barcode by name csv file. The image it's success convert into base64 but the problem when i was try to create barcode by csv file name, i was always get error like :
Unknown error during import: <class 'openerp.exceptions.ValidationError'>: ('ValidateError', u'Field(s) `ean13` failed against a constraint: You provided an invalid "EAN13 Barcode" reference. You may use the "Internal Reference" field instead.') at row 2 Resolve other errors first

And this is my code:
files = []
text = ''"
data_text3 = []

header_column2 = ["id","product_variant_ids/ean13_barcode", "product_variant_ids/ean13", "ean13", "image", "ean13_barcode", "default_code", "product_variant_ids/default_code"]

number = 1 for file in os.listdir("gmbr/"):
    file_name = os.path.splitext(file)[0]

    for n in str(number):
        directory_file = "gmbr/"+str(file)
        img = open(directory_file, 'rb').read()
        img_64 = base64.encodestr
        text = str(number)+","+str(name_product)+","+str(file_name)+","+str(file_name)+","+str(img_64+","+" "+","+" "+","+" ")
        number += 1
        data_text3.append(text)

with open('sample2.csv', 'wb') as f:
    writer = csv.writer(f, delimiter='\t', dialect='excel')
    writer.writerow(header_column2)
    for l in data_text3:
        writer.writerow(l.split(','))


text:
Q: How to execute a script on a server from a webpage? I want to run a shell script off my VPS through a website to start and stop a service. I have a script i currently execute by puttying in and typing ctf.sh. I had a look at using CGI and stuff, however this has left me thoroughly confused.
On my VPS my web folder is ofcourse /var/www so where would i find the cgi-bin folder and how would i go about runing such things? Sorry for such a stupid question :S

A: You could execute your script like:
exec('/path/to/your/script.sh');


text:
Q: Error capturing onreadystatechange of MSXML2.DOMDocument in VBA I am getting an error trying to arrange asynchronous loading and parsing of an XML document in VBA using a wrapper class.
Following the ideas described in this msdn article and this tutorial which have worked perfectly for asynchronous handling of MSXML2.XMLHTTP40.send method I attempted to do a similar thing for DOMDocument.loadXML.
Here is the code from the wrapper class DOMMonitor
Private domDoc As MSXML2.DOMDocument
Public Event onXmlLoadComplete(d As MSXML2.DOMDocument)

Public Sub loadXML(XmlFilePath As String)
    Set domDoc = CreateObject("MSXML2.DOMDocument")
    domDoc.async = True
    domDoc.onreadystatechange = Me ' error occurs here
    domDoc.Load XmlFilePath
End Sub

Public Sub onLoadComplete()
    If domDoc.readyState = "4" Then
        RaiseEvent onXmlLoadComplete(domDoc)
    End If
End Sub

I have made onLoadComplete the default method by setting VB_UserMemId = 0, so it is supposed to be invoked when domDoc fires onreadystatechange .
However when I invoke loadXML
Dim dm As DomMonitor
Set dm = New DomMonitor
dm.loadXML txtXMLData

i get the following runtime error in this line:
domDoc.onreadystatechange = Me

This object cannot sink the 'onreadystatechange' event. An error occurred marshalling the object's IDispatch interface
What am I doing wrong and is there a good workaround here?
Thanks in advance.
P.S. The reason I am republishing the event is that I do not necessarily want use the default method of the final subscriber for this purpose. However, as things stand now I do not even get to that stage.

A: The way I read that msdn article is that to assign a wrapper class to the readystatechange, the object has to be either an IXMLHTTPRequest or an IServerXMLHTTPRequest object (bullet 3).  Since your object is a DOMDocument, readystatechange doesn't accept an object.
However, you can instantiate a DOMDocument WithEvents (bullet 2), making the other way redundant, I guess.  I don't have an xml file large enough to test, but I think this should work. I assume that if the class loses scope, all bets are off, so I made it a global variable.
In a standard module
Public clsDOMMonitor As CDOMMonitor

Sub test()

    Set clsDOMMonitor = New CDOMMonitor
    clsDOMMonitor.loadXML "C:\Users\dkusleika\Downloads\wurfl-2.3.xml"

End Sub

In CDOMMonitor class
Private WithEvents mDoc As MSXML2.DOMDocument

Private Sub mDoc_onreadystatechange()

    If mDoc.readyState = 4 Then
        MsgBox "second"
    End If

End Sub

Public Sub loadXML(XmlFilePath As String)

    Set mDoc = New MSXML2.DOMDocument
    mDoc.async = True
    mDoc.Load XmlFilePath

    MsgBox "first"

End Sub

I assume that setting async to True is all that is needed for this to work properly. My 100k xml file is probably done so fast that that the event never gives up control.  But if you had a sufficiently large xml file, I think you would get "first" before "second".

A: Change the class' Instancing property from Private to PublicNotCreatable when late binding, whilst also applying the tweak which you have mentioned.
Use the above example when early binding (as in your case).


text:
Q: Spring controller returning multiple responses I am a beginner at Spring MVC and I have a quick question to ask. I searched all over Google for days to find the most efficient way to go about this problem:
I have a request that's coming in to Spring MVC controller. I want to send a response but wait for however many seconds and return another response to the same client. I was thinking about using ThreadExecutor or using Callable but I am not sure if that's the way to go.
Does anyone have any tutorials/examples or hints that can quickly get me started?
Thanks!

A: I think what you are looking for is Async processing (Which is introduced in Servlet 3.0). Here is blog from Spring team on async support and how it works


text:
Q: nco cut daily netcdf file from 10AM to 10AM everyday with duplicated 10am entries I am a very beginner of nco, and I want to split my .nc file (from 1996010110 to 2019123110) as daily file, from 10AM to 10PM. In that case, each split file contains YYYY-MM-DD:10:00 to YYYY-MM-(DD+1):10:00. Note that the end hour of DD day is repeated in the beginning of next day. That is the data of YYYY-MM-DD:10:00 occurs twice in file_YYYY_MM_DD.nc as the starting data and also the ending data of file_YYYY_MM_(DD-1).nc.
Thanks!

A: There is a CDO command that allows you select a subrange of hours:
cdo selhour,10/22 in.nc out.nc

which would answer the first part of the question, but from my comment you will see that the question needs further clarification.

A: The way to do this in NCO is to wrap a loop over time around use the sub-cycling form of the hyperslabber to eliminate the dupicate timestamps then loop over the days to create each file similar to this documented example here. For input where the first desired record is index 10, the last desired index is unbounded, the number of records in a repeating series (i.e., the stride between groups) is 25, and the number of consecutive desired records (the desired subset of a group) is 24, the first command would like this:
ncrcat -d time,10,,25,24 in.nc out.nc

Then out.nc will contain thousands of days of data with no repeated timesteps, and you can split that file into daily files however you like, including with ncrcat wrapped in a loop something like
EDIT 20210924: Based on clarification below you can ignore the above part of this message and proceed directly to this loop, which has been modified to extract 25 timesteps per day.
for yr in {1996..2019}; do
  for mth in {1..12}; do
    for day in {1..${dpm[mth]}}; do # Days-per-month array exercise left for the reader :)
      yyyy=`printf "%04d" $yr`
      mm=`printf "%02d" $mth`
      dd=`printf "%02d" $day`
      ncrcat -d time,${yyyy}-${mm}-${dd}T10:00:00,${yyyy}-${mm}-${ddp1}T10:00:00 out.nc file_${yyyy}_${mm}_${dd}.nc
    done
  done
done


text:
Q: Can every SPARQL query be expressed as a GraphQL query? The question is really formulated in the title :-)
I am working on an RDF project but I want to make it as easy as possible to interact with the API. Therefor GraphQL seems the most likely.
UPDATE:
Got an answer on Quora.

A: We are currently working on a GraphQL library to query a SPARQL Endpoint according to an OWL schema. It will be the main API access point for the DATAtourisme, french government project to handle and share touristic open data.
Contact me to tell me more about your project, i will tell you if the library can fit your needs.


text:
Q: Delete error in a file (c programming) I have a program that its purpose is to create an employee file,  then from that file that has been created the user can delete a record, update it or retreive it, the problem that I'm having is that when the user enters 2 to delete a record and the record is deleted by the Delete Function ( which transfer all the record except 3 which is the id that I intent to delete) then the display function needs to display the updated file, but it keeps on giving this error "An error occurred opening the file" I believe that happens because the file gets delete after the delete function is executed,can someone please guide me or tell me what is wrong with my code
Here is my code:
#include <stdio.h>
#include <string.h>
#define KEY_SIZE 100

typedef struct employee{
  int id;
  char name[40];
  float pay;
}EMP;

void CreateEmployee();
void DisplayRecord();
void DeleteRecord(int );
void menuEmployee();
void StoreTemp(struct employee data[],FILE *fp,int ,int );

int main() {
    menuEmployee();
    return 0;
}

 void menuEmployee(){
    int choice=0;
    printf("      Please select an Option\n");
    puts("");
    printf("\t1:Create Employee\n");
    printf("\t2:Delete Employee\n");
    printf("\t3:Update Employee\n");
    printf("\t4:Retrieve Employee\n");
    printf("\t5:Display Employee\n");
    puts("");
    printf("\t    6:Exit\n\t      ");
    scanf("%d",&choice);

     switch((choice-1)){
      case 0:
        CreateEmployee();
        break;
      case 1:
        DeleteRecord(3);
        DisplayRecord();
        break;
      case 2:
        //UpdateEmployee();
        break;
      case 3:
        //RetrieveEmployee();
        break;
      case 4:
        DisplayRecord();
        break;
      case 5:
        exit(0);
      default:
        printf("No such option Exist");
        break;
   }
 }

void DeleteRecord(int id){
   EMP test[KEY_SIZE];
   FILE *fp;
   FILE *tfp;
   int length;
   int i =0;
   fp=fopen("employee.txt","r");
   tfp=fopen("temp.txt","a");
   if(fp != NULL){
    length=ReadContents(test,fp,id);
    length=length-1;
   }
   StoreTemp(test,tfp,length,id);
   fclose(fp);
   remove("employee.txt");
   rename("temp.txt","employee.txt");

   fclose(tfp);
 }

int ReadContents(struct employee test[],FILE *fp,int id)
{

   int count=0;
   int i;
   while(!feof(fp)){
    fscanf(fp,"%i %s %f",&test[count].id,test[count].name,&test[count].pay);
    count++;
  }

  return count;
 }

void CreateEmployee(){
   char choice ='y';
   int i=0;
   long int pos;
   EMP x[20];

   FILE *fp;
   FILE *keyfp;
   fp = fopen("employee.txt","a");
   keyfp =fopen("Key.txt","a");
   if (fp==NULL){
     printf("File not created");
   }
   while((choice == 'Y') || (choice =='y')){
     printf("Enter the employee's id:");
     scanf("%i",&x[i].id);
     fprintf(fp,"%i\t",x[i].id);

     printf("\nEnter the employee's name:");
     scanf("%s",x[i].name);
     fprintf(fp,"%s\t",x[i].name);

     printf("\nEnter the employee's pay:");
     scanf("%f",&x[i].pay);
     fprintf(fp,"%.2f\t\n",x[i].pay);
     printf("\nEnter another employee?\n");
     printf("Y - Yes     N - No:\n");

     scanf("\n%c",&choice);
     i++;
  }

  fclose(fp);
  fclose(keyfp);
  menuEmployee();
}

void StoreTemp(struct employee data[],FILE *fp,int length,int id){
   int i=0;
   for(i=0;i<length;i++){
    if(data[i].id != id){
        fprintf(fp,"%i\t%s\t%.2f\n",data[i].id,data[i].name,data[i].pay);
      }

   }
 }

void DisplayRecord(){

   EMP temp;

   FILE *fp = fopen("employee.txt", "r");

   if(fp != NULL)
  {
     printf("ID\tNAME\tSALARY\n");
     while(1)
      {
         fscanf(fp, "%i %s  %f", &temp.id, temp.name, &temp.pay);
         if (feof(fp))
            break;
         printf("%i\t%s\t%.2f\n",temp.id, temp.name, temp.pay);

      }

       fclose(fp);
     }
     else
     {
       printf("An error occurred opening the file\n");
     }
  }

A: You are trying to rename a file that is still open. Swap these two lines:
   rename("temp.txt","employee.txt");
   fclose(tfp);

To this:
   fclose(tfp);
   rename("temp.txt","employee.txt");


text:
Q: How to remove GRUB Rescue prompt after deleting Ubuntu partition? I had a Windows 7 pc dual booting with Windows XP and then i got hold of Ubuntu 12.10 and I installed  it alongside Windows 7 and after installing on boot i got GNU GRUB interfering in my bootloader and after some days I by mistake formatted the parttion now my pc does not boot and shows grub rescue

A: if you again install ubuntu (or any distro) alongside your windows then you can get both OSes again.Or if you dont want to use dual boot then install your windows again.You should format drive c while installing new windows in it.Your problem will be solved.


text:
Q: Finding a 1-Dimensional Mass Distribution Past Discussion
There have been a lot of questions and discussions regarding determining the mass distribution of various bodies through non-destructive purposes. Here are a few:
Determination of mass density distribution of an object
How can I determine whether the mass of an object is evenly distributed?
The general conclusion that I reached after reading questions like these is that by mechanics alone, there is no way to positively determine the mass distribution of a 3-Dimensional object. The simplest arguments typically involved spherical masses and newton's shell theorem.
My Problem
My problem is a simplified case of this general problem that I hope can be solved more easily. I have a stick of balsa wood with dimensions 1/8" x 1/8" x 36", and I would like to know its mass distribution. Because it is so slender, it can be safely treated like a 1-Dimensional object with a density function $\rho(x)$ that depends only on variable. I can find the center of mass very easily just by balancing it, but beyond that I am stuck. I would really like to find an estimation for $\rho(x)$ that is accurate to about the 1" or 1/2" scale.
Solving It
One assumption that can be made is that the young's modulus, $E$, of the wood varies linearly with density. This might be useful for solutions that measure the deflection of the wood under different forces.
First, I am looking for solutions using the simplest methods and tools. I have a scale accurate to 0.01g (the whole stick weighs about 2.60g) and a micrometer that measures to 0.001". If a solution is possible that uses only these tools and other common and accessible ones, that would be best.
If that is not possible, I would still like to hear other more complex approaches that might require advanced equipment or might simply be unrealistic in practice.
EDIT:
The reason I need to solve this problem is that I am building an 18g, 8" tall structure for a competition that must hold over 600 pounds. I know the mass distributions of each specific stick can vary greatly and be quite unpredictable. Since the structure is subject to such extreme forces, small imperfections can significantly affect performance. If one of my 8" columns has 60% of its mass distributed to its lower half, then it will be weaker in the top half. For this reason it is beneficial for me to select wood that is nearly homogenous, and statistical methods (finding variance, etc...) are not particularly useful in this case because I need to be 100% sure that the wood I select is evenly distributed.

A: The easiest way to determine the uniformity of your slabs of wood is to take an x-ray. Seriously. This image is of an x-ray of a piece of wood where the dark regions are cavities created by termites eating away at it (the termites are the white things inside the cavities).

If you don't want to take an x-ray (or can't afford one), then just assume that since your wood is 1/8" square thick, it's fairly unlikely that the density is that far off from uniform. If you measure the center of mass and it's pretty darn close to dead center, I'd say it's probably good enough to be about 80-90% certain (depending on proximity to center) that it's uniform.


text:
Q: Node.js Socket.io - Server setInterval running at half speed, full speed only when socket.on is called My server is acting weird -- the updating setInterval under Update LOBBIES is set to run @ 1000/60ms or 60cps, which I'm only getting a steady 34cps. But when socket.emit('angle') is used from CLIENT side, it runs smoothly at 60cps up until socket.emit('angle') stops, then returns back to 34cps. It's been 3 days and I still have absolutely no idea. Code doesn't seem to have a throttle issue, and weirdly enough, works better when a socket.on event is called for the angle only, not others. Doesn't make any sense! Any ideas?
HTML/Javascript Client
User.onConnect = (socket) => {
    var lobbies = [];
    socket.on('updateLobbies', (data) => {
        $('#menu-screen-navigation-display-play ul').empty();
        $('#menu-screen-navigation-display-play ul').append(
            "
" +
            "
" +
            "       " +
            "           " +
            "       	" +
            "       " +
            "           Lobby" +
            "       	" +
            "       " +
            "           Map" +
            "       	" +
            "       " +
            "           Game Mode" +
            "       	" +
            "       " +
            "           Players" +
            "       	" +
            "       " +
            "           " +
            "       	" +
            "
" +
            "
");
        $('#menu-screen-navigation-display-play ul').append(
            "
" +
            "
" +
            "       " +
            "           " +
            "       	" +
            "       " +
            "           " +
            "       	" +
            "       " +
            "           " +
            "       	" +
            "       " +
            "           " +
            "       	" +
            "       " +
            "           " +
            "       	" +
            "       " +
            "           " +
            "       	" +
            "
" +
            "
");
        for(let i in data){
            lobbies[i] = data[i];

            switch(lobbies[i].mode){
                case 'Outbreak': {
                    lobbies[i].modeColor = 'green';

                    break;
                }
                default: {
                    lobbies[i].modeColor = 'white';
                }
            }
            switch(lobbies[i].map){
                case 'Urban Delight': {
                    lobbies[i].mapSrc = 'img/ui/map-icons/urbanDelight.png';

                    break;
                }
                default: {
                    break;
                }
            }

            $('#menu-screen-navigation-display-play ul').append(
                "
" +
                "
" +
                "       " +
                "           " +
                "       	" +
                "       " +
                "           " + lobbies[i].title + "" +
                "       	" +
                "       " +
                "           " + lobbies[i].map + "" +
                "       	" +
                "       " +
                "           " + lobbies[i].mode + "" +
                "       	" +
                "       " +
                "           " + lobbies[i].online + " / " + lobbies[i].max + "" +
                "       	" +
                "       " +
                "           <button id='"+ lobbies[i].title + "' class='bubble'>Join</button>" +
                "       	" +
                "
" +
                "
");

            $('#'+lobbies[i].title).click(function(){
                playAudio(SFX['pop']);
                socket.emit('lobby.join', this.id);
                $('#menu-screen').hide();
                $('#menu-canvas').hide();
                $('#game-screen').show();
                MUSIC['menu'].pause();
                MUSIC['menu'].currentTime = 0;

                game(socket);
            });
        }
    });
    socket.on('gameID', (data) => {
        MAIN.id = data;
    });
    socket.on('sendClientChat', (data) => {
        if(data.user == 'server'){
            $("#chat-list").append(`<li><span class="chat-message" style="color:rgba(255,255,255,0.8);"> ${data.msg}</span></li>`);
        }
        else {
            $("#chat-list").append(`<li><span class="chat-message"><span style="color:red;">${data.user}:</span> ${chatFilter(data.msg)}</span></li>`);
        }
        $("#chat-list").scrollTop($("#chat-list").prop('scrollHeight'));
    });
    socket.on('lobbyinfo', (data) => {
        MAP = data;
    });
    socket.on('refresh', (data) => {
        PLAYER_LIST = data.players;
        for(var P in PLAYER_LIST){
            if(MAIN.id == PLAYER_LIST[P].id){
                MAIN.position = PLAYER_LIST[P].position;
                break;
            }
        }
        $('#serverCPS').text(data.server.cps);
    });
}

var controlReady = {
    up:         true,
    down:       true,
    left:       true,
    right:      true,
    Q:          true,
    E:          true,
    R:          true,
    SHIFT:      true,
    SPACE:      true,
    ENTER:      true,
    click:      true
};
function controls(mobile, socket){
    if(mobile){
        $('#touchable-screen').show();
        document.getElementById("touchable-screen").addEventListener("touchstart", function(event){
            event.preventDefault();
            event.stopImmediatePropagation();

            emitMouseClick(true);
            emitMouseAngle(socket, event.touches[0]);
        });
        document.getElementById("touchable-screen").addEventListener("touchmove", function(event){
            event.preventDefault();
            event.stopImmediatePropagation();

            emitMouseAngle(socket, event.touches[0]);
        });
        document.getElementById("touchable-screen").addEventListener("touchend", function(event){
            event.preventDefault();
            event.stopImmediatePropagation();

            emitMouseClick(false);
            emitMouseAngle(socket, event.touches[0]);
        });

        var joystickRadius  = Math.round(window.innerHeight/100 * 5);

        document.getElementById("joystick-left").style.width    = Math.round(window.innerHeight/100 * 30) +"px";
        document.getElementById("joystick-left").style.height   = Math.round(window.innerHeight/100 * 30) +"px";
        document.getElementById("joystick-left").style.left     = Math.round(window.innerHeight/100 * 3) +"px";
        document.getElementById("joystick-left").style.bottom   = Math.round(window.innerHeight/100 * 3) +"px";

        document.getElementById("joystick-left-stick").style.width  = Math.round(window.innerHeight/100 * 20) +"px";
        document.getElementById("joystick-left-stick").style.height     = Math.round(window.innerHeight/100 * 20) +"px";
        document.getElementById("joystick-left-stick").style.right  = Math.round(window.innerHeight/100 * 5) +"px";
        document.getElementById("joystick-left-stick").style.bottom     = Math.round(window.innerHeight/100 * 2.5) +"px";

        let myStickLeft = new JoystickController("joystick-left-stick", joystickRadius, 8);

        document.getElementById("joystick-right").style.width   = Math.round(window.innerHeight/100 * 30) +"px";
        document.getElementById("joystick-right").style.height  = Math.round(window.innerHeight/100 * 30) +"px";
        document.getElementById("joystick-right").style.right   = Math.round(window.innerHeight/100 * 3) +"px";
        document.getElementById("joystick-right").style.bottom  = Math.round(window.innerHeight/100 * 3) +"px";

        document.getElementById("joystick-right-stick").style.width     = Math.round(window.innerHeight/100 * 20) +"px";
        document.getElementById("joystick-right-stick").style.height    = Math.round(window.innerHeight/100 * 20) +"px";
        document.getElementById("joystick-right-stick").style.right     = Math.round(window.innerHeight/100 * 5) +"px";
        document.getElementById("joystick-right-stick").style.bottom    = Math.round(window.innerHeight/100 * 2.5) +"px";

        let myStickRight = new JoystickController("joystick-right-stick", joystickRadius, 8);

        $('#joystick-left').show();
        $('#joystick-right').show();
        $('#chat-input').hide();
    }
    else{
        document.addEventListener('mousemove', function(event){
            emitMouseAngle(socket, event);
        });
        document.addEventListener('mousedown', function(event){
            emitMouseAngle(socket, event);
            emitMouseClick(true);
        });
        document.addEventListener('mouseup', function(event){
            emitMouseAngle(socket, event);
            emitMouseClick(false);
        });
    }
    document.addEventListener('keydown', (event) => {
        if(controlReady.up && (event.keyCode === 87 || event.keyCode == 38)){//UP
            controlReady.up = false;
            socket.emit('controls',{inputId:'up',state:true});
        }
        if(controlReady.down && (event.keyCode == 83 || event.keyCode == 40)){//DOWN
            controlReady.down = false;
            socket.emit('controls',{inputId:'down',state:true});
        }
        if(controlReady.left && (event.keyCode == 65 || event.keyCode == 37)){//LEFT
            controlReady.left = false;
            socket.emit('controls',{inputId:'left',state:true});
        }
        if(controlReady.right && (event.keyCode == 68 || event.keyCode == 39)){//RIGHT
            controlReady.right = false;
            socket.emit('controls',{inputId:'right',state:true});
        }

        if(controlReady.Q && event.keyCode == 81){//Q
            controlReady.Q = false;
            socket.emit('controls',{inputId:'Q',state:true});
        }
        if(controlReady.E && event.keyCode == 69){//E
            controlReady.E = false;
            socket.emit('controls',{inputId:'E',state:true});
        }
        if(controlReady.R && event.keyCode == 82){//R
            controlReady.R = false;
            socket.emit('controls',{inputId:'R',state:true});
        }
        if(controlReady.SHIFT && event.keyCode == 16){//SHIFT
            controlReady.SHIFT = false;
            socket.emit('controls',{inputId:'shift',state:true});
        }
        if(controlReady.SPACE && event.keyCode == 32){//SPACE
            controlReady.SPACE = false;
            socket.emit('controls',{inputId:'space',state:true});
        }
    });
    document.addEventListener('keyup', (event) => {
        if(!controlReady.up && (event.keyCode === 87 || event.keyCode == 38)){//UP
            controlReady.up = true;
            socket.emit('controls',{inputId:'up',state:false});
        }
        if(!controlReady.down && (event.keyCode == 83 || event.keyCode == 40)){//DOWN
            controlReady.down = true;
            socket.emit('controls',{inputId:'down',state:false});
        }
        if(!controlReady.left && (event.keyCode == 65 || event.keyCode == 37)){//LEFT
            controlReady.left = true;
            socket.emit('controls',{inputId:'left',state:false});
        }
        if(!controlReady.right && (event.keyCode == 68 || event.keyCode == 39)){//RIGHT
            controlReady.right = true;
            socket.emit('controls',{inputId:'right',state:false});
        }

        if(!controlReady.Q && event.keyCode == 81){//Q
            controlReady.Q = true;
            socket.emit('controls',{inputId:'Q',state:false});
        }
        if(!controlReady.E && event.keyCode == 69){//E
            controlReady.E = true;
            socket.emit('controls',{inputId:'E',state:false});
        }
        if(!controlReady.R && event.keyCode == 82){//R
            controlReady.R = true;
            socket.emit('controls',{inputId:'R',state:false});
        }
        if(!controlReady.SHIFT && event.keyCode == 16){//false
            controlReady.SHIFT = true;
            socket.emit('controls',{inputId:'shift',state:false});
        }
        if(!controlReady.SPACE && event.keyCode == 32){//SPACE
            controlReady.SPACE = true;
            socket.emit('controls',{inputId:'space',state:false});
        }
    });

    $('#chat-input').focus(() => {
        controlReady.ENTER = false;
    });
    $('#chat-input').blur(() => {
        controlReady.ENTER = true;
    });
    function emitMouseAngle(socket, event) {
        var mouse;
        if(settings.mobile){
            mouse = {
                x: Math.round(event.clientX * pixelDensityRatio),
                y: Math.round(event.clientY * pixelDensityRatio)
            };
        }
        else {
            mouse = {
                x: Math.round(event.x * pixelDensityRatio),
                y: Math.round(event.y * pixelDensityRatio)
            };
        };
        var angle = Math.floor(Math.atan2(mouse.y - center.y, mouse.x - center.x) * 100)/100;
        socket.emit('angle', angle);
    }
    function emitMouseClick(click){
        if(click){
            socket.emit('controls',{inputId:'click',state:true});
        }
        else{
            socket.emit('controls',{inputId:'click',state:false});
        }
    }
}

Node.js Server Code w/ Redis
const os            = require('os'),
      cluster       = require('cluster'),
      cores         = os.cpus();
var clusterCount = 0;

process.on('uncaughtException', function (exception) {
  console.log(exception); // to see your exception details in the console
  // if you are on production, maybe you can send the exception details to your
  // email as well ?
});

if(cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);
    // Fork workers
    for (let i = 0; i < cores.length; i++) {
        cluster.fork();
    }
    cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} died`);
    });
}
else{
    const http          = require('http'),
          express       = require('express'),
          socketio      = require('socket.io'),
          process       = require('process'),
          config        = require('./config.js'),
          socketioRedis = require('socket.io-redis'),
          redis         = require('./redis.js');

    const settings = {
        cps: 60
    };

    var LOBBY_LIST = {};

    redis.subscriber.on('connect', () => {
        console.log(`worker ${process.pid} connected to redis(subscriber)`);

        redis.subscriber.subscribe('LOBBIES');

        redis.subscriber.on('message', (channel, data) => {
            var parsedData = JSON.parse(data);
            switch(channel){
                case 'LOBBIES': {
                    //console.log(`Lobby -- ${parsedData.title} | ${parsedData.map} | ${parsedData.mode} | ${parsedData.max}`);
                    LOBBY_LIST[parsedData.title] = parsedData;
                    break;
                }
                default: {
                    break;
                }
            }
        });
        redis.subscriber.on('users', (channel, data) => {
            console.log(`${data.id} connected to worker ${data.server}`);
        });
    });
    redis.publisher.on('connect', () => {
        console.log(`worker ${process.pid} connected to redis(publisher)`);

        var cpu = cores[clusterCount];
        var app = express();
        var port = process.env.PORT || process.argv[2] || 8080;
        var server = app.listen(port);
        var io = socketio(server);
        var User = {};
        var SOCKET_LIST = {};
        var PLAYER_LIST = {};

        io.adapter(socketioRedis({host: config.redis_host, port: config.redis_port}));
        io.on('connection', (socket) => {
            User.onConnect(socket);
        });
        User.onConnect = (socket) => {
            console.log(`${socket.id} connected to worker ${process.pid}`);
            var id = socket.id;
            var player = new Player(id);

            SOCKET_LIST[id] = socket;
            SOCKET_LIST[id].spamGuard = 0;

            var updateLobbies = setInterval(() => {
                socket.emit('updateLobbies', LOBBY_LIST);
            }, 3000);

            socket.emit('gameID', id);

            socket.on('serverPing', (ping) => {
                socket.emit('serverPong', ping);
            });
            socket.on('sendServerChat', (data) => {
                if(data != ' ' && data != '  ' && data != '   '){
                    if(SOCKET_LIST[socket.id].spamGuard < 3){
                        if(data.length < 100){
                            var chat = {
                                user: socket.id,
                                msg: data
                            };
                            io.sockets.emit('sendClientChat', chat);
                            SOCKET_LIST[socket.id].spamGuard++;
                        }
                    }
                    else{
                        var chat = {
                            user: 'server',
                            msg: 'You\'re sending messages too fast!'
                        };
                        socket.emit('sendClientChat', chat);
                    }
                }
                else {
                    var chat = {
                        user: 'server',
                        msg: 'Can\'t send an empty message!'
                    };
                    socket.emit('sendClientChat', chat);
                }
            });
            socket.on('lobby.join', (lobby) => {
                var user = {
                    id: socket.id,
                    lobby: lobby
                };
                redis.publisher.publish('JOINROOM', JSON.stringify(user));

                socket.emit('lobbyinfo', map[LOBBY_LIST[lobby].map]);
            });
            socket.on('lobby.leave', () => {
                var user = {
                    id: socket.id,
                    lobby: lobby
                };
                redis.publisher.publish('LEAVEROOM', JSON.stringify(user));
            });
            socket.on('disconnect', () => {
                User.onDisconnect(socket);
            });
            socket.on('controls', (data) => {
                if(data.inputId === 'up'){//UP
                    player.controls.pressingUp = data.state;
                }
                else if(data.inputId === 'down'){//DOWN
                    player.controls.pressingDown = data.state;
                }
                else if(data.inputId === 'left'){//LEFT
                    player.controls.pressingLeft = data.state;
                }
                else if(data.inputId === 'right'){//RIGHT
                    player.controls.pressingRight = data.state;
                }
                else if(data.inputId === 'Q'){//Q
                    player.controls.pressingQ = data.state;
                }
                else if(data.inputId === 'E'){//E
                    player.controls.pressingE = data.state;
                }
                else if(data.inputId === 'R'){//R
                    player.controls.pressingR = data.state;
                }
                else if(data.inputId === 'shift'){//SHIFT
                    player.controls.pressingSHIFT = data.state;
                }
                else if(data.inputId === 'space'){//SPACE
                    player.controls.pressingSPACE = data.state;
                }

                if(data.inputId === 'click'){//Click
                    player.controls.leftClick = data.state;
                }
            });
            socket.on('angle', (data) => {
                player.angle = data;
            });
        };
        User.onDisconnect = (socket) => {
            console.log(`${socket.id} disconnected from worker ${process.pid}`);
            delete SOCKET_LIST[socket.id];
            delete PLAYER_LIST[socket.id];
            socket.disconnect();
        };

        var Player = function(id){
            var self = {
                id: id,
                username: 'player',
                server: '',
                position: {
                    x: 0,
                    y: 0
                },
                speed: 500,
                angle: degrees_to_radians(Math.floor(Math.random()*360)),
                controls: {
                    leftClick:      false,
                    pressingUp:     false,
                    pressingDown:   false,
                    pressingLeft:   false,
                    pressingRight:  false,
                    pressingQ:      false,
                    pressingE:      false,
                    pressingR:      false,
                    pressingSHIFT:  false,
                    pressingSPACE:  false
                }
            };
            self.updatePosition = function(){
                if(self.controls.pressingUp){
                    self.position.y -= self.speed / settings.cps;
                    if(self.position.y < 0){
                        self.position.y = 0;
                    }
                }
                if(self.controls.pressingDown){
                    self.position.y += self.speed / settings.cps;
                    if(self.position.y > 9999){
                        self.position.y = 9999;
                    }
                }
                if(self.controls.pressingLeft){
                    self.position.x -= self.speed / settings.cps;
                    if(self.position.x < 0){
                        self.position.x = 0;
                    }
                }
                if(self.controls.pressingRight){
                    self.position.x += self.speed / settings.cps;
                    if(self.position.x > 9999){
                        self.position.x = 9999;
                    }
                }
            };

            PLAYER_LIST[self.id] = self;
            return self;
        };
        Player.update = function(){
            var pack = [];
            for(var i in PLAYER_LIST){
                var player = PLAYER_LIST[PLAYER_LIST[i].id];

                player.updatePosition();

                pack.push({
                    id: player.id,
                    position: player.position,
                    angle: player.angle
                });
            }
            return pack;
        };

        //Spam Guard
        setInterval(() => {
            for(var id in SOCKET_LIST){
                if(SOCKET_LIST[id].spamGuard > 0){
                    SOCKET_LIST[id].spamGuard--;
                }
            }
        }, 3000);
        //Update LOBBIES
        setInterval(() => {
            //for(var L in LOBBY_LIST){
            //  var lobby = LOBBY_LIST[L];
                checkCPS();

                var pack = {
                    players: Player.update(),
                    server: {
                        cps: cpsSave
                    }
                };

                for(var S in SOCKET_LIST){
                    var user = SOCKET_LIST[SOCKET_LIST[S].id];

                    user.emit('refresh', pack);
                }
            //}
        }, 1000/settings.cps);

        var map = [
            'Urban Delight',
            'Graveyard',
            'Farmlands'
        ];
        for(var i in map){
            var mapName = map[i];

            map[mapName] = {
                tileSize: 100,
                matrix: [],
            };
            for(var j = 0; j < 100; j++){
                map[mapName].matrix[j] = [];
                for(var k = 0; k < 100; k++){
                    map[mapName].matrix[j][k] = 0;
                }
            }
        }
        function degrees_to_radians(degrees){
            var pi = Math.PI;
            return degrees * (pi/180);
        }
        function radians_to_degrees(radians){
            var pi = Math.PI;
            return radians / (pi/180);
        }
        var cps = 0,
            cpsCheck = 0,
            cpsSave = 0;
        function checkCPS(){
            cps++;
            var d = new Date().getSeconds();
            if(cpsCheck != d){
                cpsCheck = d;
                cpsSave = cps;
                cps = 0;
            }
        }
        console.log(`Worker ${process.pid} started on port: ${port} | ${cpu.model}`);
        clusterCount++;
    });
}


text:
Q: Android notification icon cannot display off I wrote some Android codes to display on and off an icon. However, after run the codes, the icon can display but not disappear (display off). It is always on the notification bar. If possible, could you help me have a look. THX
 final Notification.Builder mBuilder = new Notification.Builder(getApplicationContext());
        final NotificationManager mNotifyManager =
                (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
        final int mNotifyId = 1;
        final String TITLE = "abc";
        final String MSG = "abc is active.";

    Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_notification);
            mBuilder.setContentTitle(TITLE)
                    .setContentText(MSG)
                    .setSmallIcon(R.mipmap.ic_dark)
                    .setLargeIcon(largeIcon)
                    .setOngoing(true)
                    .setAutoCancel(false);

        final Handler handler= new Handler();

        final Runnable r = new Runnable() {
            public void run() {
                mNotifyManager.notify(mNotifyId, mBuilder.build());
                mNotifyManager.cancel(mNotifyId);
                handler.postDelayed(this, 1000);
            }
        };

        handler.postDelayed(r, 1000);


text:
Q: Does an IO monad make sense in a language like C# After spending a lot of time reading and thinking, I think I have finally grasped what monads are, how they work, and what they're useful for. My main goal was to figure out if monads were something I could apply to my daily work in C#.
When I started learning about monads, I got the impression that they are magical, and that they somehow make IO and other non-pure functions pure.
I understand the importance of monads for things like LINQ in .Net, and Maybe is very useful for dealing with functions that don't return valid values. And I also appreciate the need to limit statefulness in code and to isolate external dependencies, and I was hoping monads would help with those too.
But I've finally come to the conclusion that monads for IO and handling state are a necessity for Haskell, because Haskell has no other way to do it (otherwise, you couldn't guarantee sequencing, and some calls would be optimized away.) But for more mainstream languages, monads are not a good fit for these needs, since most languages already handle and state and IO easily.
So, my question is, is it fair to say that the IO monad is really only useful in Haskell? Is there a good reason to implement an IO monad in, say, C#?

A: The ability to know if a function has side effects just by looking at its signature is very useful when trying to understand what the function does. The less a function can do, the less you have to understand! (Polymorphism is another thing that helps restrict what a function can do with its arguments.)
In many languages that implement Software Transactional Memory, the documentation has warnings like the following:

I/O and other activities with side-effects should be avoided in
  transactions, since transactions will be retried.

Having that warning become a prohibition enforced by the type system can make the language safer.
There are optimizations can only be performed with code that is free of side effects. But the absence of side effects may be difficult to determine if you "allow anything" in the first place.
Another benefit of the IO monad is that, since IO actions are "inert" unless they lie in the path of the main function, it's easy to manipulate them as data, put them in containers, compose them at runtime, and so on.
Of course, the monadic approach to IO has its disadvantages. But it does have advantages besides "being one of the few ways of doing I/O in a pure lazy language in a flexible and principled manner".

A: As always, the IO monad is special and difficult to reason about. It's well known in the Haskell community that while IO is useful, it does not share many of the benefits other monads do. It's use is, as you've remarked, motivated greatly by its privileges position instead of it being a good modeling tool.
With that, I'd say it's not so useful in C# or, really, any language that isn't trying to completely contain side effects with type annotations.
But it's just one monad. As you've mentioned, Failure shows up in LINQ, but more sophisticated monads are useful even in a side-effecting language.
For instance, even with arbitrary global and local state environments, the state monad will indicate both the beginning and end of a regime of actions which work on some privileged kind of state. You don't get the side-effect elimination guarantees Haskell enjoys, but you still get good documentation.
To go further, introducing something like a Parser monad is a favorite example of mine. Having that monad, even in C#, is a great way to localize things like non-deterministic, backtracking failure performed while consuming a string. You can obviously do that with particular kinds of mutability, but Monads express that a particular expression performs a useful action in that effectful regime without regard to any global state you might also be involving.
So, I'd say yes, they're useful in any typed language. But IO as Haskell does it? Maybe not so much.

A: At work, we use monads to control IO in our C# code on our most important pieces of business logic. Two examples are our financial code and code that finds solutions to an optimization problem for our customers.
In our financial code, we use a monad to control IO writing to and reading from our database. It essentially consists of a small set of operations and an abstract syntax tree for the monad operations. You could imagine it's something like this (not actual code):
interface IFinancialOperationVisitor<T, out R> : IMonadicActionVisitor<T, R> {
    R GetTransactions(GetTransactions op);
    R PostTransaction(PostTransaction op);
}

interface IFinancialOperation<T> {
    R Accept<R>(IFinancialOperationVisitor<T, R> visitor);
}

class GetTransactions : IFinancialOperation<IError<IEnumerable<Transaction>>> {
    Account Account {get; set;};

    public R Accept<R>(IFinancialOperationVisitor<R> visitor) {
        return visitor.Accept(this);
    }
}

class PostTransaction : IFinancialOperation<IError<Unit>> {
    Transaction Transaction {get; set;};

    public R Accept<R>(IFinancialOperationVisitor<R> visitor) {
        return visitor.Accept(this);
    }
}

which is essentially the Haskell code
data FinancialOperation a where
     GetTransactions :: Account -> FinancialOperation (Either Error [Transaction])
     PostTransaction :: Transaction -> FinancialOperation (Either Error Unit)

along with an abstract syntax tree for the construction of actions in a monad, essentially the free monad:
interface IMonadicActionVisitor<in T, out R> {
    R Return(T value);
    R Bind<TIn>(IMonadicAction<TIn> input, Func<TIn, IMonadicAction<T>> projection);
    R Fail(Errors errors);
}

// Objects to remember the arguments, and pass them to the visitor, just like above

/*
Hopefully I got the variance right on everything for doing this without higher order types,
which is how we used to do this. We now use higher order types in c#, more on that below.
Here, to avoid a higher-order type, the AST for monadic actions is included by inheritance
in
*/

In the real code, there are more of these so we can remember that something was built by .Select() instead of .SelectMany() for efficiency. A financial operation, including intermediary computations still has type IFinancialOperation<T>. The actual performance of the operations is done by an interpreter, which wraps all the database operations in a transaction and deals with how to roll that transaction back if any component is unsuccessful. We also use a interpreter for unit testing the code.
In our optimization code, we use a monad for controlling IO to get external data for optimization. This allows us to write code that is ignorant of how computations are composed, which lets us use exactly the same business code in multiple settings:

*

*synchronous IO and computations for computations done on demand

*asynchronous IO and computations for many computations done in parallel

*mocked IO for unit tests

Since the code needs to be passed which monad to use, we need an explicit definition of a monad. Here's one. IEncapsulated<TClass,T> essentially means TClass<T>. This lets the c# compiler keep track of all three pieces of the type of monads simultaneously, overcoming the need to cast when dealing with monads themselves.
public interface IEncapsulated<TClass,out T>
{
    TClass Class { get; }
}

public interface IFunctor<F> where F : IFunctor<F>
{
    // Map
    IEncapsulated<F, B> Select<A, B>(IEncapsulated<F, A> initial, Func<A, B> projection);
}

public interface IApplicativeFunctor<F> : IFunctor<F> where F : IApplicativeFunctor<F>
{
    // Return / Pure
    IEncapsulated<F, A> Return<A>(A value);
    IEncapsulated<F, B> Apply<A, B>(IEncapsulated<F, Func<A, B>> projection, IEncapsulated<F, A> initial);
}

public interface IMonad<M> : IApplicativeFunctor<M> where M : IMonad<M>
{
    // Bind
    IEncapsulated<M, B> SelectMany<A, B>(IEncapsulated<M, A> initial, Func<A, IEncapsulated<M, B>> binding);
    // Bind and project
    IEncapsulated<M, C> SelectMany<A, B, C>(IEncapsulated<M, A> initial, Func<A, IEncapsulated<M, B>> binding, Func<A, B, C> projection);
}

public interface IMonadFail<M,TError> : IMonad<M> {
    // Fail
    IEncapsulated<M, A> Fail<A>(TError error);
}

Now we could imagine making another class of monad for the portion of IO our computations need to be able to see:
public interface IMonadGetSomething<M> : IMonadFail<Error> {
    IEncapsulated<M, Something> GetSomething();
}

Then we can write code that doesn't know about how computations are put together
public class Computations {

    public IEncapsulated<M, IEnumerable<Something>> GetSomethings<M>(IMonadGetSomething<M> monad, int number) {
        var result = monad.Return(Enumerable.Empty<Something>());
        // Our developers might still like writing imperative code
        for (int i = 0; i < number; i++) {
            result = from existing in r1
                     from something in monad.GetSomething()
                     select r1.Concat(new []{something});
        }
        return result.Select(x => x.ToList());
    }
}

This can be reused in both a synchronous and asynchronous implementation of an IMonadGetSomething<>. Note that in this code, the GetSomething()s will happen one after another until there's an error, even in an asynchronous setting. (No this is not how we build lists in real life)

A: In a language like C# where you can do IO anywhere, an IO monad doesn't really have any practical use. The only thing you'd want to use it for is controlling side effects, and since there's nothing stopping you from performing side effects outside the monad, there's not really much point.
As for the Maybe monad, while it seems potentially useful, it only really works in a language with lazy evaluation. In the following Haskell expression, the second lookup isn't evaluated if the first returns Nothing:
doSomething :: String -> Maybe Int
doSomething name = do
    x <- lookup name mapA
    y <- lookup name mapB
    return (x+y)

This allows the expression to "short circuit" when a Nothing is encountered. An implementation in C# would have to perform both lookups (I think, I'd be interested to see a counter-example.) You're probably better-off with if statements.
Another issue is the loss of abstraction. While it's certainly possible to implement monads in C# (or things which look a little bit like monads), you can't really generalise like you can in Haskell because C# doesn't have higher kinds. For example, a function like mapM :: Monad m => Monad m => (a -> m b) -> [a] -> m [b] (which works for any monad) can't really be represented in C#. You could certainly have something like this:
public List<Maybe<a> mapM<a,b>(Func<a, Maybe<b>>);

which would work for a specific monad (Maybe in this case), but It's not possible to abstract-away the Maybe from that function. You'd have to be able to do something like this:
public List<m<a> mapM<m,a,b>(Func<a, m<b>>);

which isn't possible in C#.

A: I use Haskell and F# regularly and I've never really felt like using an IO or state monad in F#.
The main reason for me is that in Haskell, you can tell from the type of something that it doesn't use IO or state, and that's a really valuable piece of information.
In F# (and C#) there's no such general expectation on other people's code, and so you won't benefit much from adding that discipline to your own code, and you'll pay some general overhead (mainly syntactic) for sticking to it.
Monads also don't work too well on the .NET platform because of the lack of higher-kinded types: while you can write monadic code in F# with workflow syntax, and in C# with a bit more pain, you can't easily write code that abstracts over multiple different monads.

A: You ask "Do we need an IO monad in C#?" but you should ask instead "Do we need a way to reliably obtain purity and immutability in C#?".
The key benefit would be controlling side-effects. Whether you do that using monads or some other mechanism doesn't matter. For example, C# could allow you to mark methods as pure and classes as immutable. That would go a great way towards taming side-effects.
In such a hypothetical version of C# you'd try to make 90% of the computation pure, and have unrestricted, eager IO and side-effects in the remaining 10%. In such a world I do not see so much of a need for absolute purity and an IO monad.
Note, that by just mechanically converting side-effecting code to a monadic style you gain nothing. The code does not improve in quality at all. You improve the code quality by being 90% pure, and concentrating the IO into small, easily reviewable places.


text:
Q: Vue - In a reusuable component running a method only for the respective component I have some reusuable components and whenever I add one, it gets pushed in an array etc. The question is: How do I make sure the methods in those reusuable components only run for the respective component and not for all of them.
Example: Using an @click event to open a modal, the modal shows up the exact number of times I added the component (expected, but I want to change this so it only shows up once and only for the respective component).
Adding components:
<template v-for="(comp, index) in comps">
  <component
       :is="comp"
       :key="index"
       :currentIndex="currentIndex"
       v-on:delete="deleteComp($event)"
   ></component>
</template>

Same method inside some components:
methods: {
  showModal() {
   this.$bvModal.show('modalSmall');
  }
}

A: The best way to do this is to pass an id as props for the different components.

<template v-for="(comp, index) in comps">
  <component
       ....
       :id="comps.id" // you could create a computed property to generate an id based on a number or some other unique identifier
       ....
   ></component>
</template>

Then in your component,
Component.vue

props: {
  id: {
    type: string,
    required: true
  }
}

methods: {
  showModal() {
   this.$bvModal.show(id);
  }
}

Remember to change your id for each modal, in the template, from modalSmall to id (the id prop).


text:
Q: Kernel SVC keeps getting errors on parameters in RandomSearchCV *This post continues from here
classifier = SVC()
parameters = {"kernel": ["rbf", "linear"],
              "gamma": scipy.stats.expon(scale=.1),
              "c": scipy.stats.expon(scale=100),
              "class_weight": ["balanced", None]}

randomcv = RandomizedSearchCV(estimator=classifier, param_distributions=parameters,
                              scoring='accuracy', cv=10, n_jobs=-1,
                              random_state=0)
randomcv.fit(x_tu, y_tu)

Hi, I'm not sure what's causing the problem with the code above.
I'm getting a really long error message from here, and can't read what the error is telling me.
The same problem occurred when I was using a different classifier, but was able to solve them by changing the parameter range.
For this one, nothing seems to work for me.

A: The error says

Invalid parameter 'c' for SVC()

This is because the actual parameter is C (capital C), see SVC. Change the key c in the parameters to C and that should work


text:
Q: Fastest way to apply alpha channel to image in OpenCV I'm currently using the following function to apply my alpha channels (stored as separate GRAY cv::Mats), to images:
void percepUnit::applyAlpha() {

    int x,y,w,h;
    /*vector<cv::Mat> channels;
    if (image.rows == mask.rows and image.cols == mask.cols) {
        cv::split(image,channels); // break image into channels
        channels.push_back(mask); // append alpha channel

        cv::merge(channels,alphaImage); // combine channels
    }*/

    // Avoid merge
    cv::Mat src[] = {this->image, this->mask};
    int from_to[] = {0,0, 1,1, 2,2, 3,3};
    this->alphaImage = Mat(image.rows, image.cols, CV_8UC4);
    cv::mixChannels(src, 2, &(this->alphaImage), 1, from_to, 4); // &(*alphaImage)?
}

I've had to increase the resolution of the cv::Mats to 1280x720 (due to: How to replace an instance with another instance via pointer?) and now this function is running quite slowly, using up almost 50% of what is already a heavy meanshift segmentation application.
Any suggestions on how to apply these alpha channels faster? I'm running OpenCV with GPU, if you have any GPU based solutions.)

A: I ended up doing split / merge on the GPU:
void percepUnit::applyAlpha() {

    cv::gpu::GpuMat tmpImage, tmpMask, tmpAlphaImage;
    std::vector<cv::gpu::GpuMat> channels;

    tmpImage.upload(this->image);
    tmpMask.upload(this->mask);

    cv::gpu::split(tmpImage,channels); // break image into channels
    channels.push_back(tmpMask); // append alpha channel
    cv::gpu::merge(channels,tmpAlphaImage); // combine channels

    tmpAlphaImage.download(this->alphaImage);

    tmpAlphaImage.release();
    tmpImage.release();
    tmpMask.release();

    channels[0].release();
    channels[1].release();
    channels[2].release();
}