text:
Q: Convert JavaScript function to Dart: Word of safety Is it possible to perform the same JavaScript function in Dart?
I was looking at the add-ons and found a complement that is close to what I am trying to do.
The complement found was:
https://pub.dev/packages/js_shims
You can read more here.
Documentation: JS_SHIMS
The function must return the encrypted password. For example:
Password: pass1234

In javascript the encrypted password returns me to: cGFzczEyMzQ=
My function JS DEMO:

var ezEncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

function ezEncode(){
  var str = document.getElementById('txtPassword').value;
  var out, i, len;
  var c1, c2, c3;

  len = str.length;
  i = 0;
  out = "";
  while(i < len)
 {
  c1 = str.charCodeAt(i++) & 0xff;
  if(i == len)
  {
   out += ezEncodeChars.charAt(c1 >> 2);
    out += ezEncodeChars.charAt((c1 & 0x3) << 4);
    out += "==";
    break;
  }
  c2 = str.charCodeAt(i++);
  if(i == len)
  {
     out += ezEncodeChars.charAt(c1 >> 2);
     out += ezEncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
     out += ezEncodeChars.charAt((c2 & 0xF) << 2);
     out += "=";
     break;
  }
  c3 = str.charCodeAt(i++);
  out += ezEncodeChars.charAt(c1 >> 2);
  out += ezEncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
  out += ezEncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
  out += ezEncodeChars.charAt(c3 & 0x3F);
 }
 document.getElementById('txtPassword').value = out;
  return out;
}
<!DOCTYPE html>
<html>
<head>
 <title></title>
</head>
<body>
<input type="text" hint="pass1234" value="pass1234" id="txtPassword"/>
<input type="button" value="Send" onclick="ezEncode('pass1234')"/>
</body>
</html>

