text:
Q: Prove that B is a basis for a topology Let $X = \{0,1,2,3,\ldots\}$ (the non-negative integers), let $$B_1 = \{\{n\} : n \in X \text{ and }n > 0\}= \{\{1\}, \{2\}, \{3\},\ldots\}$$  $$B_2 = \{Z \subset X : X \setminus Z = \{1,2,\ldots n\} \text{ for some }n \in \mathbb{N} \}$$
a) Prove that $B$ is a basis for a topology on $X$.
b) Let $T$ be the topology from part 1. Prove that $(X; T )$ is $T_2$.

A: To show that $\mathscr{B}$ is a base for a topology on $X$, you must show two things:

*

*For each $x\in X$ there is some $B\in\mathscr{B}$ such that $x\in B$, and

*for any $B_0,B_1\in\mathscr{B}$ and any $x\in B_0\cap B_1$, there is some $B\in\mathscr{B}$ such that $x\in B\subseteq B_0\cap B_1$.

In your case $\mathscr{B}=\mathscr{B}_1\cup\mathscr{B}_2$, where $$\mathscr{B}_1=\Big\{\{n\}:n\in X\text{ and }n>0\Big\}\;,$$ and $$\mathscr{B}_2=\{X\setminus F:F=\{1,\dots,n\}\text{ for some }n\in\Bbb N\}\;.$$
If $n\in X\setminus\{0\}$, then $n\in\{n\}\in\mathscr{B}_1\subseteq\mathscr{B}$, and $0\in X\setminus\{1\}\in\mathscr{B}_2\subseteq\mathscr{B}$, so condition (1) is satisfied.
Condition (2) is also easy to check. Suppose that $B_0,B_1\in\mathscr{B}$ and $n\in B_0\cap B_1$. If $B_0$ and $B_1$ both belong to $\mathscr{B}_1$, then clearly $B_0=B_1=\{n\}$, and in (2) we can take $B$ to be $B_1$. In fact, you can easily check that if either of $B_0$ and $B_1$ belongs to $\mathscr{B}_1$, we can take that set to be the $B$ of (2): if a member of $\mathscr{B}_1$ intersects a member of $\mathscr{B}$, it must already be a subset of that member. Thus, the only case that requires a little work is when $B_0,B_1\in\mathscr{B}_2$, and I leave you to check that in that case one of them is again a subset of the other.
To show that the resulting topology is Hausdorff ($T_2$), you need only show that if $m$ and $n$ are distinct elements of $X$, there are $B_m,B_n\in\mathscr{B}$ such that $m\in B_m$, $n\in B_n$, and $B_m\cap B_n=\varnothing$. This is dead easy of neither $m$ nor $n$ is $0$: just take $B_m=\{m\}$ and $B_n=\{n\}$. Separating $0$ and some $n>0$ is almost as easy: for you neighborhood of $n$ you will of course choose $\{n\}\in\mathscr{B}_1$, and for your neighborhood of $0$ you'll want some member of $\mathscr{B}_2$ that misses $n$. The simplest choice is $X\setminus\{1,\dots,n\}$, but any $X\setminus\{1,\dots,m\}$ with $m\ge n$ will work just as well.
You should try to convince yourself that this topology on $X$ makes $\langle 1,2,3,\dots\rangle$ a sequence converging to the point $0$. In fact, as Martin noted in the comments, $X$ looks just like the subset of $\Bbb R$ consisting of $0$ and the reciprocals $1/n$ for $0&ltn\in\Bbb N$. Call that subset $Y$. If you take as a base the sets $\{1/n\}$ for integers $n>0$ and the sets $Y\setminus\{1,\frac12,\dots,\frac1n\}$ for integers $n>0$, imitating $\mathscr{B}_1$ and $\mathscr{B}_2$ in your problem, you get the same topology on $Y$ that it inherits from the usual topology on $\Bbb R$, in which $\langle 1,\frac12,\frac13,\dots\rangle$ converges to $0$.

A: I think you mean show $B_i$ is a basis for a topology on $X$, where $B_1$ and $B_2$ are as given. To show $B_1$ is a basis for a topology on $X$, you need only show that if $A,C \in B_1$ and have non-empty intersection, then there is a $V \in B_1$ such that $V$ is contained in $A$'s intersection with $C$. But with $B_1$ if $A \cap C$ is non-void,
$A=C$, so you may choose $V=A=C$ in this case and establish that these sets in $B_1$ are a basis for a topology on $X$. It's a different but similar thing with $B_2$. If $A \in B_2$ and $C \in B_2$ then $X-A =\{1,2,3\ldots,n\}$ and $X-C = \{1,2,3,\ldots m\}$ for some $n$ and $m \in N$. Now $X-A \cup X-C =\{1,2,3,\ldots\max \{m,n\}\}$ so that $X-(A \cap C) = X \cap (X-A) \cup (X-C)$ and from the definition of $B_2$ we see $A \cap C$ is IN $B_2$ (this is stronger than what you need, but does imply that $B_2$ is a basis).
I'll give you some time to think about what neighborhoods of points look like in both topologies to decide if $T$ induced by $B_1$ makes $X$ a $T_2$ space.


text:
Q: Sending status code with response using apex I am working on a rest API using http post to get the params and create a record.  After creating the record I need to send a response with the details of created record along with a status code and message in the response body. I am facing issues while implementing the code.
 below is my code:
@RestResource(urlMapping='/events/*')
global class createEvents {

    @HttpPost
    global static void createEvent(String subject, Datetime startDateTime, Datetime endDateTime, String psaRequestedBy, String recurs,Datetime recStartDateTime, Date recEndDate, Integer recurrenceDayOfWeekMask){

        RestRequest req= RestContext.request;
       RestResponse res = RestContext.response;

        String accountId= req.requestURI.substring(req.requestURI.lastindexOf('/')+1);

        List<Event> events = [select   ShowAs, Disable_Alarm__c, WhatId, Subject, ActivityDate, StartDateTime, EndDateTime, PSA_Requested_by__c, OwnerId, IsRecurrence, RecurrenceStartDateTime, RecurrenceEndDateOnly, RecurrenceType, RecurrenceDayOfWeekMask, RecurrenceInterval from Event
                              where WhatId= :accountId  limit 10];
        system.debug('events list***'+events);

        Event e;

        try{
            if(events.size() ==0){
               e = new Event();
               e.ShowAs = 'Busy';
               e.Disable_Alarm__c = true;
               e.WhatId = accountId;
               e.Subject = subject;
               e.StartDateTime = startDateTime;
               e.EndDateTime = endDateTime;
               e.PSA_Requested_by__c = psaRequestedBy;
               e.OwnerId = UserInfo.getUserId();

                insert e;
              }

              else if(events.size() >0){
                 for(Event eve : events){
             if((startDateTime <= eve.StartDateTime && endDateTime >=  eve.StartDateTime && endDateTime <= eve.EndDateTime) ||
                 (startDateTime <= eve.StartDateTime && endDateTime >= eve.StartDateTime && endDateTime >= eve.EndDateTime) ||
                 (startDateTime >=  eve.StartDateTime && startDateTime <= eve.EndDateTime)){

               // return 'already PSA exist';
              // return '{\'status\':\'failure\',\'status_msg\':\'already PSA exist\'}';
              RestContext.response.statusCode = 500;
             // return res;

             }
               else{
               e = new Event();
               e.Type = 'Planned Site Activity';
               e.ShowAs = 'Busy';
               e.Disable_Alarm__c = true;
               e.WhatId = accountId;
               e.Subject = subject;
               e.StartDateTime = startDateTime;
               e.EndDateTime = endDateTime;
               e.PSA_Requested_by__c = psaRequestedBy;
               e.OwnerId = UserInfo.getUserId();

            }
           }
           insert e;
         }

           }catch(Exception ex){
               system.debug('Error in creating Event'+ex.getMessage());
           }
    }
}

Thank you in advance for the support.

A: Welcome to Salesforce StackExchange, As I understood you have facing issue with implementation logic of error handling / Response of the request.

*

*I would prefer to User Database.insert() rather than Insert DML because it is partial insert the record So easy to response the record which is failing or success. Please read the documentation Database class.

*Use RestResponse

*I created a Response wrapper class for store the detailed info of record/failure.

*So In try-catch block, I used Database.insert() to check if a record is successfully insert or fail with status code 200,400 with error.

*In the catch block, I used 500 status code with error message.

So below is the sudo code
    try {
    RestResponse res = RestContext.response;
    Map < Id, Event > mapToInsert = new Map < Id, Event > ();
    List < Response > lstResponse = new List < Response > ();

    for (Database.SaveResult sr: Database.insert(mapToInsert.values(), false)) {
        String errorMsg = '';
        if (sr.isSuccess()) {
            res.statusCode = 200;
            lstResponse.add(new Response('Successfully Inserted', mapToInsert.get(sr.getId())));
        } else {
            for (Database.Error err: sr.getErrors()) {
                errorMsg = err.getStatusCode() + ': ' + err.getMessage();
            }
            res.statusCode = 400;
            lstResponse.add(new Response(errorMsg, null);
            }
        }
        res.responseBody = Blob.valueOf(JSON.serialize(lstResponse));

    } catch (Exception e) {
        RestResponse res = RestContext.response;
        res.statusCode = 500;
        res.responseBody = Blob.valueOf(JSON.serialize(new Response(e.getMessage(), null)));
    }

    public class Response {
        public String message;
        public Event eventRec;
        public Response(String message, string eventRec) {
            this.message = message;
            this.eventRec = eventRec;
        }
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ease the pains of unit testing C# when you are the only person on the team unit testing I have ran into this a few times where you get put on a project and you want to do unit testing of some type, but the project isn't setup right to allow for this and you might not have buy-in from everyone.  The main issues tend to be code smells like issues with dependencies (especially the over use of statics) and seperation of concerns.  New code that you write can be setup easily, but anything that operates with other legacy code or even those not drinking the cool aide can become an issue.
Some things that I have found are that isolation frameworks like TypeMock can make this easier. What are some other tools/tricks/best practices that you have found that ease this sort of pain?

A: Wow, this describes a recent situation of mine exactly on a large, existing project.  No unit tests at all, and reluctance toward/skepticism of the idea.  At the time of writing, I've been able to work with another person who favored it to get it more accepted (though he and I are largely the only ones that generally write tests).  The code base was (still is) heavily laden with procedural static code, but it's getting better.  Here are some of the things that I did to improve the situation:

*

*Immediately interface all singletons, especially ones in heavy use.  Then, inject the interface into the new client classes you're writing to make them testable.

*Write wrappers for static classes that implement interfaces and inject those into new clients ala (1).

*Start gradually retrofitting your injected interfaces on former clients of static state/singletons and writing tests for them.

*Starting pulling functionality out of behemoth classes and testing the extracted, single-responsibility classes.

*Touched on earlier, but inject your dependencies!

*Write or factor to small methods and classes.

*Keep up the refactoring until you can finally kill the singletons/statics.

These are ways to make your code more testable (and, I would argue, better in general), but selling the process to others is a different matter.  I would offer the following advice for that:

*

*Write tests and show people how to do it  (the biggest barrier being a literal lack of knowledge of how to write tests).

*If you review people's code, write a unit test to expose a problem instead of telling them about it.  Show them the failing test and task them with making it pass.

*Make sure your test runs execute quickly - long running test suites will rot and annoy people.

*If the application is large, show people that the feedback loop is much faster for modify-test-refactor than it is for modify-build-run-maniulate-gui-observe-refactor.

*Unit test a feature that you write and keep objective statistics (defects reported per LOC) to compare to non-tested code.  This is a win with management.

*Along those same lines, run static analysis/metrics on the unit tested code which, in my experience, tends to score better than non-tested code.  Objective metrics are hard to argue with.

*Point out to people that guarding their code with unit tests makes it harder for someone to come along and mess with their code in defiance of their original intentions.  Sounds petty, but this is often a selling point for people when they realize it.

*Product implementation documents or writeups for consumption by stakeholders that emphasize code coverage or number of tests.  This creates the (accurate) impression that your code is demonstrably reliable and managers/analysts/PM types might start asking others where their coverage/test metrics are.

*Finally, and this is the one that I've found to be most eye opening or other developers, demonstrate the power of unit testing (specifically TDD for this one).  Pull off a coup like a major refactoring of your work in less than a day or having your code execute perfectly the first time you put it all together and run the application.  Developers who code it up and then spend a few days in the debugger programming by coincidence will be sobered by this in a way that they won't be all the unit test proselytizing in the world.

A: Try asking Michael Feathers article Testable Java  or Testable C# or C# TUFs and TUCs
The gist is ti avoid putting test unfriendly feature inside a test unfriendly construct.

A: Do not be hung up on the form your unit tests take, because there are many non-standard ways of doing this. Heck, you can write a stand-alone app which massages the database and looks for inconsistencies (in case some key constraints are too slow). You can test things from within a main method without formal unit test libraries. You can put together a quick Python script.
What you want to do is look for low-hanging fruits - e.g. things that are easy to test, likely to contain bugs, and are important.
When you succeed, advertise the success. Once you can demonstrate that your scripts and stuff can catch many bad bugs quickly, then take it to the next level.
Ask for permission to re-factor some code. Remember, critics will still be skeptical and will want to see tangible results, so you need to keep finding bugs with it. If you have to, make it find bugs that you actually discovered manually. Do not over-engineer stuff just because you like cleaner code. Multiply your hourly salary by the number of hours you spent on this - now you need to justify this investment. That is how many others see it.
Also, try to generate a lot of buzz slowly, so that people will start thinking that these ideas are actually theirs and not yours.

A: I don't want to sound too pessimistic here, but if on the same project you're the only one of quite a few who is unit testing, you might as well not do it at all. Compromise on integration tests, even if they're less accurate and slower.
The reason is that you're going to find yourself with a code base that's only partially-tested, inconsistent and hard to follow. And that's much worse in my book than a project without unit tests. Again, remember that integration tests are still possible.
The better alternative would be to persuade them that unit-testing will make their life easier and help them create a better product.
If you still choose (for some odd reason) to unit-test, what I do with legacy code goes pretty much like this:

*

*I start developing my classes

*When I need a legacy service, I create an interface for it, and then create an adapter that implements that interface and delegates all work to the actual legacy service.

That way I can work with legacy services and mock them in my classes' tests, without changing any legacy code.
And if you need to fix stuff in legacy code, slowly turn it to testable code - starting from integration tests and slowly and carefully turning them into unit-tests (only of the part you're fixing). Do that and you'll slowly have more and more parts of the code base that are testable (and tested).


text:
Q: VBA cross-worksheet color coded matching within cells that have a value I have been working on an excel tool for almost a week now and as I have almost made it to the end I found myself facing an issue I currently am not able to resolve.
On one sheet in my workbook I have something like this:

Now I want to color code this (fill out the cells with colors) using sheet2 to match it. So you get an idea, here's sheet2:

So the rows in sheet1 will get color coded by checking the respective A column on sheet2. For example: if the cell A2 says ABC I want the macro to fill out every cell in row 2 which has a value with the color yellow (as you can see in F1:G3 in sheet2, ABC means yellow color).
So in the end it should look something like this:

I have tried to write some code to do it unfortunately it didn't work. Nevertheless, you can take a look at it maybe it helps you help me.
Sub colormatching()

Dim wsSource As Worksheet
Dim wsTarget As Worksheet
Dim aCol As Long
Dim MaxRowList As Long, destiny_row As Long, x As Long

Set wsSource = ThisWorkbook.Worksheets("Sheet1")
Set wsTarget = ThisWorkbook.Worksheets("Sheet2")

aCol = 1
MaxRowList = wsSource.Cells(Rows.Count, aCol).End(xlUp).Row

destiny_row = 1
For x = 2 To MaxRowList
    If InStr(1, wsTarget.Cells(x, 1), "ABC") > 0 Then
        wsSource.Range("$A$" & x).Select
        With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 65535
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
destiny_row = destiny_row + 1
    End If
Next
End Sub

I would be really thankful for help on this one! Thanks in advance.

A: you could try this:
Sub main()
    Dim cell As Range

    With ThisWorkbook.Worksheets("Sheet1")
        .UsedRange.Interior.ColorIndex = xlNone '<--| clear preceeding cells coloring
        For Each cell In Intersect(.Columns(1), .UsedRange.SpecialCells(xlCellTypeConstants).EntireRow)
            cell.EntireRow.SpecialCells(xlCellTypeConstants).Interior.ColorIndex = GetColorIndex(cell.row)
        Next
    End With
End Sub

Function GetColorIndex(rowIndex As Long) As Variant
    With ThisWorkbook.Worksheets("Sheet2")
        GetColorIndex = .Range("F1:F3").Find(what:=.Cells(rowIndex, 1), LookIn:=xlValues, lookat:=xlWhole).Offset(, 1).Interior.ColorIndex
    End With
End Function


text:
Q: Relation between *sigma algebra* and *sigma models* Is there connection between sigma models in physics and sigma algebra in the probability theory?
Background: I have never had to study the former, but I am somewhat familiar with the sigma-algebra in the context of point processes.

A: There is no connection at all, apart from the name.
The "sigma" in "sigma models" comes from the name given to a field in a simplified model, introduced by Gell-Mann and Levy,  that describes how chiral symmetry breaking gives mass to the proton and neutron and at the same time makes the pion almost massless.  It then, by some accident of history, became attached as a name to any field theory in which one  integrates over the set of all maps from  spacetime to some  target manifold. Although the integration  involves assigning a  measure on the set of all such maps, there is probably no rigorous way to define a sigma algebra for  this measure.


text:
Q: An error using a python wrapper for lemmatization I'm trying to use a lemmatizing tool (MyStem) in my python code for the preparation of a text analysis in Russian. While implementing the a python wrapper for this software to my code, I get the following error (I use python 3):
from pymystem3 import Mystem
m = Mystem()
lemmas = m.lemmatize(allTexts)
print(''.join(lemmas))

cannot import name 'ifilter' from 'itertools' (unknown location)

Could someone help me solve this? I am very new to python.


text:
Q: POST from Form to external API I'm quite noob into asp.net
I'm building a simple solution in VS2019, using asp.net MVC, which is supposed to send a User data to another API which will be responsible for saving into database.
So far, both APIs are REST and I'm not using core
Basically, it is a form with a submit that will POST to the external project, pretty simple.
I'm following some tutorials and stuff but there are so many different ways that got me confused, so I decided to ask here
Here's what I have so far
[HttpPost]
public async ActionResult Index(User user)
{

    HttpClient client = new HttpClient();

    client.BaseAddress = new Uri("https://pathtoAPI.com/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json"));

    User newuser = new User()
    {
        email = user.email,
        nome = user.nome,
        cpf = user.cpf,
        cnpj = user.cnpj,
        userName = user.userName,
        senha = user.senha,
        telefone = user.telefone
    };

    var jsonContent = JsonConvert.SerializeObject(newuser);
    var contentString = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    contentString.Headers.ContentType = new
    MediaTypeHeaderValue("application/json");
    //contentString.Headers.Add("Session-Token", session_token);

    HttpResponseMessage response = await client.PostAsync("register", contentString);
    return Content($"{response}");
}

I want to receive the "OK" message from the other API and just print it on my screen, I'm using the cshtml file to handle the front and the form as well.
The return though seems to be wrong, it's expecting either 'null, task, task, or something like.
Can someone please help me with this code?
Thanks

A: You need to return the content of the response, not the response object itself.
HttpResponseMessage response = await client.PostAsync("register", contentString);
string responseBody = await response.Content.ReadAsStringAsync();
return Content(responseBody);


text:
Q: Running a Python Script in the background from Startup I want to monitor a file in a specific location and check it for updates, which upon being updated launches certain actions via a python script.
Ideally, this program would always be running in the background and would automatically start with the computer so that the user does not have to mess with starting/stopping it.
I have researched the topic some and have found daemon and similar tools, but I do not understand how they work and they look far more complex then what I need. Also, many of the examples that I am looking at use Ubuntu OS and I will be using Windows.
Are there any python modules that exist to do this already or any direction you can point me to get started? I apologize if this question has been answered already, however I have not found it in my research.
I plan on editing this post to include code that performs this action, however I currently do not know where to start.

A: On Windows you could create a batch script and schedule it using the Windows Task Scheduler to run as a process on boot.
You can trigger the Python script to run inside the batch file,
python file.py

Alternatively, if you're using something like Anaconda as your environment manager; you could write a batch file to activate Anaconda using the activate.bat contained in the Scripts folder of your Anaconda installation path and then follow the usual calling steps.


text:
Q: How to trigger next button in DataTables after it reaches to 10 rows How to automatically click next button in Data-tables after it reaches to 10 rows. The way I add rows is dynamic so when I reaches to my 11 rows i want to automate the next button so from the first page it will move to 2nd page.
I've tried to use the code below from Data-tables
But base on documentation:
If multiple data points match the requested data, the paging will be shifted to show the first instance. If there are no matches, the paging will not change.
jQuery.fn.dataTable.Api.register( 'page.jumpToData()', function ( data, column ) {
    var pos = this.column(column, {order:'current'}).data().indexOf( data );

    if ( pos >= 0 ) {
        var page = Math.floor( pos / this.page.info().length );
        this.page( page ).draw( false );
    }

    return this;
} );

So i want something that will shift the page to the next page after it reaches 11 rows. Please help. Thanks in advance.
Here is my code:
$('.btn').on( 'click', function () {
      var dTable1 = $('#list-table').DataTable();

       dTable1.row.add({
                "brand": $('#brand').val(),
                "category": $('#category').val(),
                "code": $('#code').val(),
                "description":  $('#description').val(),
                "unit": $('#unit').val(),
                "qty": $('#input-qty').val(),
                "unit_price":   $('#unit_price').val(),
                "action": ''
            }).draw();

        $('#list-table').dataTable().fnPageChange('last'); //This is not working

});

Here is the fiddle :  https://jsfiddle.net/deathnote332/9cn6ctas/

A: Reference:- Datatables -jump to last page by-default

var dTable1 = $('#search-table').DataTable();
$('.btn').on('click',function(){
dTable1.row.add([
    "id",
    "brand",
    "category",
    "code",
    "description",
    "unit",
    "qty",
    "unit_price"
]).draw();
$('#search-table').dataTable().fnPageChange('last');
});

<link rel = "stylesheet" href= "https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">

        Id
        Brand
        Category
        Code
        Description
        Unit
        Qty
        Unit Price

<button type="submit" class="btn btn-primary">add</button>


text:
Q: Removing added custom cell renderer I have created a custom cell renderer to fill a cell by a particular color.
public class ColorInCellRenderer extends DefaultTableCellRenderer

    {
        private final Map<Point, Color> cellColors = new HashMap<Point, Color>();
        public void setCellColor(int row, int column, Color color)
        {
            if (color == null)
            {
                cellColors.remove(new Point(row, column));
            }
            else
            {
                cellColors.put(new Point(row, column), color);
            }
        }

        private Color getCellColor(int row, int column)
        {
            Color color = cellColors.get(new Point(row, column));
            return color;
        }

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            Color color = getCellColor(row, column);
            c.setBackground(color);
            return c;
        }
    }

i used it in adding a row into jTable as follows.
private void addTableRow(String type, String name, String rank, String notes, String location, Color color)
    {
        tableModel.addRow(new Object[]
        {
            type,
            name,
            rank,
            notes,
            location
        });
        colorInCellRenderer.setCellColor(tableModel.getRowCount() - 1, INDEX_OF_THE_COLOR_COLUMN, color);
        JTable.repaint();
    }

It works properly and fill the cell correctly. But when I remove the row it does not remove the filled color cell. Instead of it the color column replaces with the color cell in the next row. I tried by repainting the jTable after removing a row. But it does not work.

A:
But when I remove the row it does not remove the filled color cell.

Because you store the cells to be painted in your "cellColors" Map.
When you remove a row from the table you also need to remove the Point from the Map.
You can add a TableModelListener to the TableModel. You will be notified when a row is removed and then you can also remove the Point from the Map.


text:
Q: Editing html/css within a bash script while true; do echo -e "HTTP/1.1 200 OK\n\n $(date)" | nc -l -p 8080; done

Been given this one liner to start a simple webserver on a raspberry pi for university. When connected it shows the day and date. I've been asked to simply change it so it displays with the text color as blue rather than black
I know html and css well, just not sure where to put it within this code or if i need to write it different

A: Specify a content-type to serve as text/html then you can use HTML tags with an inline style.
while true ; do echo -e "HTTP/1.1 200 OK\rContent-type: text/html\n\n $(date)" | nc -l -p 8080; done


text:
Q: Script Programming: Using arguments to develop functions in separate files When programming in a scripting language (Python, Perl, Ruby or R), I try to write functions and keep them in separate files to keep my code modular.
For debugging, I often put the arguments of the function inside the function body and un-comment them as soon as I'm done.
Moreover, I often place a call to the function right after its definition, which I also uncomment when I'm done testing.
So in the end, my file looks like this
def add(a, b):
    # a = 1
    # b = 2
    c = a + b
    return c

# add(1, 2)

Is there a more elegant way to achieve this?
Moreover, I think common practice would be to remove these comments when shipping the code to others. Is there a way to achieve this in a JavaDoc like manner, while keeping "real" comments (i.e. not uncommented code)?
I should mention, that I often write wrapper functions around calls to plot functions in Matplotlib or R (ggplot, etc) and since in these cases the output is a graph, it doesn't fit so well into test-driven development frameworks.

A: The proper way would be to write some unit tests.
If you want to have your tests very close to a source code, you should check out doctest module, it allows you to run tests placed directly in doc comments.
Neat thingy.
Edit:
In yours example it would look like this:
def add(a, b):
    """ Returns sum of a and b

    >>> add(1, 2)
    3

    """
    c = a + b
    return c

And run the tests like this:
python -m doctest -v yourFile.py


text:
Q: How do I make my subs() not change inputdata in Vba excel When I call a sub and pass a variable, after the sub ends the passed variable is changed. How do I make it not do that?
So in the example the debug.print should be 3 not 8
sub main()
  i = 3
  SomeSub i
  debug.print i
end sub

sub SomeSub(j)
  j=j+5
end sub

A: Just use the ByVal keyword to pass on the value
Sub SomeSub(ByVal j As Long)
  j = j + 5
End Sub

Further reading

Using ByRef and ByVal
When we pass a simple variable to a procedure we can pass using ByRef
or ByVal.
ByRef means we are passing the address of the variable. If the
variable changes in the procedure the original will also be changed.
ByVal means we are creating a copy of the variable. If the variable
changes in the procedure the original will not be changed.


text:
Q: Why is this code for single linked list not working? Being a beginner I tried this single linked list program to accept and display first to last elements.I can't figure out what is wrong.After you run it the program stops responding after taking in the first element. I am not very familiar with the language and am new to pointer concept. This was an assignment work.
#include <iostream>
using namespace std;

struct node
{
    int data;
    node* next;
};

class alpha
{
  public:
    node* head;
    node* last;
    node* n;
    node* p;
    int x;
    char ch;

    void input()
    {
        cout << "Enter the element..";
        cin >> x;
        insert(x);
        cout << "Do you want to add more?";
        cin >> ch;

        if (ch == 'y')
        {
            input();
        }
        else
        {
            display();
        }
    }
    void insert(int x1)
    {
        n = new node;
        n->data = x1;

        if (head == NULL)
        {
            head = n;
            last = n;
        }
        else
        {
            n->next = NULL;
            last->next = n;
            last = n;
        }
    }
    void display()
    {
        p = head;

        while (p != NULL)
        {
            cout << p->data;
            p = p->next;
        }
    }
};

int main()
{
    alpha o;
    o.input();
    return 0;
}

A: the big mistake already pointed out is the absence of an initialization by a constructor. Also I suggest to move some data member to private, and make some of them local.
#include <iostream>
using namespace std;

struct node
{
    int data;
    node* next;
};

class alpha
{
private:
    node* head;
    node* last;

public:
    alpha() {
        head = NULL;
        last = NULL;
    }

    void input()
    {
        int x;
        char ch;

        cout << "Enter the element..";
        cin >> x;
        insert(x);
        cout << "Do you want to add more?";
        cin >> ch;

        if (ch == 'y')
        {
            input();
        }
        else
        {
            display();
        }
    }
    void insert(int x1)
    {
        node* n = new node;
        n->data = x1;

        if (head == NULL)
        {
            head = n;
            last = n;
        }
        else
        {
            n->next = NULL;
            last->next = n;
            last = n;
        }
    }
    void display()
    {
        node* p = head;

        while (p != NULL)
        {
            cout << p->data;
            p = p->next;
        }
    }
};

int main()
{
    alpha o;
    o.input();
    return 0;
}

As someone suggested, please implement a destructor ~alpha(), in order to avoid leaks of node instances.


text:
Q: Hermiticity of momentum space Hamiltonian I have managed to confuse myself with the notion of hermiticity in momentum space.
In most quantum mechanical applications we assume:
$$
H(R) = H^{\dagger}(R)
$$
For $R$ some position vector. Now expanding this $H(R)$ in momentum space (on some lattice) gives:
$$
H(R) = \sum_{k}e^{ikR}H(k)
$$
So that the hermiticity condition now translates to:
$$
H^{\dagger}(R) = \sum_k e^{-ikR}H^{\dagger}(k)=\sum_k e^{ikR}H^{\dagger}(-k) = \sum_k e^{ikR} H(k)=H(R)
$$
So that comparing gives directly that $H^{\dagger}(-k) = H(k)$.
Thus, for example, if we have a $2\times 2$ Hamiltonian $H(k)=\vec{d}(k)\cdot \sigma$ then:
\begin{equation}
\vec{d}(k)  = \vec{d}^*(-k)
\end{equation}
But isn't hermiticity a property of the vector space we operate in? Is not $H(k)$ an equally valid description of the physics, so that we should be able to impose hermiticity on $H(k)$, which would result in:
\begin{equation}
\vec{d}(k) = \vec{d}^*(k)
\end{equation}
Is there anything special about position space here? Which of the last two equations holds?

A: I think the confusion arises from using various "Hamiltonians": $H(R)$, $H(k)$.
These are not the Hamiltonian of the system $\mathcal{H}$, which for free particles on a lattice can be written
\begin{equation} \mathcal{H} = \sum_{R,R'} c_R^\dagger H(R-R') c_{R'} \tag{1}\end{equation}
where we just assumed homogeneity on the lattice.
Notice that imposing $\mathcal{H}^\dagger = \mathcal{H}$ leads to
\begin{equation} \tag{2} (H(R))^* = H(-R) \end{equation}
We can express Eq. (1) also in Fourier space as\begin{equation} \mathcal{H} = \sum_{K} c_k^\dagger H(k) c_{k} \tag{3} \end{equation}
where $H(k)$ is often called Block Hamiltonian.
Notice that from Eq. (2) it follows
$$ (H(k))^* = H(k) \tag{4} $$
Therefore the answer is: your last equation $d(k) = (d(k))^*$ is correct. Notice that your second last equation $d(k) = (d(-k))^*$ is also correct, if there is inversion symmetry. Finally, of course one can use either $H(R)$ or $H(k)$ to express the Hamiltonian $\mathcal{H}$. Only $\mathcal{H}$ needs to be Hermitian.


text:
Q: Figuring out if an app supports deep links I'd like to easily figure out, for any app installed on my phone, if that app supports deep links (i.e. links that open the app instead of a website).
Is there a way of doing this in Android and/or iOS without having to randomly click links?

A: If you know the apps custom scheme then you can use:
let url = URL(string: "fb://")!
let isInstalled = UIApplication.shared.canOpenURL(url)

Here is a blog post for further reading.

A: This way works for iOS only and tells you if the app has an url scheme to open it
What you have to do is get the app on itunes on your computer.. unzip it and look inside for the Info.plist file.
This file is an XML.. look for 'URL types', somewhere inside this is where 'URL Schemes' are defined.

The sad part is that you need to do this for each app and that this
  may change in future versions of the same app.


text:
Q: Reading nodes with pos attribute from file in networkx I am new to Networkx. I have a file containing position of nodes in following format
0 : 23.23 12.23
where 0 is a node, 23.23 and 12.23 are X and Y co-ordinates respectively.
Does anyone know how to read nodes with pos attribute, using function like read_edgelist(...) or similar work around?
Thanks

A: With read_edgelist, you are assuming that you have an edge list already present. However, what you've provided is a node + properties.
Since you start off with a file that has the file format (stated in your comments), the first challenge is getting it into a format that would be easily parseable. I suggested the CSV file format for that reason. To do this with your file, I would fire up the Terminal (Linux & Mac), cd into the directory with your files, and run the following two commands:
sed -n 's/ : /,/gpw nodes_replaced1.txt' nodes.txt

This reads nodes.txt (or your file), replaces all occurrences of the : (including spaces) with ,, and saves it as nodes_replaced1.txt. You can change the file names at will.
Once that is done, run the following command in terminal
sed -n 's/ /,/gwp nodes.csv' nodes_replaced1.txt

This will do a similar thing, except read in nodes_replaced1.txt, replace [spaces] with ,, and write it as a CSV file.
Once you have a CSV file, I would suggest using Pandas to open up the CSV file and do the following to add nodes into your graph:
In [1]: import pandas as pd

In [2]: import networkx as nx

In [5]: nodes = pd.read_csv('nodes.csv', header=None)

In [6]: nodes
Out[6]:
   0      1      2
0  0  52.88  52.53
1  1  56.63  49.53
2  2  38.60  69.81
3  3  43.00   2.88

In [7]: G = nx.Graph()

In [8]: G
Out[8]: <networkx.classes.graph.Graph at 0x105e94cd0>

In [9]: for row in nodes.iterrows():
   ...:     G.add_node(row[1][0], x=row[1][1], y=row[1][2])
   ...:

In [10]: G.nodes(data=True)
Out[10]:
[(0.0, {'x': 52.880000000000003, 'y': 52.530000000000001}),
 (1.0, {'x': 56.630000000000003, 'y': 49.530000000000001}),
 (2.0, {'x': 38.600000000000001, 'y': 69.810000000000002}),
 (3.0, {'x': 43.0, 'y': 2.8799999999999999})]

You will note that when I call G.nodes() only, there is no x & y position data. However, when I call G.nodes(data=True), the x and y position data is incorporated.
For more information on how to create a graph, and how to put in 'attributes' associated with any node, edge, or graph, see this page: http://networkx.github.io/documentation/latest/tutorial/tutorial.html#nodes
Finally, if @Aric ever shows up to answer this question, please correct me if I'm wrong!


text:
Q: i want to translate string in other language using angular translate, but how to use in javascript which has the notification In below code i want to translate notification message in to another laguage, so how to translate, which dependency will require?
{
    window.history.back();
    $timeout(function(){
    Notification.info('Doubles Team not found. The Id is either wrong or the           Doubles Team has been deleted by the Admin.');//$state.go('error');
}

A: I think you want to use angular-translate module.
Once you include it, you can store in a separate json file all your translation, for instance, you will have the file en.json containing:
{
   NO_DOUBLE_TEAM: "Doubles Team not found. The Id is either wrong or the Doubles Team has been deleted by the Admin;
}

And then in your controller, you add a dependency to the $filter service and you can do:
var infoUser = $filter('translate')('NO_DOUBLE_TEAM').

Depending on the language selected, it will display the good value.
There are plenty of tutorials for this module:
http://ng-newsletter.com/posts/angular-translate.html
https://angularjs.de/artikel/angularjs-i18n-ng-translate

A: First of all you need angular-translate module, include it in your app, afterwards you need to create json files for your languages.
{
NO_DOUBLE_TEAM: "Doubles Team not found. The Id is either wrong or the Doubles Team has been deleted by the Admin;
}

Then simply use it like this.
{
    window.history.back();
    $timeout(function(){
    Notification.info($translate.instant('NO_DOUBLE_TEAM'));//$state.go('error');
}


text:
Q: Confused about this theorem in linear algebra this theorem is from lecture notes

$\{X_1,X_2,X_3\}$ are linearly dependent iff $X_3$ span $\{X_1,X_2\}$.

I think it is wrong because we can show $X_1$ and $X_2$ is also can be expressed as a linear combination of the other vectors
Am I right? Or is there something wrong with my conclusion?

A: I don't quite understand your reasoning, but the theorem you mention is wrong. Take for example $\mathbb R^2$, then $\{(1, 0), (2,0), (0, 1)\}$ are linearly dependent, but $(0,1)\notin span\{(1, 0), (2, 0)\}=span\{(1, 0)\}$.


text:
Q: How to kill the WebDriver instance keeping the Web Browser open I am developing an automatic web unit test with Selenium WebDriver.
I know that I can use the driver.close() and driver.quit() method to close the browser and to release the chromedriver from the memory after the test but it's not good for me because I want that the Chrome browser will stay open so I will be able to continue to work on the site from the place the automatic test finished.
The problem is, that when I am closing the chrome browser manually, the chromedriver.exe staying in the memory of the machine and not terminated so in the next test i will have another chromedriver.exe in the memory and so on.
Will be great if i can tell to the chromedriver.exe to terminate itself when the last chrome insistence will be closed. As i explained, i can not do it grammatically because the test method already ended.
I know that i can loop over all the process each time i am executing the test and kill any active webdriver process but i don't like that way.
Just to make things clear,  I want automation until a specific point and then to continue manually, after the automation part completed. On that point, i can not access the instance of the driver to use driver.quit() or driver.close() method. I am using Microsoft.NET TestMethod.

A: A couple of things:

*

*driver.close(): It is used to close the current page or the browser (if it is the only page/tab) which is having the focus.

*driver.quit() : It is used to call the /shutdown endpoint and subsequently the WebDriver and WebBrowser instances are destroyed gracefully closing all the pages/tabs/windows.

*You can find a detailed discussion in about the difference between driver.close() and driver.quit() in this discussion

*Even after invoking driver.quit() if the WebDriver / Web Browser still stays in memory you can kill them with brute force following the discussion discussion

*Once your Automated Tests are completed to terminate only the ChromeDriver binary and keep the Chrome Browser stay open you can use use Python raise Keyword and you can use the following (Python based) solution:

*Code Block:
from selenium import webdriver
import psutil

driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('https://www.google.com/')
try:
    raise ValueError('Test Execution completed ... Killing the ChromeDriver instance only')
except Exception as error:
    print('Caught this error: ' + repr(error))
    PROCNAME = "chromedriver.exe" # or geckodriver.exe or IEDriverServer.exe
    for proc in psutil.process_iter():
        # check whether the process name matches
        if proc.name() == PROCNAME:
            proc.kill()
print("Only ChromeDriver instance was killed and Chrome Browser instance left open")

*Console Output:
Caught this error: ValueError('Test Execution completed ... Killing the ChromeDriver instance only',)
Only ChromeDriver instance was killed and Chrome Browser instance left open

*Here you can find a detailed discussion on Manually raising (throwing) an exception in Python


text:
Q: Minimize trace of $A$ given that $A−N$ is positive semi-definite and $A$ is diagonal \begin{array}{ll} \text{minimize} & \mbox{tr} (\mathrm A)\\ \text{subject to} & \mathrm A - \mathrm N \succeq \mathrm O_n\end{array} where $A$ and $N$ are pd matrices, and $A$ is diagonal.
There is a related post: Minimize trace of $A$ given that $A-N$ is positive semi-definite. . However, in that case $A$ is not diagonal thus, $tr(A)=tr(N)$ is possible, while in current case not.
For $A\in \mathbb{R}^{2\times2}$, I believe $\min tr(A)=\sum n_{ij}$, however for $A\in \mathbb{R}^{3\times3}$ we have inequality $\min tr(A)\leq\sum n_{ij}$. Can you please help with analytical approach so solve it


text:
Q: Center the map on a current location - Titanium I am running my app on simulator and I have 2 issues: 1) default "user current location" is placed on San Francisco. Can I change that without using "region:" and set the delta for long lat? 2)How can I center the map on the current location(I want the current location in the center of the map) Thanks in advance.

A: You can't use the current location in simulator, that will only work on a device.


text:
Q: a quality that must have vs a quality every person must have Are both sentences correct? I suppose that the first one is better (more common form). Is it true?

Politeness is a quality that must have.
Politeness is a quality every person must have.

A: I would say your first sentence is totally incorrect. This is because it is wanting in detail.

Politeness is a quality that must have.

To see why this doesn't work we could temporarily dispense with the part is a quality: it doesn't affect the syntax, after all.
We then are left with

Politeness must have

If it is still unclear to see why this abbreviated version doesn't work, you could further abbreviate the version and say

Politeness has  (Imagine that Politeness "got" what it must have had.)

This version is ungrammatical because we're left with a subject and an incomplete predicate.
A helping verb like has above must take a main verb to complete the predicate.
By the same token, your second sentence is a perfectly grammatical sentence because it has a complete predicate.
To see why, you could turn around the word order and say instead

Every person must have (the quality of) politeness.


text:
Q: How to write into a file (.txt or .html) in javascript does anyone know how to write into a file (.txt or .html) in javscript.
I got multiple answers in google but none of them are working.
Currently I am using this line :
var FileOpener = new ActiveXObject("Scripting.FileSystemObject");;
var FilePointer = FileOpener.OpenTextFile("C:\Users\sidkr\Desktop\sid.txt", 8, true);
FilePointer.WriteLine("I m a good boy");
FilePointer.Close();

But getting following error
ActiveXObject is not defined
I am using google chrome for development

A: From the microsoft docs

This object is a Microsoft extension and is supported in Internet
  Explorer only, not in Windows 8.x Store apps.

https://learn.microsoft.com/en-us/scripting/javascript/reference/activexobject-object-javascript
Take a look at this question here
Is it possible to write data to file using only JavaScript?


text:
Q: Enabling equation editor in kingsoft wps office suite All solutions found on the net said to download a certain wps_symbol_fonts.zip file (available on the net) then to extract its contents (mtextra.ttf, symbol.ttf, WEBDINGS.TTF, wingding.ttf, WINGDNG2.ttf, WINGDNG3.ttf) to a fonts/ folder (I used /usr/share/fonts/wps_symbol_fonts/) and finally to reload fonts with:
fc-cache -fv

I tried this on two different Ubuntu versions, but never succeeded in getting the equation editor menu enabled!

A: Equation is not supported in WPS office currently so there is no way to enable this function.

A: I found the solution right HERE and it worked perfectly for me with the latest WPS Office on Ubuntu 17.10. I used the "Manual installation" method.

For this tutorial we will use the /tmp directory to temporarily save
  the files.
Change directories to the /tmp directory.
cd /tmp

Clone the Git repository.
git clone https://github.com/iamdh4/ttf-wps-fonts.git

Create a sub directory in your system's fonts directory. This is
  usually /usr/share/fonts, otherwise consult your distribution's
  documentation.
sudo mkdir /usr/share/fonts/wps-fonts

Move fonts to the new directory.
sudo mv ttf-wps-fonts/* /usr/share/fonts/wps-fonts

Fix the file permissions.
sudo chmod 644 /usr/share/fonts/wps-fonts/*

Rebuild the font cache.
sudo fc-cache -vfs

Clean up the /tmp directory.
rm -rf /tmp/ttf-wps-fonts

A: WPS Office does not have the tool to Equation Editor as it does in windows
On Windows Equation Editor Software executable .exe are inside this path:
C:\Users\yourusername\AppData\Local\Kingsoft\WPS Office\11.2.0.9906\office6\mui\default\resource\ksee

Note: You need enable view hidden files and folders in windows to find that path.
there is the next folder and files:
Fonts
ee3.dsc
EqnEdit.exe
Equation Editor.chm
Note: You can open the Windows help file on Linux with: xchm or kchmviewer
In the next picture on Linux I have that folder from WPS Office Windows Version with the executable:
EqnEdit.exe

Note: You can obtain that on Windows if you have installed WPS Office. Search in that path.
This software where made for:
http://www.dessci.com
Note: I do not know if in the future they ask that company to make a version for Linux
You can execute this on Linux with wine but the formula generated is not possible to insert to WPS Writer and this tool not have any way to export in file the content code formula language to view the code. But there is a way to enter that on WPS Office Linux version with code:
Enter Fraction and Radical Number in WPS Office Writer enabling Equation Field Code
Acording to this tutorial: http://help.wps.com/articles/how-to-enter-fraction-and-radical-number-in-writer to enable Toggle Field Codes you need to use the shortcut:
Ctrl+F9
now the following appears:

then in the generated field enter (or paste but wihout format):
eq \f(3,4)
Next, click the right mouse button and choose "Toggle Field Codes" from context menu:

now see a fraction:

And in that web page said the next example:

to do that enter:
eq \r(3,2)
with right clic:

and edit:

and appear:
[
I go to enter this in the same place:
eq \f(3,4 ) eq \r(3,2)

and appear repeated "eq":

for this reason delete this second word:
eq \f(3,4 ) \r(3,2)

and now ok:

Now I do other example:
eq × = \f(13 × 7,201 ÷ 6 ) ÷ \r(4, 2 ÷ 3)

And Togle Field Codes:

To do that I insert × and ÷ symbols with that tool in WPS Office:

¿The rest of the codes?
I do not know the language in which these codes are written, I have tried to search the Web for a manual to be able to write the formulas in code but I cannot find anywhere. At the moment what I am going to do is write to the developers because there on that page it says that they can be written:

If you know the codes help us


text:
Q: How do you include images from your desktop withing the  tag in html?

The image does not appear when incorporate the image location within the
source. If I upload an image from the internet, and copy the image source, the
image will appear after executing the code.

A:

try this change the slash

A: If this is for a website you are developing on your computer, then put in in a folder called 'images' relative to the index.html file;

*

*FOLDER: myWebsite

*

*-SUB FOLDER - images

*-FILE - index.html

Then use this:

If this is for a website that is current accessable to the public, then i suuggest uploading the images you wish to use onto the server the website is located and follow the same directions as specified above. You do not want to allow people to access your local files system, bad news.

A: You can access local files ONLY if the whole webpage (the HTML file) is also accessed as a local file. If you uploaded the page to some server or access it via localhost, then it is not possible to access local file directly.
Also, you should use file:// at the beginning of path, however browsers will understand the path even without it:
src="file://C:\Users\Maxine\Pictures\loveson.jpg"


text:
Q: Retrieving data from array of array objects In my application i am trying to return javascript object of employee who works in all projects. My array of data is like:
   var data = [
{
    projectName: "project1", projectId: 1,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Jane Smith", employeeId: 2}
    ]
},

{
    projectName: "project2", projectId: 2,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Mary Jones", employeeId: 3},
        {fullName: "Bill Evans", employeeId: 4}
    ]
}

];
I need to search for employeeid 1 and return both projects. How do i search it.

A: I hope this is the code you're looking for:
for(i=0;i<data.length;i++)
 {
    emp=data[i].employees;
    for(j=0;j<emp.length;j++)
    {
        if(emp[j].employeeId==1)
          console.log('Project of' + emp[j].fullName + 'is = ' + data[i].projectName)
    }
}

A: try to use Array.filter and Array.findIndex.
UPD:
since Array.findIndex is a new feature in ES6, maybe not supported by some browsers, but it has a polyfill for those unsupported browsers to use, see documentation here).
function doFilter(arr) {
  return arr.filter(function(item) {
    return item.employees.findIndex(function(employee) {
      return employee.employeeId === 1;
    }) > -1;
 });
}

this code snippet will return the target project array which contains the employee with an ID of 1.

var data = [{
    projectName: "project1",
    projectId: 1,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Jane Smith",
        employeeId: 2
      }
    ]
  },
  {
    projectName: "project2",
    projectId: 2,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Mary Jones",
        employeeId: 3
      },
      {
        fullName: "Bill Evans",
        employeeId: 4
      }
    ]
  },
  {
    projectName: "project3",
    projectId: 3,
    employees: [{
      fullName: "Jane Smith",
      employeeId: 2
    }]
  }
];

function doFilter(arr) {
  return arr.filter(function(item) {
    return item.employees.findIndex(function(employee) {
      return employee.employeeId === 1;
    }) > -1;
  });
}
console.log(doFilter(data));

A: Hope this works Fine

var data = [{
    projectName: "project1",
    projectId: 1,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Jane Smith",
        employeeId: 5
      }
    ]
  },

  {
    projectName: "project2",
    projectId: 2,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Mary Jones",
        employeeId: 3
      },
      {
        fullName: "Bill Evans",
        employeeId: 4
      }
    ]
  }
];

function getEmployeeById(id) {
  var e = $.map(data, function(a) {
    var r = $.grep(a.employees, function(b) {
      return b.employeeId == id;
    });
    if (r.length) {
      console.log(a.projectName, r[0].fullName)
    }
  });
}
getEmployeeById(1)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: It can be as simple as this. Just iterate and compare.
https://jsfiddle.net/
for( i=0;i<data.length;i++)
{
    for( j=0;j<data[i].employees.length;j++)
  {
     if (data[i].employees[j].employeeId == 1)
      console.log(data[i].projectId);
  }
}


text:
Q: Sever level MongoDB authentication I am trying to put authentication on mongodb, which I already did, but the thing is that the authentication is at Database level not at Server level. e.g. A person can connect to my mongo server without authentication, he/she can do a random guess about the DB name and use DBName will show the Databse but not the collection and documents inside it. My prime agenda is to restrict access to my server without proper credentials altogetger. I tried official mongo document but it is quite vague. Thanks in advance for your support.

A: I figured out that authentication cannot be applied at server level because mongodb does not have web server as we have in MSSQL or MySQL. So, we can only apply auth at DB level and restrict visibility of our server by VNet and by configuring firewall.


text:
Q: Create a New Plone addon mrbob error I want to start developing of my first test addon. I have a problem on the basis of mr.bob. Any described ways have leaded to one result. my documentation
log image

Check

mrbob --help

do the same answer.
After I came to the conclusion the problem is in pre-installed Python2.7 with no worked mr.bobe and bobtemplates. I do not know how to make a working set.

A: Looking at your traceback I guess mr.bob is not fully supporting Windows.
The readline module on Windows is not available. There's some alternatives like pyreadline.
Seems it's a know issue: see https://github.com/domenkozar/mr.bob/issues/49

A: Don't know about mr.bob, but you could alternatively try adi.devgen (disclaimer: one of my add-ons). Install it with pip:
pip install adi.devgen

And then do:
devgen addOn yournamespace.youraddonname


text:
Q: How do I give Ubuntu more space (when installed inside Windows 7 (via wubi))? I had installed Ubuntu inside Windows XP but then I formatted XP and installed Windows 7.
EDIT1: I used Wubi for the same.
I want to know which one of the two will solve my problem? creating a virtual disk or resizing root? Also is resizing root possible as the 4GB ext4 partition is already in a NTFS format Hard Drive partition.
At the time of installation I had allocated only 4GB of space to Ubuntu. I want to increase that size as I keep getting a low disk space notification.
I have surfed through a lot of similar questions but this is not a duplicate.
Because I want to know a little about the file systems. In order to solve my problem,do I have to increase the size of root.disk? Or will it be solved by creating a virtual disk?
Also I want to know the difference between creating a virtual disk and just increasing disk space of root.I'm new to Ubuntu so I don't know how the file systems function.
EDIT2:I have created a virtual disk of 10gb ,but I'm still getting the same notification.Is there anyway to install all further applications on the virtual disk I created?

A: Additional virtual disks are only useful if you're able to split the filesystem (eg putting /home/ on it) so aren't much use if you've installed a ton of stuff. You can split things like /usr/bin but it can get really messy, really fast.
Have you not seen a link to this post on your travels? You'll need a LiveCD or LiveUSB to action it, but it's very simple once you're at that point. Here are the main points:

*

*mount your windows partition (where the Wubi install sits)

*fsck the Wubi filesystem to make sure it's okay. If you don't do this and it has corruption in it before resizing, bad things can happen.

*resize2fs the Wubi filesystem to increase its size.

*Have a snack, chill out, high-five yourself... You've just increased the partition size.

Those aren't the full commands, I'll leave those in that thread because it seems to be well maintained.
Failing that, installing Ubuntu only takes a few minutes. If you like it, perhaps you should consider a proper install (disk performance is better too).

A: It's hard to tell here whether you are referring to virtualization or simply the Wubi installer.
Assuming the former, first increase the size of the virtual disk, since that will allow us to expand the actual partition.
Then mount the LiveCD in the Virtual Machine and run gparted. Using that tool, resize the partition to take up the remaining space you created when you expanded the disk. Now reboot and unmount the CD.

A: You actually don't have to boot from a livecd to do this:
sudo dd if=/dev/zero bs=1MiB of=/host/ubuntu/disks/root.disk conv=notrunc oflag=append count=2048
sudo losetup -c /dev/loop0
sudo resize2fs /dev/loop0

This will add 2 GiB to the filesystem.  Adjust the count=2048 for different sizes.

A: Of course it is too late but helpful for new comer
Install 14.04 Ubuntu via WUBI in windows 8. I have done these steps:
Download the iso from Ubuntu site.
mount it in a virtual drive in windows and copy all files in a drives folder.
From the folder click the exe to run WUBI setup. Which runs same as 10.x Ubuntu.
In 5 to 10 min it ask to restart, I have a issue of ro (read only) so convert it to rw(read and write) as show here Describe Here
Above part is for installing..
To extend the WUBI root.disk is a way.
I have found solution here
you need to download a zip from link this.
Extract it and just run the one line command and this will done all job
sudo bash wubi-resize.sh 10

Above commad will done following job:
Create a disk(Virtual) with desired (10GB) size in drive.
Copy all data from you running disk to newly created disk
and ask you to boot Windows and rename root.disk to OLDroot.disk and new.disk (New drive)
to root.disk and reboot again Ubuntu. Now check you system propery it will show your new size.
This works well for me.
Thanks


text:
Q: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.14/$injector/modulerr I am trying to inject an emoji app into my project.
I have added the emoji.min.js and referenced it like this
<script type="text/javascript" src="js/emoji.min.js"></script>

Now I am also injecting it into my project like this:
angular.module('ionicApp', ['ionic','ngSanitize','emojiApp'])

Immediately I inject the emojiApp,
I get the following error.

Uncaught Error: [$injector:modulerr]
  http://errors.angularjs.org/1.2.14/$injector/modulerr?p0=ionicApp&p1=Error%…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.14%2Fangular.min.js%3A29%3A115)

===================EDITTED=============
Completed injected file
angular.module('ionicApp', ['ionic','LocalStorageModule','ngImgCrop', 'btford.socket-io', 'angularMoment','ngCordova','ngResource','ngSanitize','emojiApp'])

Complete script used in the index file
<script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<!--    css scripting for fan page search-->
<!--<link href="http://code.ionicframework.com/1.0.0-beta.9/css/ionic.css" rel="stylesheet">-->
<!--cdn for isportline css fonts-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

<!--    for the ionic lightbox-->
<link rel="stylesheet" href="css/lightbox.css">
<!--increase the height and the width of the ionic lightbox-->

<!-- Ionic framework - replace the CDN links with local files and build -->

<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!--<link rel="stylesheet" href="css/autocomplete.css">-->

<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!--    <script src="http://code.ionicframework.com/0.9.27/js/ionic.bundle.min.js"></script>-->

<!--fan page search resource-->
<!--  <script src="http://code.angularjs.org/1.2.12/angular-resource.js"></script>-->
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
<!-- <script type="text/javascript" src="js/autocomplete.js"></script>-->
<script src="lib/angular-local-storage/dist/angular-local-storage.min.js"></script>
<script src="dist/ng-cordova.min.js"></script>
<script src="js/ng-crop.js"></script>
<script src="js/loader-image.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>

<script src="lib/moment/min/moment.min.js"></script>
<script src="lib/angular-moment/angular-moment.min.js"></script>

<script src="lib/sio-client/socket.io.js"></script>

<script src="http://192.168.19.12:3000/socket.io/socket.io.js"></script>

<script src="lib/angular-socket-io/socket.js"></script>

<script src="js/services/SocketService.js"></script>

<script src="js/controllers/HomeController.js"></script>
<script src="js/controllers/RoomController.js"></script>

<!-- emoticon scripting -->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular-sanitize.min.js"></script>
<script type="text/javascript" src="js/config.js"></script>
<script type="text/javascript" src="js/emoji.min.js"></script>
<link type="text/stylesheet" rel="stylesheet" href="css/emoji.min.css" />

Please what am I getting wrong. Kindly Assist!

A: please try to add <!-- emoticon scripting -->
section before <!--fan page search resource-->
it may be version issue,
you added
angularjs/1.2.14/angular.min.js and angular.js/1.3.7/angular-sanitize.min.js
try to use same version


text:
Q: How to know if a point is inside a complex 3D shape (.ply file) I'm working on a Java project witch is really killing me. After several days of researching on different forums, looking for what I really need, I come to ask your help.
My data :

*

*A .ply file (containing a 3D shape made of a lot of triangles)

*A point (3D coordinates)

I would like to know if this point is contained inside the complex 3D shape.
I have split this problem in 2 smaller problems :

*

*How can I represent the complex 3D shape in memory? (I found several libraries, but it seems really complex for the task I want to do : Java3D, JBullet, JME3...) I do not want my java application to show the object for now.

*How can I know if this point is inside the 3D shape or not? (I thought to make a 3D vector starting from the point and to count the number of intersections with the shape, but I don't see how to do and witch library can I use?)
Maybe there are easier ways to do it, that's also why I come to you.
I am really stuck now and I would like if this is possible without writing customs libraries...
(Sorry for my writing, I'm not English ^^)
Thanks for helping me.

A: Here is one approach.  Not the best or the fastest, but once you have something working, it will be easier to improve upon.

How can I represent the complex 3D shape in memory?

Implement a quick and dirty PLY file format parser.  Here is the PLY format spec.  Load the data up and store it internally: an array for each X, Y, and Z.  This is all just plain Java.

How can I know if this point is inside the 3D shape or not?

Define a line based on your point and some other arbitrary point.  For each polygon, determine where it intersects the plane (some help) and if the intersection point is inside or outside the polygon (some help).  As you suggested, then count the number of intersections to determine if the point is inside or outside your 3d shape.


text:
Q: How to use shared library for Android NDK (C lib adding to C++) So. I found this lib in C called fastpbkdf2 and made shared lib out of it.
I created small C++ snippet that'll call one of the methods from the lib. But I'm constantly getting
error: undefined reference to ...

I search for so many stuff, try everything, but no luck. I'm probably missing something obvious here. (oh, and I've never programmed for C++ or C so maybe that could be the problem)
All the files are in same folder.
Here's Android.mk
LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE           := pbkdf2core
LOCAL_SRC_FILES        := libpbkdf2core.so
include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE    := pbkdf2
LOCAL_SRC_FILES := pbkdf2.cpp
LOCAL_SHARED_LIBRARIES := pbkdf2core
include $(BUILD_SHARED_LIBRARY)

Here's my try in C++:
#include <jni.h>
#include "native.h"
#include <pbkdf2core.h>

extern "C"{
    JNIEXPORT jbyteArray JNICALL Java_com_package_generatePBKDF2key
    (JNIEnv * env, jclass cls, jbyteArray password, jbyteArray salt, jint iterations)
    {
            uint8_t * out;

            fastpbkdf2HmacSha1(jbyteArrayToString(env, password),
                env->GetArrayLength(password),
                jbyteArrayToString(env, salt),
                env->GetArrayLength(salt),
                (int) iterations, out, 32);

            jbyteArray bytes = env->NewByteArray(32);
            env->SetByteArrayRegion(bytes, 0, 32, (jbyte*)out);
            return bytes;
            //return password; --> running only this works ok
    }

    uint8_t* jbyteArrayToString(JNIEnv* env, jbyteArray barr)
    {
           uint8_t* rtn = NULL;
           jsize alen = env->GetArrayLength(barr);
           jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);
           if (alen > 0)
           {
                     rtn = (uint8_t*)malloc(alen + 1);
                     memcpy(rtn, ba, alen);
                     rtn[alen] = 0;
           }
           env->ReleaseByteArrayElements(barr, ba, 0);
           return rtn;
    }

    //commenting out "bad" code, and running only this really works
    JNIEXPORT jint JNICALL Java_com_package_getNum(JNIEnv * env, jclass cls){
        return 1;
    }
}

And pbkdf2core.h:
#include <jni.h>
#include <stdlib.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif
void fastpbkdf2HmacSha1(const uint8_t *pw, size_t npw,
                          const uint8_t *salt, size_t nsalt,
                          uint32_t iterations,
                          uint8_t *out, size_t nout);
#ifdef __cplusplus
}
#endif

When I skip the "bad" code, everything is ok (I can run the other method, or return anything from the first, so all the other setup should be ok).
If I change anything from header, I get different error (not declared). What am I missing here?
(oh. the lib I'm using is in C.
Edit:
Here's error I get:
[armeabi] Compile++ thumb: pbkdf2 <= pbkdf2.cpp
[armeabi] SharedLibrary  : libpbkdf2.so
/Users/.../src/main/jni/pbkdf2.cpp:15: error: undefined reference to 'fastpbkdf2HmacSha1'
collect2: error: ld returned 1 exit status
make: *** [/Users/.../src/main/obj/local/armeabi/libpbkdf2.so] Error 1

Oh. I also tried with
LOCAL_ALLOW_UNDEFINED := true

Build does go ok (obviously), but then I get app runtime error:
java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "fastpbkdf2HmacSha1"

A: It looks like the linker cannot find the method fastpbkdf2HmacSha1, in your source code and the shared library. By forcing it to ignore the problem (e.g. using the LOCAL_ALLOW_UNDEFINED flag), you simple move the problem at runtime. That's why you get the UnsatisfiedLinkError (the VM tries to load the library, which has a missing dependency, and the loading fails).
First I would make sure that the library you are using is correct. You need to look into the libpbkdf2core.so for the missing symbol (fastpbkdf2HmacSha1). You can do this using readelf and nm. Nm will show you the symbols if you have a debug .so, whereas with readelf is a more powerful tool.
To get the symbol table from the .so do something like this:
readelf -Ws libpbkdf2core.so | grep fastpbkdf2HmacSha1

If the symbol is not there, you either have a corrupt .so or you are using the wrong .so?


text:
Q: Open windows in background I'm opening a second window in my main window. This window is used to display a progress bar, so I don't want to block my application when it is open.
My code is:
public partial class MainWindow : Window, IDisposable
{
    private void doUpdate(object sender, UpdateInfosArgs e)
    {
        this.Dispatcher.BeginInvoke(new Action(() =>
        {
            using (DownloadingFileWindow dlw = new DownloadingFileWindow())
            {
                dlw.OnDownloadFileComplete += OnDownloadFileComplete;
                this.Dispatcher.BeginInvoke((Action)(() => dlw.ShowDialog()));
                // or dlw.Show();
            }
        }
    }
}

Currently, when the window is shown, it is closed immediately when execution reaches the } of the using.
Is there a way to way that windows is closed?

A: To open a dialog as non-modal (non-blocking) you need to use Show() instead of ShowDialog().
Your second problem is your using statement. This disposes dlw again at the end of the using block, which closes the window.
So try this:
private void doUpdate(object sender, UpdateInfosArgs e)
{
    DownloadingFileWindow dlw = new DownloadingFileWindow();
    dlw.OnDownloadFileComplete += OnDownloadFileComplete;
    dlw.Show();
}

I don't think it's necessary to call Dispose() on the child window explicitly. See this question for a discussion of that.

A: The dialog will close after the using, because the using bracket cleans the object after finished the task in the using bracket.
To keep it open after your using bracket, you must not initiate the ressource for the using.
DownloadingFileWindow dlw = new DownloadingFileWindow()
dlw.OnDownloadFileComplete += OnDownloadFileComplete;
this.Dispatcher.BeginInvoke((Action)(() => dlw.ShowDialog()));

And within the Dialog itself, implement a closing routine like this.close(); by a trigger.


text:
Q: MSAL Node / Electron - PublicClientApplication.acquireTokenByCode() accessing Tokens despite clearing accounts I'm trying to clear all access Tokens from Main.Ts in an Electron App without success.
On the Node side of the App, I have a login function that implements the Auth Code Flow with PKCE  - which works fine:
let login = async () => {
  try {
    const authResult = await getTokenInteractive(authCodeUrlParams);
    mainWindow.webContents.send(IpcMessages.XXX-XXXX, authResult);
  } catch (error) {
    console.log(error);
  }
};

let getTokenInteractive = async (

tokenRequest: AuthorizationUrlRequest

): Promise\<AuthenticationResult\> =\> {

try {

     ...
     // Generate PKCE Challenge and Verifier before request
        const cryptoProvider = new CryptoProvider();
        const { challenge, verifier } = await cryptoProvider.generatePkceCodes();

     ...
     // Get Auth Code URL
    const authCodeUrl = await clientApplication.getAuthCodeUrl(
      localAuthCodeUrlParams
    );
    const authCode = await listenForAuthCode(authCodeUrl, authWindow);

    ...

// This works fine
const authResult: AuthenticationResult =
await clientApplication.acquireTokenByCode({
...authCodeRequest,
code: authCode,
codeVerifier: verifier,
});

    return authResult;

} catch (error) {

    throw error;

}
};

The logout function also clears the accounts:
    const logout = async () =\> {
         try {
   console.log("LOGOUT RECEIVED");
const accounts: AccountInfo\[\] = await clientApplication
.getTokenCache()
.getAllAccounts();
if (accounts && accounts.length \> 0) console.log(accounts);
await clientApplication.getTokenCache().removeAccount(accounts\[0\]);

     // Test to see if accounts are cleared returns '[]'
    const checkAccounts: AccountInfo[] = await clientApplication
      .getTokenCache()
      .getAllAccounts();

    console.log(checkAccounts);
    mainWindow.webContents.send(IpcMessages.USER_LOGGED_OUT);

} catch (err) {
console.log("Error in main.logout ", err);
}
};

Unfortunately, acquireTokenByCode still accesses the Token (?? How) when the user is redirected to a login page.
ps I've also checked local storage, Cookies etc in the browser and they are never populated (ie always remain empty).
I've seen numerous answers suggesting using a logout URL:
https://learn.microsoft.com/en-us/answers/questions/263335/msal-sign-out-does-not-appear-to-clear-cache.html
https://learn.microsoft.com/en-us/answers/questions/994601/logout-does-not-clear-session.html
However, these solutions down't work with Azure B2C. Also, redirecting using the logout endpoint using Electron.shell(openExternal([url])) also does nothing.
It's unbelievable that MS hasn't implemented a simple logout solution.
Question: Does anyone know how to stop tokens from being acquired WITHOUT having to open a native browser window or populate the Browser Window with a "Successfully signed out. You can now close this window" prompt ?
Thanks in advance.


text:
Q: Conditional WHERE according to Parameter I created a report but I've stopped on a hurdle that may be very simple for You but I can't think about any method that would let me solve my problem.
I have created a report based on SQL query (with multiple CTE) that should be parametrized by like that:
where
deliverydate between @FromDate and @ToDate
and
carrierid = @Carrier

And it's working so far. But I want to create another parameter that'll have 3 values. And depending on those values I want to get all the records that will meet the condition. Sorta like that:

*

*when parameter value = 1 then I want to get every record

*when parameter value = 2 then I want every record where column1 <>
column2

*when parameter value = 3 then I want to get every record where
column1 = column2

Column1 and column2 are columns from the report that I created.
The final select looks like that:
SELECT  SALESID ,
        CARRIERID ,
        dlvmodeid ,
        SUM(totalweight) AS totalweight ,
        SUM(totalcharges) AS totalcharges ,
        TOTALCHARGESCURRENCY ,
        SUM(HowManyPackagesForThisSO) AS HowManyPackagesForThisSO ,
        SUM(HowManyPackagesForThisSO_st) AS HowManyPackagesForThisSO_st ,
        SUM(InHowManyDays) AS InHowManyDays ,
        SUM(cspjnumber) AS HowManyPackingSlip
FROM    countingcte
WHERE   deliverydate BETWEEN @FromDate AND @ToDate
        AND carrierid = @Carrier
GROUP BY SALESID ,
        CARRIERID ,
        dlvmodeid ,
        TOTALCHARGESCURRENCY

Does anyone know a solution for my problem?
The exact columns that I have in mind are HowManyPackagesForThisSO and HowManyPackagesForThisSO_st.

A: Add this to your WHERE clause :
AND ((@Param = 1) OR
     (@Param = 2 AND col1 <> col2) OR
     (@Param = 3 AND col1 = col2))


text:
Q: C++ function in python from .dll using ctypes - function not found and access violation I have this simple C++ code named hello.cpp which has a function to print "Hello world"
#include <iostream>

void hello_world();

int main() {
    std::cout << "Start" << std::endl;
}

void hello_world() {
    std::cout << "Hello world" << std::endl;
}

I build the .dll (~1.9mb) using:
g++ -c hello.cpp
g++ -static -fPIC -o hello.dll hello.o

(using -shared gives a WinError 126 ... module not found when trying to access it in python)
The python code is:
from ctypes import cdll

lib = cdll.LoadLibrary('hello.dll')
lib.hello_world()

This throws the following error:
AttributeError: function 'hello_world' not found

I've read people mention that a __declspec(dllexport) wrapper is necessary and so is a extern "C" so that the code doesn't get "mangled". So now using that as the code:
#include <iostream>

extern "C" {
    __declspec(dllexport) void hello_world();
}

int main() {
    std::cout << "Opened" << std::endl;
}

void hello_world() {
    std::cout << "hello world" << std::endl;
}

The python line lib.hello_world() now raises:
OSError: exception: access violation writing 0x000E28A0

What are the issues here? How can I get python to recognise and run the C++ function in the .dll? Can I skip the middleman and somehow run a C++ function from a .cpp file or a .o file?
edit:
Using eryksun's answer, it turns out that the dllexport isn't needed. The extern "C" is a must though

A: Thanks to @eryksun, this was solved in this case by compiling like this:
g++ -c hello.cpp
g++ -static -shared -o hello.dll hello.o

Having the C++ code set up like so:
#include <iostream>

int main() {
    std::cout << "Opened" << std::endl;
}

void hello_world() {
    std::cout << "hello world" << std::endl;
}

extern "C" {
    void hello_world();
}

And running it from Python as usual:
from ctypes import cdll

lib = cdll.LoadLibrary('hello.dll')
lib.hello_world()


text:
Q: I can login to my server through the terminal, but can't get in through Mac network I can login to my ubuntu 18.04 server with my credentials as usual, but if I try to login through cmd + k on my mac and use the same login credentials, it doesn't allow me to login. Are there different credentials for this? do I have to create new ones?
UPDATE
I have my username JAKE and have my password myPassword which when I am on the server or use ssh, I can provide JAKE and myPassword to login. When on my mac, and I want to connect to a server, I put in smb://192.168.11.32/sambashare (the folder to connect to) and then it gives me the login screen, but JAKE and myPassword aren't working.

A: Not sure if you have configured this already, but Samba does not use the system password for your user.
You need to set one with sudo smbpasswd -a username
More information on configuring samba on Ubuntu can be found here: https://ubuntu.com/tutorials/install-and-configure-samba#4-setting-up-user-accounts-and-connecting-to-share


text:
Q: Post request to a service, get response ,validate response I am looking for a sample code to send request to a web service( SOAP) using C# .net
Get the response back and then validate the response automatically
Ex:http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit
 Send celcius data to this web service and get some response back and then validate this response with expected values.
I am looking to do this programmatically using C# nunit framework
Does anyone have idea how to achieve this?

A: There should be no logic worth testing in the web service itself.
You cannot easily test the web service call, and nor should you. This is the responsibility of the Framework.
Your web service should be a wrapper around the class that does the real work. You would then unit test the class with the logic in, not the web service.
In your example, you should have a class who's responsibility it is to convert Fahrenheit to Celsius. The public method that does this would be covered by your unit tests.
The end point you call to actually perform the conversion (for example, the methods in your .asmx file) would simply call the code above.

A: using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using NUnit.Framework;

namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main()
        {
String b = "OK";
            // Create a request using a URL that can receive a post.

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("your end point here");

        request.Headers.Add ("SOAPAction", "some soap action here");
        request.ContentType = "text/xml;charset=\"utf-8\"";
        request.Accept = "text/xml";
        request.Method = "POST";

        // Set the Method property of the request to POST.
        request.Method = "POST";
        // Create POST data and convert it to a byte array.
        string postData = @"<s:Envelope xmlns:s="Som request that you want to send";

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = byteArray.Length;
        Stream stream = request.GetRequestStream();

        stream.Write(byteArray, 0, byteArray.Length);

        int a = 0;
        stream.Close();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Assert.AreEqual(response.StatusCode, b, "Pass");

        Console.WriteLine(((HttpWebResponse)response).StatusDescription);


text:
Q: Creating a dictionary from a string where the values are the vowel counts from each word? I have the following string:
S = "to be or not to be, that is the question?"

I want to be able to create a dictionary that has the output of
{'question': 4, 'is': 1, 'be,': 1, 'or': 1, 'the': 1, 'that': 1, 'be': 1, 'to': 1, 'not': 1}

where I get the number of vowels in each word next to the word, not the count of each word itself. So far I have:
{x:y for x in S.split() for y in [sum(1 for char in word if char.lower() in set('aeiou')) for word in S.split()]}

with an output of:
{'or': 4, 'the': 4, 'question?': 4, 'be,': 4, 'that': 4, 'to': 4, 'be': 4, 'is': 4, 'not': 4}

How do I get a dictionary from a string where the values are the vowel counts from each word?

A:
number of vowels in each word next to the word, not the count of each word itself?

>>> s = "to be or not to be, that is the question"

first remove punctuation:
>>> new_s = s.translate(None, ',?!.')
>>> new_s
'to be or not to be that is the question'

then split on the whitespace:
>>> split = new_s.split()
>>> split
['to', 'be', 'or', 'not', 'to', 'be', 'that', 'is', 'the', 'question']

Now count the vowels in a dictionary. Note there are no redundant counts:
>>> vowel_count = {i: sum(c.lower() in 'aeiou' for c in i) for i in split}
>>> vowel_count
{'be': 1, 'that': 1, 'is': 1, 'question': 4, 'to': 1, 'not': 1, 'the': 1, 'or': 1}

A: You can use re (regex module) to find all the valid words (\w+ - does not includes spaces and commas), and use Counter to check the frequencies:
import re

from collections import Counter
s = "tell me what I tell you, to you"
print Counter(re.findall(r'\w+', s))

OUTPUT
Counter({'you': 2, 'tell': 2, 'me': 1, 'what': 1, 'I': 1, 'to': 1})


text:
Q: How to call constructor with 2 arguments from a no argument constructor? I am having trouble wrapping my head around this one. I have 2 constructors. The first has 2 arguments:
public Instrument(string name, string category)
{
    this.Name = name;
    this.Category = category;
}

Then I have a default(no argument) constructor with constants for defaults:
public Instrument()
{
    this.Name = DefaultName;
    this.Category = DefaultCategory;
}

I am also supposed to call the 2 parameter constructor from the no argument constructor. How do I do this? I also question why this is even necessary. If you are calling the 2 parameter from the default how would you ever pass the default values to the application?  So I guess my main question is how do I call the 2 parameter constructor from the default constructor?

A: by calling the two arg constructor from the default one, passing the default values, like this:
public Instrument() : this(DefaultName, DefaultCategory)
{

}

A: This is how you can do this...
public class Instrument
{
    public string Name;
    public string Category;

    public Instrument()
        : this("DefaultName", "DefaultCategory")
    {

    }

    public Instrument(string name, string category)
    {
        this.Name = name;
        this.Category = category;
    }
}

Now to answer the question why this is even necessary....
This is to make sure that if you ever come across an instantiated object inside the code - doesn't matter how it was instantiated (using either of constructor) - it will always have valid values in it's properties Name & Category.
Basically, it potentially makes your business objects bug free. Anyone using your business object will always have valid values in it's properties - either default or passed in using 2nd constructor.


text:
Q: MongoDB $geoNear in aggregation pipeline with the latest Java-Driver Ok what I am trying to do is to find the proper way to add $geoNear in the aggregation pipeline. I have managed to do that, by adding a org.bson.Document at aggregation pipeline List, but I think there should be a more clear way to implement it with the latest official mongoDB Java-Driver. For instance, in order to do that for $group, $project, $match, mongoDB Java-Driver provides Aggregates class and the relevant calls are:
Aggregates.group,Aggregates.project,Aggregates.match. What I am looking for is something like: Aggregates.geoNear, which is abscent. My example code looks like this:
createDocumentCollection()
            .aggregate(
                Arrays.asList(
                    // geoNear spherical geometry for 2d sphere
                    new Document("$geoNear", new Document()
                        .append("near", new Document()
                            .append("$geometry", new Document()
                                .append("type", "Point")
                                .append("coordinates", Arrays.asList(longitude, latitude)))
                            .append("$maxDistance", maxDistance))
                        .append("key", "avgGeoPoint")
                        .append("distanceField", "dist.calculated")),
                    // group
                    Aggregates.group("$mmsi",
                        Accumulators.first("mmsi", "$mmsi"),
                        Accumulators.first("vesselName", "$vesselName"),
                        Accumulators.first("shipType", "$shipType")),
                    // projection
                    Aggregates.project(Projections.fields(
                        Projections.excludeId(),
                        Projections.include("mmsi", "vesselName", "shipType"))),
                    // skip
                    Aggregates.skip(options.getSkip()),
                    // limit
                    Aggregates.limit(options.getLimit())))
            .map(ModelExtractor::extractPlainVessel)
            .forEach((Consumer<PlainVessel>) nearVessels::add);

The part I am trying to replace is this:
new Document("$geoNear", new Document()
           .append("near", new Document()
               .append("$geometry", new Document()
                   .append("type", "Point")
                   .append("coordinates", Arrays.asList(longitude, latitude)))
               .append("$maxDistance", maxDistance))
            .append("key", "avgGeoPoint")
            .append("distanceField", "dist.calculated"))


text:
Q: Umbraco / TeamCity BuildAgent nullReference error showing in Event Viewer I'm noticing a strange error cropping up regularly with a site I've inherited the maintenance of from a former colleague.
Does it ring any bells for any of you out there?
It's an umbraco v 4.0.4.2 site, and TeamCity is most definitely NOT installed on this machine.
Here's the message:
Exception information:
    Exception type: NullReferenceException
    Exception message: Object reference not set to an instance of an object.
Request information:
    Request URL: http://www.[[some website name]].co.uk/default.aspx
    Request path: /default.aspx
    User host address: [[some ip address]]
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
    Thread ID: 1
Thread account name: NT AUTHORITY\NETWORK SERVICE

Is impersonating: False

Stack trace:

at umbraco.requestHandler..ctor(XmlDocument _umbracoContent, String url) in d:\TeamCity\buildAgent\work\7380c184e9fcd3ea\umbraco\presentation\requestHandler.cs:line 230
at umbraco.UmbracoDefault.Page_PreInit(Object sender, EventArgs e) in d:\TeamCity\buildAgent\work\7380c184e9fcd3ea\umbraco\presentation\default.aspx.cs:line 113
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.EventHandler.Invoke(Object sender, EventArgs e)
at System.Web.UI.Page.OnPreInit(EventArgs e)
at System.Web.UI.Page.PerformPreInit()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Custom event details:
For more information, see Help and Support Center at

A: The reference to Teamcity is just telling where the original file was compiled from in the filesystem.
It is most likely that you are missing a dll in the bin folder.


text:
Q: How to correctly supply power to multiple 12 V devices wired in parallel? I am an artist, building a functional miniature which contains multiple devices (3 12 V computer fans, 1 cooling pump, two LED strips totauling 14 segments of three or 42 individual lights, and 1 Peltier tile). They are currently wired in parallel. I have been using an adjustable power supply, and it works however it only works when I turn the supply up to 19 V, which I know is bad for all of the devices. This supply claims a max of 3.4 A output. I also have a power supply which provides 12 V and 6 A, which when plugged in is insufficient to power the device. I have tried calculating what the current draw of the device should be, however I am not sure what the current draw of the Peltier tile is or how to determine it, and my best estimate is the the device should use possibly 4-7 Aat 12 V. Why does it work when I give it additional voltage, and yet when using a higher amperage power supply (possibly sufficient) it doesn't work? What would be a better hypothetical way to supply power to this device? How can I calculate the current the Peltier tile is drawing?
I am learning as much as I can about electrical engineering to safely build this object, and I know enough to hack together art objects, however I am not a professional, and I feel like I have come up against the limits of my ability to figure this out!
I do have a multimeter, which I've used to test the claimed voltage of my adjustable PSU, and it is accurate to what it is putting out.

A: The Peltier tiles consume a lot of power, and it sounds like you have no measuring equipment (multimeter) nor datasheets for the device.
It's safe to assume the tile alone consumes just about everything that your fixed power supply is rated for. I wonder how/if your adjustable power supply measures the voltage level when you set it or if it's just a knob with divisions and no indicator - in which case when you set the knob to 19V you are likely getting closer to the 12V you need to run everything.

A: I suspect you might be having a large voltage drop between your power supply and all your devices. So even though your power supply says 19V maybe only 13 or 14V are arriving to you devices.
What is the cable section and distance between your power supply and your devices? Also check with your voltmeter what is the voltage arriving at your devices. If it is how I suspect then increase the diameter of your cables.


text:
Q: How does `# -*- coding: utf-8 -*-` work in ruby? In Ruby, # is used for comments. Then, how will:
# -*- coding: utf-8 -*-

be detected? Will it ignore this line?

A: It's a magic comment.
From Script encoding:

The default script encoding is Encoding::UTF-8 after v2.0, but it can be changed by a magic comment on the first line of the source code file (or second line, if there is a shebang line on the first). The comment must contain the word coding or encoding, followed by a colon, space and the Encoding name or alias.


text:
Q: Passing object by value to a SubClass constructor leading to SuperClass's constructor not call I was trying to implement a SuperClass "Person" and inheriting from it some SubClasses.
The SubClass's constructor is passed an object from "Person" type and then calls parent contractor with object's member as passed value.
Everything is OK if pass the object to SubClass constructor by reference but, if pass the object by value then something strange happens. The SubClass object will create but not through the parent constructor (just a copy of the passed object will create and destroys after constructor ends.)
class Person
{
private:
    string _name;

public:
    Person (string name) : _name(name){cout << "Person registered.\n";}
    ~Person () {cout << "deleted\n";}
    string getName() {return _name;}
};

class Employee : public Person
{
public:
    Employee (Person p) : Person(p.getName()){};
};

int main()
{
    Person a("Jack");
    Employee b(a);
    cout << a.getName() << "\n";
    cout << b.getName() << "\n";
    cin.get();
    return 0;
}

I expected creation of 3 objects and destruction of one, but 2 objects were created and one was destroyed.
Expected output:
Person registered.
Person registered.
Person registered.
deleted
Jack
Jack
Actual output:
Person registered.
Person registered.
deleted
Jack
Jack
And as output shows, second object is created but not through constructor.
Any idea of how SubClass object creates?

A: When you define a class (or a struct), the compiler implicitly generates several functions (e.g. default constructor, destructor, copy-/move- constructor, and copy-/move- assignment operators, etc.) for you, depending on context (i.e. whether or not you yourself have defined one of those functions).
Here, when you pass the Person object a by value to the Employee object b, the compiler calls on the implicitly generated copy constructor, which basically is this:
Person (const Person& p) : _name(p._name) { /* add logging */ }

The implicitly-generated copy constructor's job is to call the copy constructors of all of the members of the class.
If you define the copy constructor yourself with a logging message, you will see that it's the 3 constructions and 1 destruction you expected, but one of the constructions was by copy as the compiler won't be able to copy-elide because its parameter is not a prvalue.
Note: the compiler can sometimes elide (i.e. choose not to perform in the first place) the copy constructor call and instead instantiate the to-be-copied object in place as an optimization. This means that user-defined copy constructors should never have any side effects.


text:
Q: angular-meteor patterns for handling multiple reactive variables efficiently I'm playing with angular-meteor and still trying to understand how to use 3-way binding. How do I run a method that checks multiple 'reactive' variables?
For example, the setVisibleLocation() method below would need to be re-run if any of the following values changed, event.setting.isPublic, event.participantIds, event.location, event.address, event.neighborhood, Meteor.userId(). The last few might not need to update reactively - a page reload might be acceptable.
showExactLocation = (event, userId) ->
  return true if event.setting.isPublic
  return true if userId == event.ownerId
  return true if event.participantIds && ~event.participantIds.indexOf(userId)
  return false

setVisibleLocation = (event, userId) ->
  userId ?= Meteor.userId()
  if showExactLocation(event, userId)
    event.visible = {
      address: event.address
      marker: event.location
    }
  else
    event.visible = {
      address: event.neighborhood
      marker: utils.maskLatLon(event.location, event.title)
    }
  return event

What are the more efficient patterns for handling this? I can think of a few options.
this.autorun ()=>
  this.getReactively('event', true)
  setVisibleLocation(this.event)
  // plus any number of other methods that might need to update
  // based on changes to this.event properties

or
this.autorun ()=>
  this.getReactively('event.setting.isPublic')
  this.getReactively('event.location')
  this.getCollectionReactively('event.participantIds')
  this.getReactively('event.address')
  this.getReactively('event.neighborhood')
  setVisibleLocation(this.event)
this.autorun ()=>
  // plus any number of other combination of reactive properties
  // and methods that need to be rerun

Is a deep watch advisable if event has a lot of properties to check?