My dart function
 var ezEncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

  ezEncode({String password}) {
    var out, i, len;
    var c1, c2, c3;

    len = password.length;
    i = 0;
    out = "";
    while(i < len)
    {
      c1 = js.charCodeAt(password, i++) & 0xff;
      if(i == len)
      {
        out += js.charAt(ezEncodeChars, c1 >> 2);
        out += js.charAt(ezEncodeChars, (c1 & 0x3) << 4);
        out += "==";
        break;
      }
      c2 = js.charCodeAt(password, i++);
      if(i == len)
      {
        out += js.charAt(ezEncodeChars, c1 >> 2);
        out += js.charAt(ezEncodeChars, ((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
        out += js.charAt(ezEncodeChars, (c2 & 0xF) << 2);
        out += "=";
        break;
      }
      c3 = js.charCodeAt(password, i++);
      out += js.charAt(ezEncodeChars, c1 >> 2);
      out += js.charAt(ezEncodeChars, ((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
      out += js.charAt(ezEncodeChars, ((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
      out += js.charAt(ezEncodeChars, c3 & 0x3F);
    }
    print(out);
  }

CONSOLE RUN
  E/flutter ( 4805): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: RangeError: Value not in range: 28
    E/flutter ( 4805): #0      _StringBase.substring (dart:core-patch/string_patch.dart:392:7)
    E/flutter ( 4805): #1      charAt (package:js_shims/src/strings.dart:5:45)

A: Just a word of safety. This password is not encrypted using this function. All your javascript function does is a base64 encode, a representation of the password string in a different character set. This is fully reversible and not a sufficient password encryption. Actually none at all. You can verify here that your "encrypted" password can be decoded to your original password string.
You should read up on how to properly secure and encrypt passwords in this answer.
If you're still interested in how to convert your string to base64 (not an encryption) you can use darts convert package from its core library.
https://api.dartlang.org/stable/2.1.0/dart-convert/dart-convert-library.html
import 'dart:convert';

ezEncodeChars(String notAPassword) {
  var bytes = utf8.encode(notAPassword);
  var base64Str = base64.encode(bytes);
  return base64Str;
}

A: Javascript function charAt returns an empty string when argument value is out of range. This empty string converts to integer 0. Dart throws an exception that value is not in range. You should handle out of range cases yourself.


text:
Q: Trouble checking if props is undefined So I have a page in my project that has a get and then it passes the response to a const, as below.
const [reference, setReference] = useState([])

useEffect(() => {
            api.get(`/${props.route.params.index}`).then( response => {
                setReference(response.data)
                setLegendaryAction(response.data.legendary_actions)
            }).catch( error =>
                console.log(error)
            )
        }, [])

Then I pass diferent parts of the reference to multiple instances of the same component.
As the following example, there is reference.action and reference.reaction. I will always have an action, but sometimes Reaction will be undefined, so I'm cheking if it's true before I render my component.
                <ReferenceDetails
                    detailTitle="Actions"
                    details={reference.actions}
                />
                {reference.reactions &&
                    <ReferenceDetails
                         detailTitle="Reactions"
                         details={reference.reactions}
                    />
                }

But it gives me this error:

Error: Text strings must be rendered within a  component.

But when I do console.log(reference.reactions) it returns undefined.
Could someone shed some light here please?

A: console.log(reference.reactions) should initially give undefined and then give expected value. Did you try console.log(reference?.reactions) ?
Or, console.log(reference && reference.reactions)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting "Could not find or load main class" only after I add dependencies in Maven I get this weird problem When I create new maven project and run the App, it's working as expected.But, When I add some dependencies in pom.xml, clean the project and run the app again, It says "Error: Could not find or load main class com.kishore.HibernateApp.App".
It's just a Hello world printing main class. Nothing fancy about the app.
My Questions are
1) Does is has to do anything with class path?
2) What might have went wrong when I add new dependencies in my pom.xml
3) Is this problem specific, expected? How to resolve this for ever?
Dependencies added

Run the app as below

Runtime configurations

Note: I've seen several answers similar to this error. But found none which has helped me. So I had to post this question.

A: Try this:
maven clean
maven install


text:
Q: Click automatically on Tabs Jquery with button I have html tabs and a continue shopping button. Every tab contains few products. When we land on the page by default first tab is opened. The requirement is this when we click on continue shopping button, user will automatically goes to next tab say tab2, tab3 and then finish i.e. user will have to traverse each tab after clicking on continue shopping button.
Here is my tab code

Warranty

Accessories

Software

    Content of Tab 1

    Content of Tab 2

    Content of Tab 3

Continue Shopping

Complete code of tabs are here:
http://jsfiddle.net/syahrasi/us8uc/

A: use simple setters in your javascript code
$( ".tab-content" ).tabs( "option", "active", 1 );
for more info check out the api documentation
http://api.jqueryui.com/tabs/

A: I made a quick demo here it will try to find the next tab, please have a look for more details and as if you need:
demo http://jsfiddle.net/Us8uc/4696/

A: Your button can have a click event that does this:
$("a[href='#tab-2']").trigger('click');

Replace #tab-2 with whatever tab you want to have open by the button
--edit--
Your button logic will look at the tab sequence and just add 1 to the end until there is no more tabs to traverse through. Alternatively, have a "Continue Shopping" button in each of the tab content moving forward


text:
Q: Making Input Element Style same with class I know my title is a little bit weird. I'm trying to add a  specific class to an input without directly adding the class name to it. Example:
I want .add CSS to be same with input[type="text"]. This is my code:
<style> input[type="file"] .add{background-color: #f7f7f7;} </style>

<input type="text"/>

I want the .add class to automatically apply to it; how do I do that?

A: The HTML:
<input type="file">

And you can try the following css:
input[type="file"] {
  background-color: yellow;
}

A: You have to create a class in CSS
.add{
   background:orange;
   // your css goes here
 }

and in your HTML you have to add  the class
<input type="text" class="add">

make sure that your CSS file is linked.

A: So you want to add a class in the input box but not directly.
Then Use JQuery
 $(function() {
  $('input').addClass('add');
});

Here is a jsfiddle example I made..


text:
Q: How to use multiple models inside one viewset/serializer? I have 2 items inside my system that I have to use.But I am trying to develop a system which i have to get them inside one view and order them by "timestamp".
class CalendarEventSerializer(serializers.ModelSerializer):

    class Meta:
        model = CalendarEvent
        fields = ("id","author",...)

class CalendarItemSerializer(serializers.ModelSerializer):

    class Meta:
        model = CalendarItem
        fields = ("id","author",...)

I use ViewSet to regulate my models to paginate and filter them.
class CalendarItemViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = CalendarItem.objects.all().order_by('-timestamp')
    serializer_class = CalendarItemSerializer
    filter_backends = [UserFilterBackend,DjangoFilterBackend]
    pagination_class = StandardResultsSetPagination
    filterset_fields = ['author']

class CalendarEventViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = CalendarEvent.objects.all().order_by('-timestamp')
    serializer_class = CalendarEventSerializer
    filter_backends = [UserFilterBackend,DjangoFilterBackend]
    pagination_class = StandardResultsSetPagination
    filterset_fields = ['author']

How can I use this system to merge 2 or models into one viewset or serializer like this?
Note:I know there are some answers for similar kind of questions in stackoverflow but my code structure is but different, I want to get some viewpoints
Update
So here is what i want to do:
-I am forming a feed page like facebook/instagram and combine multiple models inside one view.
-I can already do it with the viewsets above,but i want to now merge them.
-I want to sort each item by its timestamp and retrieve them inside JSON but inside one system, not like :
calendarevents:[] calendaritems []

but like:
calendarevent 1(created 2 mins ago)
calendaritem 1 (created 3 mins ago)
calendarevent 2(created 4 mins ago)
calendaritem 2(created 5 mins ago)

I am happy to include more information,just ask.
Update 2:
class CalendarEvent(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(User,  on_delete=models.CASCADE,related_name='calendarevents')
    charfield1 = models.CharField(max_length=300)
    integerfield1 = models.IntegerField(default='0')
    charfield2 = models.CharField(max_length=200,null=True, blank=True)
    charfield3= models.CharField(null=True,blank=True,max_length=64000)

class CalendarItem(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(User,  on_delete=models.CASCADE,related_name='calendaritems')
    charfield1 = models.CharField(max_length=300)
    integerfield1 = models.IntegerField(default='0')
    charfield2 = models.CharField(max_length=200,null=True, blank=True)
    charfield3= models.CharField(null=True,blank=True,max_length=64000)

A: You can customize the login using APIView and Generic APIVIEW
Here is one of the ways you can achieve what you are trying to achieve.
class GetCalenderEventAndItemsAPIView(APIView, GenericAPIView):
    permission_classes = (IsAuthenticated,)
    item_queryset = CalendarItem.objects.all().order_by('-timestamp')
    event_queryset = CalendarEvent.objects.all().order_by('-timestamp')
    item_serializer_class = CalendarItemSerializer
    event_serializer_class = CalendarEventSerializer
    filterset_fields = ['author']

    def get_paginated_query(self, _query_set):
        page = self.paginate_queryset(self.filter_queryset(_query_set))
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        return page

    def get(self, request, *args, **kwargs):
        event_serializer = self.event_serializer_class(self.get_paginated_query(self.event_queryset),
                                                       many=True)
        item_serializer = self.event_serializer_class(self.get_paginated_query(self.item_queryset), many=True)

        response_results = {
            "calendarevents": event_serializer.data,
            "calendaritems": item_serializer.data

        }
        return Response(response_results)

It will get you in the right direction. Just play around above way of doing it.

A: Another way to approach this is to use multi-table inheritance..[Django-doc] to create a parent model for both CalendarEvent and CalendarItem, where the common fields they have can be defined in the parent:
class CalendarFeed(models.Model):
    author = models.ForeignKey(User,  on_delete=models.CASCADE,related_name='calendarevents')
    charfield1 = models.CharField(max_length=300)
    integerfield1 = models.IntegerField(default='0')
    charfield2 = models.CharField(max_length=200,null=True, blank=True)
    charfield3 = models.CharField(null=True,blank=True,max_length=64000)
    timestamp = models.DateTimeField(auto_now_add=True)

class CalendarEvent(CalendarFeed):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class CalendarItem(CalendarFeed):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

Then you can just create a serializer and a viewset that captures all CalendarFeed like so:
class CalendarFeedSerializer(serializers.ModelSerializer):
    class Meta:
        model = CalendarFeed
        fields = "__all__"

class CalendarFeedViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = CalendarFeed.objects.all().order_by('-timestamp')
    serializer_class = CalendarFeedSerializer
    filter_backends = [UserFilterBackend, DjangoFilterBackend]
    pagination_class = StandardResultsSetPagination
    filterset_fields = ['author']

With these, you can list all CalendarEvent and CalendarItem via the parent CalendarFeed.


text:
Q: How to zero-extend a number if it is valid, or X-extend it otherwise? I have a 16-bit number which might be x (i.e. unknown).
I would like to zero-extend the number to 32 bits, but if the MSB is x, then I would like it to be x-extended instead of zero-extended. (This helps with my simulation.)
How can I do this?

A: Unless you are working with signed values, I think you will need a custom function for this. If you are working with signed values, the MSB will be X-extended on an assignment from a 16-bit value to a 32-bit value if the sign bit is X. However if the MSB (the sign bit) is a 1 then it will be 1-extended, which is most likely not what you want if you are working with unsigned values.
Here's a simple function to do this.
function [31:0] extend(input[15:0] in);
begin
   if (in[15] === 1'bX) begin
      extend = {16'hXXXX, in};
   end else begin
      extend = {16'h0000, in};
   end
end
endfunction

Example:
$display("%032b", extend(16'h0000));
$display("%032b", extend(16'hFFFF));
$display("%032b", extend(16'bX000_0000_0000_0000));

Output:
00000000000000000000000000000000
00000000000000001111111111111111
xxxxxxxxxxxxxxxxx000000000000000

A: If your simulator is modern enough to support SystemVerilog syntax:
module tb;

reg [15:0] a;
reg [31:0] b;

initial begin
    $monitor("a='b%b b='b%b", a, b);
    #5 a= '1; extendo();
    #5 a= '0; extendo();
    #5 a= 'z; extendo();
end

task extendo;
    b[15:0] = a[15:0];
    b[31:16] = (a[15] === 1'bx) ? 'x : '0;
endtask

endmodule

Output:
a='bxxxxxxxxxxxxxxxx b='bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
a='b1111111111111111 b='b00000000000000001111111111111111
a='b0000000000000000 b='b00000000000000000000000000000000
a='bzzzzzzzzzzzzzzzz b='b0000000000000000zzzzzzzzzzzzzzzz


text:
Q: What is the best tool or technique to write doxygen code comments Public c++ header files must be provided with a lot of comments. It is hard to format and wrap doxygen comments. Does some formatting tool exists?
With features like auto wrap lines on 80th character, easy visual function grouping. Ideally documentation writer prepares a documentation separately, then inject it into or link using doxytags with code.
At this time we are using notepad/IDE to document the code.

A: You don't say which IDE you're working with - If you're working in Visual Studio, then I've written an addin (AtomineerUtils) that might help you - It generates/updates XML, Doxygen or JavaDoc documentation comments in your source files, and can word wrap and format the comments for you, minimising the work you need to do to keep them tidy. It also keeps the comments in sync with the code (parameters, type-params, thrown exceptions, etc).
(It supports C, C++, C++/CLI, C#, Visual Basic and Java, in Visual Studio 2010, 2008, 2005).

A: Emacs + doxymacs works fine for me.


text:
Q: Angular not recognizinig type of object I have an angular project with a java backend.
the following is the scenario.
I create a DTO object in the Backend, and submit it to the frontend.
    ...
    QuestionResponseDTO dto = new QuestionResponseDTO();
    dto.setStart(ZonedDateTime.now());
    dto.setEnd(ZonedDateTime.now());
    dto.setDuration("X seconds");
    dto.setResponse(new ActivityListResponseDTO(Arrays.asList("Cooking", "Eating")));
    return dto;
}

in which the ActivityListResponseDTO just contains a List<String> activities.
Also note that ActivityListResponseDTO extends QuestionResponseBodyDTO.
In the frontend I send the request to the backend, and I receive the object back.
this is how the object looks like.
{"id":2,"responses":[{"id":0,"dto":{"start":"2021-06-16T09:08:28.142Z","end":"2021-06-16T09:08:28.142Z","duration":"X seconds",
"response":{
"activities":["Cooking","Eating"],
"typeName":"ActivityListResponseDTO",
"className":null},
"typeName":"QuestionResponseDTO",
"className":null}}]}

which means that the backend works fine.
The java classes I mentioned earlier have their corresponding classes in the Frontend with the exact same name. Idk what exactly happens to parse the response.
When I receive the object I check:
//angular
if (dto instanceof QuestionResponseDTO) {
        console.log("this ran");
        const responseBody = ((<QuestionResponseDTO>dto).response);

        if(responseBody instanceof ActivityListResponseDTO) {
          console.log("this ran 2");
          // because backend only returns a string
          const arr = (<ActivityListResponseDTO>responseBody)
            .activities.map(s => ({stringContent: s}));
...

The responseBody per default has the Type QuestionResponseBodyDTO in the frontend as well. the ActivityListResponseDTO extends this in the frontend too, so it should work.
but for some reason the program doesn't go in the inner if statement, and "this ran 2" is never logged.
Is there something I am doing wrong?

A: The response received from the HTTP API will be a simple JSON Object.
For it to work correctly on frontend, you will have to map that object to its corresponding type on frontend.
You can use json-object-mapper library to achieve this.

*

*Create a Typescript class named QuestionResponseDTO with all the nested object classes. I usually do this using json2ts which provides me interfaces and then I convert those interfaces to typescript classes.

*Use json-object-mapper or use your own class constructors to initialize the properties

*In your HTTP service, when you get the data, pipe that data to deserialize it to typescript object. http.get<QuestionResponseDTO>(url).pipe(map(data => ObjectMapper.deserialize(QuestionResponseDTO, data)));

*Once this is done, you should be able to correctly use instanceof on any nested objects


text:
Q: Select first child of class in different parents I want the first div with class .labelinput in different parents to be selected. I do not want to select by parent because I have different parents. Is it possible to define only once?
Tried:

div.labelinput:first-child {
  border-top: 1px solid #efefef;
}

style this

not this

not this

style this

not this

not this

style this

not this

not this

A: div .labelinput:first-child {
   border-top: 1px solid #efefef;
}

See http://jsbin.com/cupisefore/1/edit

A: Your example is working just be more specific:

div div.labelinput:first-child {
   color: red;
}

style this

not this

not this

style this

not this

not this

style this

not this

not this

After OP comments the final solution is:
div div.labelinput:nth-of-type(2) {
   border-top: 1px solid red;
}

A: First of type also works:
div.labelinput:first-of-type {
    border-top: 1px solid #efefef;
}

See http://jsfiddle.net/x7Lcutvx/9/


text:
Q: PBR shading only works in the corner of the window. DirectX 11 As the title implies i have problems with DirectX 11 shading.
The problem is shown in the picture below.
enter image description here
I have tried drawing it to the framebuffer, Change the math order in the shader, resize the BRDF to the window. But nothing seems to work.
I generate the BRDF with computeshader, same with the irradience map and cube map.
I use a Equirectangular image to get the cube data.
any sugestion would help, thanks!


text:
Q: Make Outlook compose outgoing plain-text emails in monospaced font Due to corporate standards, I use Outlook 2013 (15.0.4779.1001, says the About dialog that Microsoft has cleverly hidden in "File | Office Account")
When I reply to an email, I don't want my reply to be HTML but rather plain text, as God intended emails to be.
The way I've figured out how to do this is to

*

*Press the "Reply" (or "Reply all", as appropriate) button.

*Press "Pop Out".

*Press the "Format text" tab in the pop-up window.

*Press the "Plain Text" item in the toolbar jumble.

*Answer "yes" in the "Formatted text will become plain text" nag box that appears.

*Manually wrap quoted lines and add > quote marks in the text I'm responding to, correct "RE:" in the subject line to "Re:", and so forth.

My problem is that about half of the time, seemingly without any pattern to it, the email after step 5 ends up displaying in Times Roman rather than the usual monospaced font, which makes it difficult to wrap lines consistently, draw ASCII art and so forth.
This problem doesn't occur all the time but when it does occur it does so consistently: switching back and forth between plain text and HTML will not make the monospaced font appear. Neither will force-changing the entire email to be in Consolas while in HTML mode before I press the "Plain Text" button.
Question: Is there a way to force Outlook to use monospaced font when COMPOSING plain-text emails?
I have managed to configure it to use a monospaced font when DISPLAYING incoming plain-text emails, but this setting doesn't seem to take for writing the emails.

A: I know this is a really old question, but the answer above isn't what OP wanted, I wanted to do the same thing, and found that there is actually a way to do this, just below the option that @Burgi recommended, so I'm going to start with his instructions.

*

*Click File -> Options

*Click the Mail option in the dialog

*There is an option entitled:

Use stationary to change default fonts and styles, colors, and backgrounds.

*Click the Stationary and Fonts... button to the right of it

*The dialog has two tabs, and the active one should be Personal Stationary

*At the bottom of that tab, there is a section called

Composing and reading plain text messages

*Use the Font... button to select a mono-spaced font for plain text messages

A: I haven't figured out how to check the version myself but I can help with the formatting issue.

*

*Click File -> Options

*Click the Mail option in the dialog

*There is an option entitled:

Compose messages in this format

*Select Plain Text from the dropdown and hit OK

BONUS ROUND
You can get messages you are composing to automatically appear in the pop-out format without clicking the annoying "pop-out" button.
On the same options tab as before, scroll down to "Replies and forwards". Then tick the option called:

Open replies and forwards in a new window


text:
Q: Pandas sum over multiple columns after group by if I have a data set where the columns are something like:
Day Column2 Column3 Column4......Column100

Is there a better way to do something like the below?
grouped_df = df.groupby('Day').agg({
'Column2': lambda x : sum(x),
'Column3': lambda x : sum(x),
'Column4': lambda x : sum(x),
..........
'Column100': lambda x : sum(x)})

What I have works but wondering if there is a more elegant solution.
Thank You

A: You can try df.groupby('Day').sum() just like what  MaxU said.

A: you can do it this way:
In [17]: df
Out[17]:
    a  b  c  d  e        Day
0   7  5  4  9  4 2016-01-01
1   2  1  5  4  5 2014-01-01
2   2  8  8  6  9 2014-01-01
3   1  4  4  3  7 2015-01-01
4   5  6  7  9  5 2016-01-01
5   3  6  0  8  7 2015-01-01
6   7  4  4  5  5 2014-01-01
7   1  1  0  1  6 2015-01-01
8   7  8  9  8  3 2015-01-01
9   8  5  5  2  8 2015-01-01
10  6  1  3  0  3 2014-01-01
11  1  8  2  7  2 2016-01-01
12  2  5  2  5  1 2016-01-01
13  1  2  3  2  2 2016-01-01
14  7  4  9  5  2 2016-01-01
15  4  0  8  9  5 2015-01-01
16  8  5  8  9  7 2015-01-01
17  6  7  9  5  4 2016-01-01
18  7  4  2  3  2 2016-01-01
19  2  7  8  6  8 2015-01-01

In [18]: cols = df.columns

In [19]: cols[1:]
Out[19]: Index(['b', 'c', 'd', 'e', 'Day'], dtype='object')

In [20]: df.ix[:, cols[1:]].groupby('Day').sum()
Out[20]:
             b   c   d   e
Day
2014-01-01  14  20  15  22
2015-01-01  36  42  46  51
2016-01-01  41  38  45  22

setup sample DF:
rows = 20
df = pd.DataFrame(np.random.randint(0, 10, size=(rows, 5)), columns=list('abcde'))
dates = [pd.to_datetime(d) for d in ['2016-01-01','2015-01-01','2014-01-01']]
df['Day'] = np.random.choice(dates, len(df))


text:
Q: How to recover a list sent by a javascript function called through cefSharp in my c# program after a page has loaded? I'm writting a c# program using cefSharp which uses the data present on a webpage. My problem comes when retrieving the information I need form the webpage. I nedd to get that information as a list.
I first tried simply waiting for the entire page to have fully loaded however this is way too long given the fact that I only need the DOM to be loaded and that retrieving the list should be carried efficently. I was advised to use an eventHandler to be able to call the javascript method returning the list exactly when the DOM is done loading. My problem is that an eventHandler can't return any value so even though I can call my method at the right time, I can't get the value it returns in my c# program. I dont know what to do. Is there a way to call my method at the right time and still get the value it returns?
Here is the code i have tried :
browserStartedLoading = async (sender, args) =>
{
   browser.EvaluateScriptAsync("window.addEventListener('DOMContentLoaded',
   function() { ... });").ContinueWith(x =>
   {
                            var response = x.Result;
                            if (response.Success && response.Result != null)
                            {
                                list = (List<object>)response.Result;

                            }
   });
}


text:
Q: Why is python decode replacing more than the invalid bytes from an encoded string? Trying to decode an invalid encoded utf-8 html page gives different results in
python, firefox and chrome.
The invalid encoded fragment from test page looks like 'PREFIX\xe3\xabSUFFIX'
>>> fragment = 'PREFIX\xe3\xabSUFFIX'
>>> fragment.decode('utf-8', 'strict')
...
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 6-8: invalid data

UPDATE: This question concluded in a bug report to Python unicode component. The Issue is reported to be fixed in Python 2.7.11 and 3.5.2.

What follows is the replacement policies used to handle decoding errors in
Python, Firefox and Chrome.  Note how they differs, and specially how
python builtin removes the valid S (plus the invalid sequence of bytes).
Python
The builtin replace error handler replaces the invalid \xe3\xab plus the
S from SUFFIX by U+FFFD
>>> fragment.decode('utf-8', 'replace')
u'PREFIX\ufffdUFFIX'
>>> print _
PREFIX�UFFIX

Browsers
To tests how browsers decode the invalid sequence of bytes will use a cgi script:
#!/usr/bin/env python
print """\
Content-Type: text/plain; charset=utf-8

PREFIX\xe3\xabSUFFIX"""

Firefox and Chrome browsers rendered:
PREFIX�SUFFIX

Why builtin replace error handler for str.decode is removing the S from SUFFIX
(Was UPDATE 1)
According to wikipedia UTF-8 (thanks mjv),
the following ranges of bytes are used to indicate the start of a sequence of
bytes

*

*0xC2-0xDF : Start of 2-byte sequence

*0xE0-0xEF : Start of 3-byte sequence

*0xF0-0xF4 : Start of 4-byte sequence

'PREFIX\xe3\abSUFFIX' test fragment has 0xE3, it instructs python decoder
that a 3-byte sequence follows, the sequence is found invalid and python
decoder ignores the whole sequence including '\xabS', and continues after it
ignoring any possible correct sequence starting in the middle.
This means that for an invalid encoded sequence like '\xF0SUFFIX', it will
decode u'\ufffdFIX' instead of u'\ufffdSUFFIX'.
Example 1: Introducing DOM parsing bugs
>>> '
\xf0
Price: $20
...
'.decode('utf-8', 'replace')
u'
\ufffdv>Price: $20
...
'
>>> print _

�v>Price: $20
...

Example 2: Security issues (Also see Unicode security considerations):
>>> '\xf0'.decode('utf-8', 'replace')
u'\ufffd-  -->'
>>> print _
�-  -->

Example 3: Remove valid information for a scraping application
>>> '\xf0' + u'it\u2019s'.encode('utf-8') # "it's"
'\xf0it\xe2\x80\x99s'
>>> _.decode('utf-8', 'replace')
u'\ufffd\ufffd\ufffds'
>>> print _
���s

Using a cgi script to render this in browsers:
#!/usr/bin/env python
print """\
Content-Type: text/plain; charset=utf-8

\xf0it\xe2\x80\x99s"""

Rendered:
�it's

Is there any official recommended way for handling decoding replacements?
(Was UPDATE 2)
In a public review, the Unicode Technical Committee has opted for option 2
of the following candidates:

*

*Replace the entire ill-formed subsequence by a single U+FFFD.

*Replace each maximal subpart of the ill-formed subsequence by a single U+FFFD.

*Replace each code unit of the ill-formed subsequence by a single U+FFFD.

UTC Resolution was at 2008-08-29, source: http://www.unicode.org/review/resolved-pri-100.html
UTC Public Review 121 also includes an invalid bytestream as example
'\x61\xF1\x80\x80\xE1\x80\xC2\x62', it shows decoding results for each
option.
            61      F1      80      80      E1      80      C2      62
      1   U+0061  U+FFFD                                          U+0062
      2   U+0061  U+FFFD                  U+FFFD          U+FFFD  U+0062
      3   U+0061  U+FFFD  U+FFFD  U+FFFD  U+FFFD  U+FFFD  U+FFFD  U+0062

In plain Python the three results are:

*

*u'a\ufffdb' shows as a�b

*u'a\ufffd\ufffd\ufffdb' shows as a���b

*u'a\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdb' shows as a������b
And here is what python does for the invalid example bytestream:
>>> '\x61\xF1\x80\x80\xE1\x80\xC2\x62'.decode('utf-8', 'replace')
u'a\ufffd\ufffd\ufffd'
>>> print _
a���

Again, using a cgi script to test how browsers render the buggy encoded bytes:
#!/usr/bin/env python
print """\
Content-Type: text/plain; charset=utf-8

\x61\xF1\x80\x80\xE1\x80\xC2\x62"""

Both, Chrome and Firefox rendered:
a���b

Note that browsers rendered result matches option 2 of PR121 recomendation
While option 3 looks easily implementable in python, option 2 and 1 are a challenge.
>>> replace_option3 = lambda exc: (u'\ufffd', exc.start+1)
>>> codecs.register_error('replace_option3', replace_option3)
>>> '\x61\xF1\x80\x80\xE1\x80\xC2\x62'.decode('utf-8', 'replace_option3')
u'a\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdb'
>>> print _
a������b

A: the 0xE3 byte is one (of the possible) first bytes indicative of a 3-bytes character.
Apparently Python's decode logic takes these three bytes and tries to decode them. They turn out to  not match an actual code point ("character") and that is why Python produces a UnicodeDecodeError and emits a substitution character
It appears, however that in doing so, Python's decode logic doesn't adhere to the recommendation of the Unicode Consortium with regards to substitution characters for "ill-formed" UTF-8 sequences.
See UTF-8 article on Wikipedia for background info about UTF-8 encoding.
New (final?) Edit: re the UniCode Consortium's recommended practice for replacement characters (PR121)
(BTW, congrats to dangra to keep digging and digging and hence making the question better)
Both dangra and I were partially incorrect, in our own way, regarding the  interpretation of this recommendation; my latest insight is that indeed the recommendation also speaks to trying and "re-synchronize".
The key concept is that of the maximal subpart [of an ill-formed sequence].
In view of the (lone) example supplied in the PR121 document, the "maximal subpart" implies not reading-in the bytes which could not possibly be part of a sequence.  For example, the 5th byte in the sequence, 0xE1 could NOT possibly be a "second, third or fourth byte of a sequence" since it isn't in the x80-xBF range, and hence this terminates the ill-formed sequence which started with xF1.  Then one must try and start a new sequence with the xE1 etc.  Similarly, upon hitting the x62 which too cannot be interpreted as a second/third/fourth byte, the bad sequence is ended, and the "b" (x62) is "saved"...
In this light (and until corrected ;-) ) the Python decoding logic appears to be faulty.
Also see John Machin's answer in this post for more specific quotes of the underlying Unicode standard/recommendations.

A: You know that your S is valid, with the benefit of both look-ahead and hindsight :-) Suppose there was originally a legal 3-byte UTF-8 sequence there, and the 3rd byte was corrupted in transmission ... with the change that you mention, you'd be complaining that a spurious S had not been replaced. There is no "right" way of doing it, without the benefit of error-correcting codes, or a crystal ball, or a tamborine.
Update
As @mjv remarked, the UTC issue is all about how many U+FFFD should be included.
In fact, Python is not using ANY of the UTC's 3 options.
Here is the UTC's sole example:
      61      F1      80      80      E1      80      C2      62
1   U+0061  U+FFFD                                          U+0062
2   U+0061  U+FFFD                  U+FFFD          U+FFFD  U+0062
3   U+0061  U+FFFD  U+FFFD  U+FFFD  U+FFFD  U+FFFD  U+FFFD  U+0062

Here is what Python does:
>>> bad = '\x61\xf1\x80\x80\xe1\x80\xc2\x62cdef'
>>> bad.decode('utf8', 'replace')
u'a\ufffd\ufffd\ufffdcdef'
>>>

Why?
F1 should start a 4-byte sequence, but the E1 is not valid. One bad sequence, one replacement.
Start again at the next byte, the 3rd 80. Bang, another FFFD.
Start again at the C2, which introduces a 2-byte sequence, but C2 62 is invalid, so bang again.
It's interesting that the UTC didn't mention what Python is doing (restarting after the number of bytes indicated by the lead character). Perhaps this is actually forbidden or deprecated somewhere in the Unicode standard. More reading required. Watch this space.
Update 2 Houston, we have a problem.
=== Quoted from Chapter 3 of Unicode 5.2 ===
Constraints on Conversion Processes
The requirement not to interpret any ill-formed code unit subsequences in a string as characters (see conformance clause C10) has important consequences for conversion processes.
Such processes may, for example, interpret UTF-8 code unit sequences as Unicode character
sequences. If the converter encounters an ill-formed UTF-8 code unit sequence which
starts with a valid first byte, but which does not continue with valid successor bytes (see
Table 3-7), it must not consume the successor bytes as part of the ill-formed subsequence
whenever those successor bytes themselves constitute part of a well-formed UTF-8 code
unit subsequence.
If an implementation of a UTF-8 conversion process stops at the first error encountered,
without reporting the end of any ill-formed UTF-8 code unit subsequence, then the
requirement makes little practical difference. However, the requirement does introduce a
significant constraint if the UTF-8 converter continues past the point of a detected error,
perhaps by substituting one or more U+FFFD replacement characters for the uninterpretable,
ill-formed UTF-8 code unit subsequence. For example, with the input UTF-8 code
unit sequence <C2 41 42>, such a UTF-8 conversion process must not return
or , because either of those outputs would be the result of misinterpreting a well-formed subsequence as being part of the ill-formed subsequence. The
expected return value for such a process would instead be .
For a UTF-8 conversion process to consume valid successor bytes is not only non-conformant,
but also leaves the converter open to security exploits. See Unicode Technical Report
#36, "Unicode Security Considerations."
=== End of quote ===
It then goes on to discuss at length, with examples, the "how many FFFD to emit" issue.
Using their example in the 2nd last quoted paragraph:
>>> bad2 = "\xc2\x41\x42"
>>> bad2.decode('utf8', 'replace')
u'\ufffdB'
# FAIL

Note that this is a problem with both the 'replace' and 'ignore' options of str.decode('utf_8') -- it's all about omitting data, not about how many U+FFFD are emitted; get the data-emitting part right and the U+FFFD issue falls out naturally, as explained in the part that I didn't quote.
Update 3 Current versions of Python (including 2.7) have unicodedata.unidata_version as '5.1.0' which may or may not indicate that the Unicode-related code is intended to conform to Unicode 5.1.0. In any case, the wordy prohibition of what Python is doing didn't appear in the Unicode standard until 5.2.0. I'll raise an issue on the Python tracker without mentioning the word 'oht'.encode('rot13').
Reported here

A: In 'PREFIX\xe3\xabSUFFIX', the \xe3 indicates that it and the next two bites form one unicode code point. (\xEy does for all y.) However, \xe3\xabS obviously does not refer to a valid code point. Since Python knows it's supposed to take three bytes, it sucks up all three anyhow since it doesn't know your S is an S and not just some byte representing 0x53 for some other reason.

A:
Also, is there any unicode's official recommended way for handling decoding replacements?

No. Unicode considers them an error condition and doesn't consider any fallback options. So none of the behaviours above are 'right'.


text:
Q: peculiar jQuery .closest when using $(this) This statement does not work:
$(this).closest(".myclass").addClass("myextraclass");

But this statement does:
$("div").closest(".myclass").addClass("myextraclass");

It is being used in this context (with the mark.js library):
instance.markRegExp(/mypattern/gi, {className:"myclass", done: function() {
    $(this).closest(".myclass").addClass("myextraclass");
  }});

SOLUTION: (courtesy Baro and Chay22):
$(node).closest(".myclass").addClass("myextraclass");

context,
instance.markRegExp(/mypattern/gi, {className:"myclass", each: function(node) {
        $(node).closest(".myclass").addClass("myextraclass");
      }});

A: I don't know what you want exactly without see the HTML, and I think something is wrong on your logic. This because you add myclass at all element highlighted and with closest you are looking for a father element with this class.

$("div").closest(".myclass").addClass("myextraclass");

This work because is a simple JQuery command, nothing else.

$(this).closest(".myclass").addClass("myextraclass");

this in that context is the Mark object, and not the elements highlighted or the father element.

If you want all elements highlighted try this:
JSFiddle example
HTML

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ut augue neque. Cras euismod varius metus ut bibendum.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ut augue neque. Cras euismod varius metus ut bibendum.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ut augue neque. Cras euismod varius metus ut bibendum.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ut augue neque. Cras euismod varius metus ut bibendum.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ut augue neque. Cras euismod varius metus ut bibendum.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ut augue neque. Cras euismod varius metus ut bibendum.

CSS
.findhere { color:red; }
.myclass { text-decoration:underline; }
.myextraclass { font-weight:bold; }
.green { color:green; }

JS
var instance = new Mark("div.findhere");
instance.markRegExp(/ipsum/gi, {className:"myclass", each: function(node) {
    $(node).addClass("green");
    $(node).closest(".findhere").addClass("myextraclass");
}});

A: You should use the jquery syntax of mark.ks if you are using jquery..
$(".context").markRegExp(regexp [, options]);


text:
Q: On Area 51 example questions, what are the criteria for classing a question as 'on-topic'? This question below has 16 yeses to 1 no and is classed as on-topic

Whereas this question has 6 yeses to 10 nos and isn't classed as on-topic or off-topic

Are there certain criteria before a question gets considered on-topic or off-topic. Is it a miminum number of votes in one direction and also a certain minimum difference between the yeses and nos?

A: To be marked on-topic you need:

*

*At least 20 on-topic votes

*At least 4 times as many on-topic as off-topic votes

It's the reverse for off-topic.
EDIT
The number of votes was raised to 20 (from 10), and the details have been added to the FAQ


text:
Q: Finding the "best" way to map set of points to another set I've got a set of points (currently 4, but I can increase the number for better accuracy), and I want to find the optimal transformation so that they can be mapped to another set of points.
For example, I have (2,2), (2, 4), (4, 2), (4, 4) which makes a 2x2 square if these points were connected. I have another set of points, say (2, 2), (2, 5), (3,2), (5,5) which resembles the shape of a rectangle, but clearly stretched, skewed, translated, or even possibly rotated. Using these two sets of points, how can I find the optimal skew factor, stretch factor, translation magnitudes (x and y) and rotational degree to apply to all points in set A so that they overlay as precisely as possible on set B?
Note: I'm actually trying to write a program to overlay one image onto another. I have selected points on both images that I know should be matched to each other. However, I'm having trouble calculating how to map one set onto the other. Please excuse the incorrect use of any math terms :P

A: As such the question is not totally well posed. You shoudl specify what kind of transformation you are looking at. If you have that, this will lead to a natural parametrization of your allowed tranformation. If have yan that, you can (for example) formulate a least squares approach.
In an abstract formulation: Denote the set of allowed transformations by $F$ (that is a class of functions  ${f:\mathbf{R}^2\to\mathbf{R}^2}$). Then you may solve
$$
\min_{f\in F} \sum_{a\in A}|F(a) - b|^2.
$$
A pointer: In image processing this problem is the problem of registration and a good math book is called FAIR by Modersitzki. See the website.


text:
Q: UnsupportedOperationException while adding a string to a list through ArrayAdapter What I am trying to do here is add the word currently in the EditText at the press of "Enter/Done" on the softkey. However, each time I press the "Enter/Done" on the soft key, the app crashes.
I've tried to do some debugging and it appears that the issue seems to be the adapter.add(v.getText().toString()); line. I am not sure why/how !!
  public boolean onEditorAction(TextView v,int actionId, KeyEvent event)    {
  Log.d("InThere","in onEditorAction1");
  if((event==NULL) || (event.getAction()==KeyEvent.ACTION_UP))
  {
     if(event==NULL)
     Log.d("InThere","inside if+EVENT");
     if(event.getAction()==KeyEvent.ACTION_UP)
    Log.d("InThere","inside if+ACTION_UP");
     Log.d("InThere","before adapter ");
         adapter.add(v.getText().toString());      <<<cause of error ?
     Log.d("InThere","after adapter ");
     v.setText("");

     InputMethodManager imm=(InputMethodManager)
     getSystemService(INPUT_METHOD_SERVICE);
     imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
  }

  Log.d("InThere","in onEditorAction2");
  return true;

}
I created a filter with the tag "InThere" and here's what it looks like in the LogCat:
InThere         in onEditorAction1
InThere         in onEditorAction2
InThere         in onEditorAction1
InThere         inside if+ACTION_UP
InThere         before adapter

Also, could you help me understand why the string is being obtained through an instance of TextView in the onEditorAction function when actually it is actually being obtained from EditText  ?
[UPDATE]
Here's the declaration part of the code....
private final static String[] items={"this","is","a","really","silly","list"};
 private static final KeyEvent NULL = null;
   private ArrayList<String> words=null;
    private ArrayAdapter<String> adapter;

    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        words = new ArrayList<String>();
        for(String s: items)
        {
            words.add(s);
        }
        adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
        setListAdapter(adapter);

    }

A: Yeah as suspected, your ArrayAdapter is backed by an array.
Array does not support the add operation.
Change it to be back by an ArrayList. ie:
private final static List<String> items = new ArrayList();
static {
  items.add("this");
  items.add("is");
  items.add("a");
  items.add("really");
  items.add("silly");
  items.add("list");
}

As WandMaker hinted, you seem to have done some work to create an ArrayList already, another solution could be:
 adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, words);

The optimum solution (with your code) being:
public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        List<String> words = new ArrayList<String>();
        words.add("this");
        words.add("is");
        words.add("a");
        words.add("really");
        words.add("silly");
        words.add("list");
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, words);
        setListAdapter(adapter);
    }


text:
Q: Changing the name of an app in manage applications Android menu I'd like my app to display on that menu with another name and icon, to be clear, I'm refering to the menu that shows all apps installed on the device, in which by tapping the app you can access the options for force stop, uninstall, clear data etc.
It looks like the app displays with the name defined for it on AndroidManifest.xml, with something like:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="mylabel"

And that label cannot be changed as shown here: Android : Change App Label Programatically. In fact, I also agree with a comment of the first answer that says it could give some security problems.
But I'm not 100% sure of that, as maybe the name it takes for displaying there is taking from another source that by default copies the name indicated in AndroidManifest.xml, but that can be changed in its own.
Is there some way to change the name of the application in that android menu?
I think the question is not a duplicate, as I'm asking about changing the name with which it displays on that manage applications menu, although it's true that if that were the only way, then it's duplicated.


text:
Q: Volume of the solid with given base, whose sections with the planes orthogonal to $y = 0$ are rectangles of height $4$ Please help me to solve the following problem:
Determine the volume of the solid having as base the portion of cartesian plane limited by $y = 0$ and by $y = x^{3}$ in the closed interval $\left[-1,1\right]$, whose sections with the planes orthogonal to $y = 0$ are rectangles of height $4$.

A: $$\left(\int_0^1 x^3 dx\right)\cdot 2\cdot 4=2$$
We are able to double it since it's symmetrical to get rid of the "negative" since we're dealing with the shape rather than the value. This gives us the area of the base of the object, so we can multiply it by 4 and arrive at the answer


text:
Q: How to assign a reference to a dynamically created object using Excel VBA There are some answers to similar questions, but none of them work for me. Most of them are geared towards Forms whereas I am trying to add objects directly onto Excel worksheets. Beyond that, nearly all are incredibly complicated solutions for something that should not be so difficult.
Here is the straightforward kind of thing I'm looking for - but I need it for ToggleButton and ComboBox. The code below works for CommandButton but it seems to have no analog for the other ActiveX object types, so far as I could tell.
Sub AddButtons()
    Dim ws As Excel.Worksheet
    Dim btn As Button

    For Each ws In ThisWorkbook.Worksheets
        Set btn = ws.Buttons.Add(10, 20, 30, 40)
        Debug.Print ws.Name
        ' MySub_[worksheet name] will be executed when btn is clicked
        btn.OnAction = "MySub_" & ws.Name
        btn.Caption = ws.Name
        ' Set additional btn properties as needed
    Next ws
End Sub

(I'm not actually trying to create an object for each worksheet, but this example shows how one can loop through some construct and tether customized code to the object created within each iteration.)
Thanks!

A: Activex controls are OLEObjects. I have shown how to add checkbox below.
Sub AddButtons()
    Dim ws As Worksheet
    Dim btn As OLEObject
    Debug.Print ("Start")
    For Each ws In ThisWorkbook.Worksheets
        Set btn = ws.OLEObjects.Add(ClassType:="Forms.CheckBox.1", Link:=True, _
        DisplayAsIcon:=False, left:=10, top:=10, width:=20, _
        height:=20)
        Debug.Print (ws.Name)
    Next ws
End Sub


text:
Q: Install-Package System.Data.SQLite.Core not working I try to run this command Install-Package System.Data.SQLite.Core in Nuget console but it does nothing :/

A: You could try these:

*

*Try to do the same using the GUI. Right click in the project -> Manage Nuget Packages.

*Check your nuget sources (although looks good in the screenshot)

*Check the references in you project. Sometimes the file packages.config contains an entry with the same package and the command does nothing because the target package is already there. If that's the case, delete the reference, delete the entry for the package on the package.config file and try the command again.

Hope this helps.


text:
Q: VueJS - function in import js file not getting triggered We are building a web application using Vue JS and PHP, we are new to Vue JS. The server-side execution is fine, the API is able to fetch data as JSON. While trying out a static array display before making the API call, we find that the function in imported "app.js" is not getting called and the table displayed is empty. Please let us know what we might be doing wrong. Appreciate your help.
import Vue from 'vue';

export const MY_CONST = 'Vue.js';
export let memberList = new Vue({
    el: '#members',
    data: {
        members: []
    },

    mounted: function () {
        this.getAllMembers();
    },

    methods: {
        getAllMembers: function () {
            /*
            axios.get("https://xxxxxx.com/services/api.php")
                .then(function (response) {
                    memberList.members = response.data.members;
                });
            */
            memberList.members = [{ "empname": "Dinesh Dassss" },
                                  { "empname": "Kapil Koranne" }];
        }
    }
});

This is the Vue component. The members object is empty.
<script>
    import * as mykey from './app.js'
    export default {
        name: 'Home',
        props: {
            msg: String
        },
        data() {
            return {
                message: `Hello ${mykey.MY_CONST}!`,
                members: mykey.memberList.members
            }
        }
    };
</script>

A: You can also use this reference for current instance reference:
getAllMembers: function () {
          var me = this;
            /*
            axios.get("https://xxxxxx.com/services/api.php")
                .then(function (response) {
                  // direct this not works here but we have
                 //saved this in another variable and scope of a var is there
                    me.members = response.data.members;
                });
            */
          // this reference works fine here.
            this.members = [{ "empname": "Dinesh Dassss" },
                          { "empname": "Kapil Koranne" }];
        }


text:
Q: VSCode python tasks Trato de configurar una tarea que ejecute python con argumentos.
He conseguido ejecutar el fichero principal, pero el argumento no lo coge igual que si lo ejecutase desde consola.
Se trata de leer un archivo de configuración y pienso, que al no estar ejecutándolo al mismo nivel de carpeta sino uno superior, la ejecución me da errores.
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "execute odoo",
            "command": "${workspaceFolder}/odoo/odoo-bin",
            "args": [
                "--config=${workspaceFolder}/odoo/debian/odoo.conf"
            ],
            "type": "shell",
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "reveal": "always",
                "panel": "new",
                "focus": true
            }
        }
    ]
}

A: Puedes usar el apartado options dentro del task para definir el directorio de ejecución del comando:
{
    "label": "execute odoo",
    "command": "${workspaceFolder}/odoo/odoo-bin",
    "args": [
        "--config=${workspaceFolder}/odoo/debian/odoo.conf"
    ],
    "type": "shell",
    "options": {
        "cwd": "${workspaceFolder}/odoo"
    },
    "group": {
        "kind": "build",
        "isDefault": true
    },
    "presentation": {
        "reveal": "always",
        "panel": "new",
        "focus": true
    }
}


text:
Q: A non-numeric value encountered Laravel 5 It's been a while since I'm getting the same Error after I installed the Laravel Voyager package, when I wanted to access the /admin it shows this error as mentioned in the picture.
I didn't get where the problem come from..
Please help
A non-numeric value encountered
Here is my code :
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Auth;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($page = 1)
    {
      $DBpostscheck= DB::table('posts')->where('whocanseethis', 'Everyone')->select('id')->get();
      $postcount = 0;
      $pageminus = $page  - 1;
      $toskip = $pageminus * 20;
      foreach($DBpostscheck as $post) {
          $postcount++;
      }
      $pagecount = ceil($postcount / 20);
        if($page > 1) {
            $previouspage = $page - 1;
        } else {
            $previouspage = false;
        }
        $nextpage = $page + 1;

      $DBposts = DB::table('posts')->where('whocanseethis', 'Everyone')->take(20)->skip($toskip)->get();
      $DBcategories = DB::table('categories')->get();

      //need for poll
      $allvotes = 0;
      $DBpoll = DB::table('poll')->get();
      $DBvotes = DB::table('pollvotes')->select('id')->get();
      foreach ($DBvotes as $vote) {
          $allvotes++;
      }
      //end
      if(isset(Auth::user()->name)) {
          $loggedid = Auth::user()->id;
          $DBrepliesthreads = DB::table('replies')->where('authorid', $loggedid)->get();
          array_set($array, 'arraycreator45236125312', 69);
          foreach ($DBrepliesthreads as $replythreads) {
              array_push($array, $replythreads->postid);
          }
          array_forget($array, 'arraycreator45236125312');
          $DBactivethreads  = DB::table('posts')->where('authorid', $loggedid)->orWhereIn('id', $array)->orderBy('updated_at', 'desc')->select('title', 'id')->groupBy('title')->take(6)->get();
          return view('home', ['DBposts' => $DBposts, 'page' => $page, 'pagecount' => $pagecount,'nextpage' => $nextpage, 'previouspage' => $previouspage,
              'DBcategories' => $DBcategories, 'DBactivethreads' => $DBactivethreads, 'DBpoll' => $DBpoll,'allvotes' => $allvotes]);
      }
      return view('home', ['DBposts' => $DBposts, 'page' => $page, 'pagecount' => $pagecount,'nextpage' => $nextpage, 'previouspage' => $previouspage,
          'DBcategories' => $DBcategories,  'DBpoll' => $DBpoll, 'allvotes' => $allvotes]);
    }
}


text:
Q: Deploying Node + MongoDB API on AWS or GCP I am working on a Node + MongoDB API and the API is deployed on a VM on Google Cloud Platform. Currently, the data is stored in a MongoDB instance running on the VM.
Is running a local MongoDB instance for production a good practice? And how does various cloud services providing MongoDB compare with each other? And what are some good practices to ensure the API is scalable? Also can deploying API to Kubernetes as a container offer better results as compared to VMs?

A: Having both server and database running in the same VM instance would always be a bad idea for a service that you want to scale. Let's think what happen if your instance could not handle the number of traffic being sent into anymore?
At first you might just do the vertical scale adding more CPU and RAM to the currently running instance and yes, that would be fine for some period of time. But it is actually more like a temporary life-extending plan since at some point, your instance will not be able to do the vertical scale anymore. And here come the horizontal scale...
New instance has to be created to handle the increasing number of traffic and how would you design the new instance for that?
The best practice is to have an instance that looks exactly the same as the first one. So the server is needed to be designed as a stateless one. In this case, your instance will be able to scale for at any number of machine.
That's why you should not have the API front end and database running in the same instance. It could not be scaled.
So how's about the database? It is quite straightforward. Just simply place it in the another VM instance! If database is still be able to handle the request, you can just share the database server among the server instances. But if there is a bottleneck on the database side, you can scale your mongoDB separately with cluster or so.
If you don't have time, you can consider using the ready-to-use service like Heroku Add-On, for example, mongolab, to managing the MongoDB instance for you.
Cheers.


text:
Q: A split function with two arguments returns error I tried to write a very simple code in python because I did not understand how line.split is working if we have two parameters. However, this code returns an error and I also did not understand the purpose of the line.split. Can you please help me?
from operator import itemgetter
import sys

word = None
count = 0
line= 'foo     1' \
      ''

line = line.strip()
try:
    word, count = line.split('\t', 1)
except:
    print('error')

count = int(count)
print(word, count)

A: Split returns a single list of strings split based on the delimiter you pass it.
'hey, you'.split(',') returns ['hey', ' you'] which can be unpacked if you provide two variables.
If the string you are splitting splits into a list of more than two values then you will have an error ValueError: too many values to unpack
In your case just check what the output of split is, it may be a list containing only one element foo    1, which cannot be unpacked.

A: line.split('\t') is returning only one value, and by word, count you are expecting two, so it results in the error: ValueError: not enough values to unpack (expected 2, got 1)
If you change that line to word, count = line.split() without any parameter in the split function, it will split on any whitespace by default, and it correctly returns the two values you expect with no errors.

A: What error message is returned, exactly? If it's a ValueError caused by the line.split('\t') line, then it probably means that the string doesn't actually contain a tab character, but a number of spaces. If you want to split the string on either tabs or spaces, omit the argument: line.split()

A: Easy,,, source
result = your_string.split(separator, max)

separator Optional. Specifies the separator to use when splitting the string. Default value is a whitespace
max Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences"

python string split returns a list of strings after breaking the given string by the specified separator.
So you cannot have word, count = line.split('\t', 1)
just use words= line.split('\t')


text:
Q: How can I see/display the value of a variable from views.py? views.py:
while i<10:
    temp = random.choice(possible)
    token = token + temp
    i=i+1

userf.email_token = token

I want to display/see the value of the variable token. How can I do this?

A: if you are using the test server (./manage.py runserver), printing to stdout (print token) will print to the console. you can also drop into a debugger, which will also use the console (import pdb; pdb.set_trace())

A: Use pprint module
import pprint
pprint.pprint(token)

or raise exception to stop script execution
raise Exception(token)

to see type type type() ;)
type(token)


text:
Q: How do I keep a table and caption together on the same page in Word? I have not found an answer to this.  I have a table in Microsoft Word 2016.  When I add a caption to the table, the caption appears in a random text box that often float off the page.
I have almost decided that the only way to keep this from happening is to add a row to the table that doubles as column headers and a caption.  Otherwise, I have to constantly fight this randomly positioned caption.  Is there any official way to (1) prevent the caption from appearing in these randomly positioned text boxes and (2) keep captions and tables together - right now my caption is on one page and my table on another page.

A: Select the Caption paragraph and the table. Then from the Format Paragraph dialog choose the Line and Page Breaks tab. On that tab is a checkbox for Keep with next. Mark it.


text:
Q: cypress run && node cucumber-html-report.js not generating html report when assertion fail I want to generate the html report in cypress when assertion failed.
I am using "multiple-cucumber-html-reporter" and I am able to generate when all passes.

A: When there is a failure cypress run returns a non-zero exit code and && will only continue executing if the previous call ends with a successful exit code. You need to switch the && to ;.


text:
Q: Hide your paths/filenames in apache in Apache 2.4, can I hide all "paths" from the browsers?
if somebody are on https://example.com/users/list.html it would only say https://example.com in the addressbar, and if someone takes a bookmark, it will also only take https://example.com and not the complete path
Preferably in the apache configuration


text:
Q: Evaluation of gene regulatory network I am new to this forum and data science, I will try my best to describe my question.
Question background:
I am molecular biology student and have recently inferred a gene expression network using 105 RNASeq gene expression datasets related to a bacterium, CLR algorithm from Minet R package. This network has 1784 nodes and 9897 edges. Now I would like to evaluate the network and determine precision recall metrics. Minet package has validate function where one compares their network with a reference network.
My question or problem:
I do not have a reference network to compare my network to in order to evaluate my network. Could you please let me know if there is a straight forward software or R package to generate a synthetic network and to validate my network or if there are synthetic bacterial networks with at least 1784 nodes that I could use for this purpose.
Finally, thank you very much and please let me know if I need to provide more information.
Best,
Ash
PS: I am an amateur when it comes to using R or data science. Learning snew mething e

A: Unless I'm missing something, I don't think that you can do what you wish to validate your results.
Things like precision/recall metrics* apply when you have known classifications and you are trying to see how well a model succeeds at assigning cases to classes. Classifications in this situation are whether or not 2 nodes (genes) share an edge (connection) in the network. Each potential edge is assigned to a "doesn't exist" or an "exists" class.
In the software package you cite, that evaluation shows how well the reconstruction of a network from gene-expression data captures a particular known network of gene associations. In that case, for each potential edge (connection) between two nodes (genes), you know whether or not there "really" is an edge. Precision and recall represent how well the edges predicted by the algorithm agree with what is known to be the case. Agreement provides reassurance that the method (using mutual information between gene-expression values to infer connections) fundamentally works.
As I understand your situation, however, your building of a network is based solely on the information you provide via the gene-expression data. There is no ground truth about which genes (nodes) are connected via edges. What you have is thus a type of unsupervised learning, in which you learn associations directly from the data. So unless you have independent knowledge of the actual structure of the underlying network, there is no ground truth against which to test your model. Whether or not your network corresponds with some similarly sized (real or synthetic) network of bacterial genes wouldn't contain information about how well your network represents the true relationships within your bacterium--unless that's the already known network for your bacterium.
There might be some interesting ways to look at similarities/differences between your networks and those of related bacterial species, see how well different gene-expression data sets agree with respect to the inferred networks, estimate the sensitivity of your network to vagaries in the underlying data, and so on. But those aren't directly connected to precision and recall.

*You will find many pages on this site that question the general usefulness of precision/recall, accuracy, and F-scores of the type that the package in question reports. The important point here is the distinction between supervised and unsupervised learning, explained for example in An Introduction to Statistical Learning, Section 2.1.4 and in Chapter 10.


text:
Q: Python: char capitalization one-by-one Trying to write a program which is to take a string as input and replace it's chars with capitalized ones one by one, printing how far it got at each iteration:
>>> house
House
HOuse
HOUse
HOUSe
HOUSE

After many hours of banging the head in this wall, i have produced a code which is likely way off, and feels like a dead end:
inp = input()
temp = []

for x in inp:
    if x != x.isupper():
        x = x.upper()
        temp.append(x)

        for y in inp:
            if y != y.isupper():
                y = y.upper()

                if y not in temp:
                    y = y.lower()
                    temp.append(y)
    break

print(temp)

<<< House

Essentially, all this does is capitalizing the first letter and adding the remaining ones. The idea was to put this loop in a function and run it for the len of the input. But i am realizing that this is probably not the right path from the very beginning.

A: you need only one for-loop:
for i in range(1, len(w)+1):
    print w[:i].upper()+w[i:]

A: s = "house"

l = [s[:i].upper() + s[i:] for i in range(len(s)+1)]

print l #['house', 'House', 'HOuse', 'HOUse', 'HOUSe']


text:
Q: How to add vary custom header My application is changing the content based on user country code.
Server request flow

https request -> nginx handle the ssl termination -> varnish -> if not cacheed, get contents from apache
http rquest -> varnish -> redirect to https link -> nginx handle the ssl termination -> varnish -> if not cached get contents from apache

Using varnish GeoIP module I found the user country code and set value to the header req.http.X-Country-Code I read this header value in the application.
Problem: It always caches the first hit and serves to all the locations
I hope adding vary header will resolve my problem, could you please guide me?
I'm not sure where to add vary header nginx or apache.

A: Adding the Vary header should fix the issue and if you have access to backed code it's preferred over changing the hash in Varnish.
Where to add it though? The best place would be to do it in the application. The application decides what to serve and it should have the power to decide what to cache and when, after all you could replace nginx or Varnish with something else in the future and there may be other caches between you and the client.


text:
Q: If $0 < \alpha < \alpha + \delta < \beta < \frac\pi2$ then $\tan\alpha + \tan\beta > \tan(\alpha + \delta) + \tan(\beta - \delta).$ For reasons that probably don't bear examination (I've rewritten my answer to this question, but I haven't posted the new improved version with added vitamins, because I wish to supplement my irritatingly long and pointless school-geometry proof with an equally quixotic school-trigonometry proof, avoiding the theory of convexity), I wish to prove:
$$
\text{If } 0 < \alpha < \alpha + \delta < \beta < \frac\pi2 \text{ then } \tan\alpha + \tan\beta > \tan(\alpha + \delta) + \tan(\beta - \delta)
$$
using only trigonometric identities familiar from secondary school mathematics.
All I have managed to come up with so far is this pathetic dog's dinner of a proof:
If $0 < \theta < \theta + \varphi = \frac\pi2,$ then
$$
\tan\theta + \tan\varphi = \tan\theta + \frac1{\tan\theta} = 2 + \left(\frac1{\sqrt{\tan\theta}} - \sqrt{\tan\theta}\right)^2,
$$
which decreases strictly with $\theta$ for $\theta \leqslant \frac\pi4.$
If $\alpha + \beta = \frac\pi2,$ then either $\alpha + \delta \leqslant \frac\pi4$ or $\beta - \delta \leqslant \frac\pi4,$ therefore $\tan\alpha + \tan\beta > \tan(\alpha + \delta) + \tan(\beta - \delta).$ $\ \square$
Assume from now on that $\alpha + \beta \ne \frac\pi2.$ Then $\tan\alpha\tan\beta \ne 1,$ and similarly $\tan(\alpha + \delta)\tan(\beta - \delta) \ne 1.$
Because $\alpha + \beta = (\alpha + \delta) + (\beta - \delta),$ the addition formula for the tangent function gives:
\begin{equation}
\label{eq:1}\tag{$1$}
\frac{\tan(\alpha + \delta) + \tan(\beta - \delta)}{\tan\alpha + \tan\beta} =
\frac{1 - \tan(\alpha + \delta)\tan(\beta - \delta)}{1 - \tan\alpha\tan\beta}.
\end{equation}
Because $\tan\alpha\tan\delta < 1,$ we can write, after some tedious manipulation (yawn-making details provided on request):
$$
\tan(\alpha + \delta)\tan(\beta - \delta) - \tan\alpha\tan\beta =
\frac{\tan\delta(1 - \tan^2\alpha\tan^2\beta)[\tan(\beta - \alpha) - \tan\delta]}
{(1 - \tan\alpha\tan\delta)(1 + \tan\beta\tan\delta)}.
$$
Therefore $\tan(\alpha + \delta)\tan(\beta - \delta) - \tan\alpha\tan\beta$ has the same sign as $1 - \tan\alpha\tan\beta.$
It follows that the right hand side of \eqref{eq:1} is always strictly less than $1,$ and we are done (more like done in!). $\ \square$
Surely it must be possible to do better than this? Please put me out of my misery, so that I can be rid of this stupid obesssion, and perhaps even get on with some slightly more respectable mathematics instead!

A: We need to prove that if $\{a,b,c,d\}\subset\left(0,\frac{\pi}{2}\right)$, $a\geq b$, $c\geq d$, $a\geq c$ and $a+b=c+d$ so
$$\tan{a}+\tan{b}\geq\tan{c}+\tan{d}.$$
Indeed, we need to prove that:
$$\frac{\sin(a+b)}{\cos{a}\cos{b}}\geq\frac{\sin(c+d)}{\cos{c}\cos{d}}$$ or
$$\cos(c+d)+\cos(c-d)\geq\cos(a+b)+\cos(a-b)$$ or
$$a-b\geq c-d$$ or
$$a-c\geq b-d,$$ which is obvious because $a-c\geq0$, but $b-d\leq0.$
I think it is better to use Karamata.
Indeeed, if $\beta-\delta\geq\alpha+\delta$ so
$$(\beta,\alpha)\succ(\beta-\delta,a+\delta).$$
If $\beta-\delta\leq\alpha+\delta$ so
$$(\beta,\alpha)\succ(\alpha+\delta,\beta-\delta).$$
In any case your inequality follows from Karamata because $\tan$ is a convex function on $\left(0,\frac{\pi}{2}\right).$


text:
Q: How to get Linux commands history in Splunk without Splunk Forwarder? We have tons of Linux machines which are all connected to Active Directory (AD). AD logs are being pulled in Splunk.
Is there a way to get the command history of all Linux machines in Splunk from AD logs (more like processes command line logs for Windows) without installing a Splunk forwarder in each one of them?

A: One solution would be to system syslog to a central syslog server, and running single Splunk Forwarder there. You could then bulk ingest logs, or only ingest logs for the systems you want. It also makes it a little easier to grow down the road as you can have any additional processes just syslog to the same server.


text:
Q: AEM query builder: search multiple properties How can I list all the properties and respective values for more than one property under a give node.
For example, the below code, I could search for one property only. But I need to search for 10 different property(alttext, img, promos.. etc) and get respective values(if exist) for it.
 Map<String, String> map = new HashMap<String, String>();
                    map.put(TYPE_PREDICATE, "nt:base");
                    map.put(PATH_PREDICATE, printAttachmentJsonNodePath);
                    map.put("property", "fileReference");
                    map.put("p.excerpt", "true");
                    map.put(SEARCH_LIMIT_PREDICATE, "-1");

                    Query query = queryBuilder.createQuery(PredicateGroup.create(map),
                            resourceResolver.adaptTo(Session.class));
                    SearchResult result = query.getResult();

                    for (Hit hit : result.getHits()) {
                        String path = hit.getPath();
                        Resource resourceHit = resourceResolver.getResource(path);

                            Node node = resourceHit.adaptTo(Node.class);

                            String fileReference = node.getProperty("fileReference").getString();
                            System.out.println(fileReference);
                    }

A: you can use numerical prefixes for multiple properties:
map.put("1_property", "jcr:content/cq:template");
map.put("1_property.value", "/apps/geometrixx/templates/homepage");
map.put("2_property", "jcr:content/jcr:title");
map.put("2_property.value", "English");

here is documentation

A: If you have a lot of properties, or amount of properties is generated during runtime you could use Predicate.class
Your code:
Map<String, String> map = new HashMap<String, String>();
map.put(TYPE_PREDICATE, "nt:base");
map.put(PATH_PREDICATE, printAttachmentJsonNodePath);
map.put("property", "fileReference");
map.put("p.excerpt", "true");
map.put(SEARCH_LIMIT_PREDICATE, "-1");

Query query = queryBuilder.createQuery(PredicateGroup.create(map),
        resourceResolver.adaptTo(Session.class));
SearchResult result = query.getResult();

Will looks in the following way:
PredicateGroup rootGroup = new PredicateGroup();
rootGroup.add(new Predicate("type").set("type", "nt:base"));
rootGroup.add(new Predicate("path").set("path", printAttachmentJsonNodePath));
rootGroup.add(new Predicate("property").set(property, "fileReference"));
rootGroup.add(new Predicate("property").set(property, "property1").set("value", value1));
.....
rootGroup.add(new Predicate("property").set(property, "propertyN").set("value", valueN));
rootGroup.set(Predicate.PARAM_EXCERPT, Boolean.TRUE.toString());
rootGroup.set(Predicate.PARAM_LIMIT, "-1");

Query query = queryBuilder.createQuery(rootGroup);
query.setHitsPerPage(limit); // also you could put limit here

SearchResult result = query.getResult();
...........

In this case AND condition will be created betwean properties : @property1=value1 AND @property2=value2
If you want OR, create separate group and add it to the root group:
PredicateGroup properties = new PredicateGroup();
properties.add(new Predicate("property").set(property, "property1").set("value", value1));
.....
properties.add(new Predicate("property").set(property, "propertyN").set("value", valueN));
properties.setAllRequired(false);

rootGroup.add(properties);


text:
Q: JQuery Mobile Datebox - How to remove the input box and show only the inline calendar? Good Day all,
I want to use datepicker to show the user particular dates that an event falls on. My game plan is to use datepicker as inline, show that it always shows and to pass the high lighted dates to it. My question is, how can I hide the input box, so the user only sees the calendar? Alternatively, the user could click a button to show the calendar, but I don't want them to be able to select a date.
Thanks
Mike

A: this helps:
.ui-input-datebox { width: 40px; border: 0; background: transparent; padding: 0;margin: 0; box-shadow: none;}
.ui-input-datebox input {display: none;}

A: with data-option "hideInput": "true" (see http://dev.jtsage.com/jQM-DateBox/demos/fullopt.html and then the "Display Options"-Accordion-Tab)
<input name="mydate" id="mydate" type="date" data-role="datebox" data-options='{"mode": "calbox", "hideInput": "true"}' />

A: Apparently I didn't get around to documenting this one - useInlineHideInput: true should do it.  I think it's dependent on useInline being true as well.

A: It can be done like that:
HTML
28/08/2013

<input data-role="datebox" data-options='{"mode": "calbox", "hideInput": "true", "noButton": "true"}' name="date" id="date" type="date" value="28/08/2013">

JS
$('#date-trigger').on( 'click', function(){
    $('#date').datebox('open');
});

Using Datebox2, see http://dev.jtsage.com/jQM-DateBox2/demos/opt/open.html.
David

A: Here is the good answer.
<input id="date-id" name="date" type="text" data-role="datebox" data-options='{"mode":"calbox", "hideInput": "true", "hideButton": "true", "useInline": "true"}'>

A: You can hide the input box using following code:

<input name="mydate" id="mydate" type="date" data-role="datebox" data-options='{"mode": "calbox", "calTodayButton": true}'>


text:
Q: Can't find Python 3 folder on Mac? I'm unable to find the python 3 folder on my Mac (Mojave). I have installed it correctly, and I've tried to reinstall it with but it says that it is already installed. I even installed a package (Mendel-development-tool) on it. Through my checking of the Mendel-development-tool (trying to uninstall it), it states that I have a folder with this:
/Users/username/Library/Python/3.7/bin/mdt

But, when I enter this path into my terminal, it shows python 2.7. And, when I look through to the site packages, mdt isn't there, and when I look through my library folder and see python, the only thing there is 2.7.
Does anyone know a fix to this?

A: It's not clear how you installed python, but it could literally be installed anywhere on disk
If you want to find something use the find command
sudo find ~ -type f -name mdt

If that returns nothing, then mdt is not in your home folder
You can also find all directories with Python in the name
sudo find ~ -type d -iname '*python*'

A: There may not be a python3 folder. What you probably want is the python3 application. Type

which python3

and see what you get. In my case, I get the location of the python3 application. I also have the application python3.7. Once you find the location of these apps you can make sure the location is in your PATH.
Installing a python version does not create a python folder.


text:
Q: How to add custom font in flutter web? So I am developing flutter mobile apps for some time now, and I want to explore flutter web, now I tried to add custom font but it is not showing custom font.
I have added all the dependencies and made a separate folder for fonts and added into pubspec.yaml like how I do in flutter mobile.
My main.dart

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red,
        title: Text("Dextroxd",
            style: TextStyle(
              fontSize: 36.0,
              fontFamily: 'CookieFam',
              color: Colors.white,
              fontWeight: FontWeight.w500
            )),
        centerTitle: true,
      ),
    );
  }
}

My pubspec
description: An app built using Flutter for web

environment:
  # You must be using Flutter >=1.5.0 or Dart >=2.3.0
  sdk: '>=2.3.0 <3.0.0'

flutter:
  fonts:
    - family: CookieFam
      fonts:
       - asset: assets/Cookie-Regular.ttf

dependencies:
  flutter_web: any
  flutter_web_ui: any

dev_dependencies:
  build_runner: ^1.6.2
  build_web_compilers: ^2.1.0
  pedantic: ^1.7.0

dependency_overrides:
  flutter_web:
    git:
      url: https://github.com/flutter/flutter_web
      path: packages/flutter_web
  flutter_web_ui:
    git:
      url: https://github.com/flutter/flutter_web
      path: packages/flutter_web_ui

A: Add font in the font folder and also add in the pubspec.yaml for example refer given images
Font Folder:

pubspec.yaml

now for the web add the assets folder in the web section and add below JSON file with the name web/assets/FontManifest.json

[
  {
    "family": "MuliBold",
    "fonts": [
      {
        "asset": "fonts/Muli-Bold.tff"
      }
    ]
  },
  {
    "family": "MuliExtraBold",
    "fonts": [
      {
        "asset": "fonts/Muli-ExtraBold.ttf"
      }
    ]
  },
{
    "family": "MuliRegular",
    "fonts": [
      {
        "asset": "fonts/Muli-Regular.ttf"
      }
    ]
  }
]

Great now your font applied to your flutter web application.


text:
Q: Sed command filtering extra text/removing "GET /?add=jt1777,justine,tignor,f,November_24_1983,Skeleton_,Italy HTTP/1.1" 200 34053

does anyone know how to use the sed command to cut out the extra lines or filtering like
"GET /?=jt1777,f,November_24_1983,Skeleton_,Italy HTTP/1.1" 200 34053"

but include just only the name "justine, tigor". Thats all I need, just the first and last name.
Any ideas???

A: Perhaps something like "cutting just" fields 2 and 3 could apply:
echo ..... | cut -d, -f2,3

A: You can use awk
echo "\"GET /?add=jt1777,justine,tignor,f,November_24_1983,Skeleton_,Italy HTTP/1.1\" 200 34053" | awk -F, '{print $2","$3}'

Explanation:

*

*-F, Here you're delimiting text with ,

*'{print $2","$3}' You'll print the field 2 and 3 within the delimiter ,. If you want to print the comma, since this is being used as delimiter, it won't print so you must hardcode it ","


text:
Q: Export HTML Table to Excel I have HTML table on the ASP.NET MVC View page.  Now I have to export this table to Excel.
(1) I have used partial view (Inquiries.ascx) to display the table data from database (using LINQ to Entity)
(2) I also have used UITableFilter plugin to filter the records (Ex:  http://gregweber.info/projects/demo/flavorzoom.html )
(3) At any point of time, I have to filter the visible records to Excel.
Appreciate your responses.
Thanks
Rita
Here is my View:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Mvc.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="cphHead" runat="server">

</asp:Content>

//Main Content
<asp:Content ID="Content1" ContentPlaceHolderID="cphContent" runat="server">

View All Inquiries

<input type="submit" value="Export to Excel" id="export" />

</asp:Content>

Strongly Typed Partial view user control (Inquiries.ascx) to generate table:

Filter Expression: <%= Html.TextBox("searchName")%>

            Tx_ID
            TX Date
            Name
            Email Address
            Products
            Document Name

    <% foreach (var item in Model) { %>

            <%= item.RequestID %>
            <%= String.Format("{0:d}", item.RequestDate) %>
            <%= item.CustomerName %>
            <%= Html.Encode(item.Email) %>
            <%= item.ProductName %>
            <%= Html.Encode(item.DocDescription)%>

    <% } %>

Here is my Controller code to load the Inquiries partial view:
[HttpGet]
        public PartialViewResult Inquiries()
        {
var model = from i in myEntity.Inquiries
  where i.User_Id == 5
                        orderby i.TX_Id descending
                        select new {
                            RequestID = i.TX_Id,
                            CustomerName = i.CustomerMaster.FirstName,
                            RequestDate = i.RequestDate,
                            Email = i.CustomerMaster.MS_Id,
                            DocDescription = i.Document.Description,
                            ProductName = i.Product.Name
                        };
            return PartialView(model);
        }

A: Try the jQuery plugin: table2csv. Use the argument, delivery:'value', to return the csv as a string.
Here is an implementation:

*

*Add a regular html input button and a .NET HiddenField to the page

*Add an onclick event to that button called "Export"

*Create a javascript function, Export, that stores the return value of table2CSV() into the hidden field, and posts back.

*The server receives the hiddenfield post data (the csv as a string)

*The server outputs the string to the browser as a csv file

.
// javascript
function Export()
{
    $('#yourHiddenFieldId').val() = $('#yourTable').table2CSV({delivery:'value'});
    __doPostBack('#yourExportBtnId', '');
}

// c#
if(Page.IsPostBack)
{
    if(!String.IsNullOrEmpty(Request.Form[yourHiddenField.UniqueId]))
    {
        Response.Clear();
        Response.ContentType = "text/csv";
        Response.AddHeader("Content-Disposition", "attachment; filename=TheReport.csv");
        Response.Flush();
        Response.Write(Request.Form[yourHiddenField.UniqueID]);
        Response.End();
    }
}

A: download components:npm install table-to-excel
https://github.com/ecofe/tabletoexcel

var tableToExcel=new TableToExcel();
document.getElementById('button1').onclick=function(){

    tableToExcel.render("table");

};
document.getElementById('button2').onclick=function(){
    var arr=[
        ['LastName','Sales','Country','Quarter'],
        ['Smith','23','UK','Qtr 3'],
        ['Johnson','14808','USA','Qtr 4']
    ]
    tableToExcel.render(arr,[{text:"create",bg:"#000",color:"#fff"},{text:"createcreate",bg:"#ddd",color:"#fff"}]);
};


text:
Q: How to insert a new column with repeated values into a pandas table? I'm new to Python. I have scraped a html table by pandas and I'm looking for ways to insert a new column with repeated string value and set it as the index of the table (as follow:). Reminded that the table is a long one :).
Original df:
Age IQ
12  100
15  111
 .   .
 .   .
 .   .
 .   .
13  121

Expected df"
Group  Age IQ
 A     12  100
 A     15  111
 .      .   .
 .      .   .
 .      .   .
 .      .   .
 A     13  121

A: Use assign to create a copy of your dataframe with a new column included:
df.assign(Group='A')

   Age   IQ Group
0   12  100     A
1   15  111     A
2   13  121     A

You can realign the columns afterwards
df.assign(Group='A')[['Group'] + df.columns.tolist()]

  Group  Age   IQ
0     A   12  100
1     A   15  111
2     A   13  121

However, you can edit the dataframe in place with insert.  This has the added bonus of allowing you to specify where the new column goes.
df.insert(0, 'Group', 'A')

df

  Group  Age   IQ
0     A   12  100
1     A   15  111
2     A   13  121


text:
Q: Indicator to indicate vibration on the phone Currently I am developing a app which would vibrate morse code.
I am using this code to vibrate the pattern:
int dot = 100;
int dash = 220;
int short_gap = 200;
int medium_gap = 700;
s = new long[] {0, dot, short_gap, dash, medium_gap}
Vibrator vibrator;
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(s, -1);

How do I add an indicator to indicate if my application is vibrating a dot or a dash?
I know I can use a for loop to transverse the long[] and then use a if else statement to change a textview background colour to indicate a change in the pattern. But how do I get the for loop to keep within the vibration ms for each change?

A: dot = new long[] {200, 100};
dash = new long[] {700, 220};
String s = "01";
for (int i = s.length() - 1, i >= 0, i--) {
  if (s.charAt(i) == "0") {
    // CHANGE TEXTVIEW HERE
    vibrator.vibrate(dot, -1);
  }
  else {
    vibrator.vibrate(dash, -1);
  }
}

Because it takes a few mil-seconds to execute the code before vibrate and to start the vibrator, you may need to shorten the time accordingly if you want to be accurate.

By the way, according to the api, your original code should be
s = new long[] { short_gap, dot, medium_gap, dash}


text:
Q: Boost.Asio without Boost.System On the Boost System page it is stated that:

The Boost System Library is part of the C++11 Standard Library.

But a number of Boost libraries, such as Asio, depend on Boost System. Is it possible to use the C++11 std stuff instead of Boost System to work with Asio?

A: AFAIR you can configure Boost System to be header-only

Source: http://www.boost.org/doc/libs/1_66_0/libs/system/doc/reference.html
Other than that, you might simply use Non-Boost Asio


text:
Q: Labelling of states using $R$-symmetry for ${\cal N=4}$ SUSY In Modern Supersymmetry by John Terning, page 13, the states of the massless supermultiplets of $N=4$ SUSY are labelled by the helicity and representation of R-symmetry under which they transform. However, for $N$ other than 4, only the helicity and degeneracy are used to label the states. Is there a reason why $N=4$ is singled out in this regard, or is it just a notational convention?
Further, for massive states, he uses spin and representation of R-symmetry to label the states for all $N$, so why was a similar treatment by replacing spin with helicity not done for the massless supermultiplets?

A: $\mathcal{N}$ in the $\mathcal{N}$ supersymmetry denotes the number of the supercharge spinors $Q_\alpha^a$. The $R$-symmetry comes from the $U(\mathcal{N}$) rotations in terms of $a$ index.
Now, when we construct the massless supermultiplet (usually choosing the frame of reference $p^\mu=E(1,0,0,1)$) we note (from the commutation relations) that one of each supercharge components $Q_1^a$ annihilates any state from that supermultiplet whereas the other component $Q_2^a$ is a helicity raising operator. Likewise $Q_{\dot{2}}^a$ is a helicity lowering operator. If $|-h_0\rangle$ is a state with some minimal helicity $-h_0$ then the states with helicity $-h_0+\frac{m}{2}$ can be constructed by application helicity raising operator $m$ times,
\begin{equation}
Q_2^{a_1}\ldots Q_2^{a_m}|-h_0\rangle
\end{equation}
with complete antisymmetry in $\{a_k\}$ indices thanks to $\{Q_\alpha^a,Q_\beta^b\}=0$. The degeneracy is a dimension of this state subspace i.e. the number of linearly independent states with the same helicity.
Now think what is the nature of $Q_2^{a_1}\ldots Q_2^{a_m}$ from the point of view of $R$-symmetry (more precisely its $SU(\mathcal{N})$ subgroup as $U(1)$ factor will simply give those states an irrelevant phase). This is a component of some antisymmetric tensor with $m$ indices. The result of the rotation will be a linear superposition of the components of the same tensor i.e. of other states with helicity $-h_0+\frac{m}{2}$. I.e. if you take all states with the same helicity from one supermultiplet they form a multiplet of $R$-symmetry. The aforementioned degeneracy is exactly the dimension of the corresponding representation.
The case $\mathcal{N}=4$ is special only in the following sense. If you start with $-h_0=-1$ the maximum helicity you can reach is $h_{max}=-1+\frac{\mathcal{N}}{2}$. For $\mathcal{N}=1,2,3$ those are $h_{max}=-\frac{1}{2},0,+\frac{1}{2}$ correspondingly. That means that this supermultiplet is not $\mathcal{CPT}$-invariant and you have to supplement it with extra states constructed by application of $\mathcal{CPT}$ operator on the original states. In case of $\mathcal{N}=2,3$ that obviously doubles the degeneracy of states $h=0$ (and for $\mathcal{N}=3$ of $h=\pm 1/2$). However for $\mathcal{N}=4$ you can reach $h_{max}=+1$ and get $\mathcal{CPT}$-invariant multiplet automatically.
Concerning Terning, it should be stressed that he notes very briefly the connection between degeneracy and the $R$-symmetry representation dimensions. E.g. he writes

Note that the degeneracy also tells us the dimension of representation of the $SU(2)_R$ subgroup of the $U(2)_R$ symmetry that each state belongs to.

But frankly from my quick look at this book I find it somewhat sloppy and skipping some points that may be important for a student just starting to learn susy (he doesn't even write full commutation relations of susy!) It looks more like a quick reference guide than a true textbook.


text:
Q: Copying JavaScript variables to SSI variables I started to use ssi and i came across with the ssi conditions -
if, elif, else, endif directives that work like conditional statements and are used to mark code which is to be included in a page if the conditions are met.
I know that there is a way to copy SSI variables to JavaScript variables.
The question is, if there is a way to do the other way (Copying JavaScript variables to SSI variables)?
I know that since the ssi is processed before the page reaches the browser it is possible to pass any variable from the SSI environment to client-side JavaScript.
maybe there is a manipulation way to do it?
EDIT:
There is a way to get parameters from the url (with ssi)?

A: No. It isn't possible.
Server side code runs. Then client side code runs.
Client side code can't send data to the server without starting a new HTTP request.
Such a request could cause the page to be reloaded with data in the query string, or it could use XMLHttpRequest (or some other Ajax tool) to fetch the data and insert it into the DOM using JS.


text:
Q: Angular stepper: Show a pop up on changing steps I am using Angular and Material. I have a stepper and I want to show a dialog message before changing step in order to ask the user if he wants to change step or not. The probleme is that the step is changing before of showing the pop up and the user's answer. Yout can find my exemple here:  https://stackblitz.com/edit/angular-angular-material-stepper-mok1em?file=src/app/app.component.ts
Bellow you can see the function that is called to change step:
public onStepChange(event: any, stepper:MatStepper): void {
    //in the stepper we have the data of current step and in the event of the clicked step
    console.log('Current step ' + stepper.selectedIndex + " next step " + event.selectedIndex);

          const dialogRef = this.dialog.open(DialogMessageN2Component, {
            width: '500px',
            height: '500px',
            data: {},
          });
          dialogRef.afterClosed().subscribe((result) => {
            console.log('The dialog was closed' + JSON.stringify(result));
            if (result.data === 'no') {
              console.log("no");
              stepper.selectedIndex = event.selectedIndex; //go to clicked step
            }
            if (result.data === 'yes') {
              console.log("yes");
               stepper.selectedIndex = stepper.selectedIndex; // stay to the same step

            }
          });

  }

Thank you in advance.

A: It's normal that the stepper goes to the next step before that your popup is opened because you're opening your popup inside the stepChage event that is called when you click on a button with a matStepperNext directive.
You can make it work by using a custom click event in your next buttons instead of a matStepperNext directive as shown below :
<mat-horizontal-stepper [linear]="false" #stepper>
  <mat-step [stepControl]="firstFormGroup">
    <form [formGroup]="firstFormGroup">
      <ng-template matStepLabel>Fill out your name</ng-template>
      <mat-form-field>
        <input matInput placeholder="Last name, First name" formControlName="firstCtrl" required>
      </mat-form-field>

        <button mat-button (click)="goToNextStep()">Next</button>

    </form>
  </mat-step>
  <mat-step [stepControl]="secondFormGroup">
    <form [formGroup]="secondFormGroup">
      <ng-template matStepLabel>Fill out your address</ng-template>
      <mat-form-field>
        <input matInput placeholder="Address" formControlName="secondCtrl" required>
      </mat-form-field>

        <button mat-button matStepperPrevious>Back</button>
        <button mat-button (click)="goToNextStep()">Next</button>

    </form>
  </mat-step>
  <mat-step>
    <ng-template matStepLabel>Done</ng-template>
    You are now done.

      <button mat-button matStepperPrevious>Back</button>
      <button mat-button (click)="stepper.reset()">Reset</button>

  </mat-step>
</mat-horizontal-stepper>

and your goToNextStep method will contain:
  goToNextStep(): void {
    const dialogRef = this.dialog.open(DialogMessageN2Component, {
      width: '500px',
      height: '500px',
      data: {},
    });
    dialogRef.afterClosed().subscribe((result) => {
      console.log('The dialog was closed' + JSON.stringify(result));
      if (result.data === 'yes') {
        console.log('yes');
        this.stepper.next();
      }
    });
  }

And don't forget to add @ViewChild('stepper') stepper: MatHorizontalStepper; in your component.