text:
Q: (Speed Calculate) How Make Simple way? I have huge dataframe,, hundred thousand row and column.
My data like this:
df

MAC T_1 X_1 Y_1 T_2 X_2 Y_2 T_3 X_3 Y_3 T_4 X_4 Y_4 T_5 X_5 Y_5 T_6 X_6 Y_6 T_7 X_7 Y_7
ID1 1   1   1   1   1   1   2   1   2   3   1   3   3   1   3   4   1   4   5   1   5
ID2 6   2   5   6   2   5   7   3   5   7   3   5   8   4   5   9   5   5   10  5   4
ID3 1   1   1   2   1   2   3   1   3   3   1   3   4   1   4   5   1   5   6   2   5

I want to calculate the speed using this equation:

I used code:
df = pd.read_csv("data.csv")
def v_2(i):
     return (df.ix[x,(5+3*(i-1))]-df.ix[x,(2+3*(i-1))])**2 + (df.ix[x,(6+3*(i-1))]-df.ix[x,(3+3*(i-1))])**2

def v(i):
    if (df.ix[x,(4+3*(i-1))]-df.ix[x,(1+3*(i-1))]) ==0:
        return 0
    else:
        if (df.ix[x,(4+3*(i-1))]-df.ix[x,(1+3*(i-1))]) <0:
            return 0
        else:
            return math.sqrt(v_2(i)) / (df.ix[x,(4+3*(i-1))]-df.ix[x,(1+3*(i-1))])

for i in range(1,int((len(df.columns)-1)/3)):
v_result = list()
for x in range(len(df.index)):
    v_2(i)
    v(i)
    v_result.append(v(i))
df_result[i]=v_result

my expected result:
MAC V1  V2  V3  V4  V5  V6
ID1 0   1   1   0   1   1
ID2 0   1   0   1   1   1
ID3 1   1   0   1   1   1

but this code takes huge time,
would you mind to give another idea more simple and fast process or using multiprocessing module.
thank you

A: The calculation can be sped up quite a bit through reshaping the data first, so that efficient pandas methods can be used. If that is not fast enough, you can then go down to the numpy array and apply the functions there.
first reshape the data from the wide format to a long format so that there are only 3 columns, T, X, Y. The column suffixes, i.e. _1, _2, etc are split out into a new index.
df = df.set_index('MAC')
df.columns = pd.MultiIndex.from_arrays(zip(*df.columns.str.split('_')))
df = df.stack()

this produces the following data frame:
        T  X  Y
MAC
ID1 1   1  1  1
    2   1  1  1
    3   2  1  2
    4   3  1  3
    5   3  1  3
    6   4  1  4
    7   5  1  5
ID2 1   6  2  5
    2   6  2  5
    3   7  3  5
    4   7  3  5
    5   8  4  5
    6   9  5  5
    7  10  5  4
ID3 1   1  1  1
    2   2  1  2
    3   3  1  3
    4   3  1  3
    5   4  1  4
    6   5  1  5
    7   6  2  5

Next calculate the del_X^2, del_Y^2 & del_t (I hope the usage of prefix del is unambiguous). This is easier done using these two utility functions to avoid repetition.
def f(x):
    return x.shift(-1) - x

def f2(x):
    return f(x)**2

update: description of functions

The first function calculates F(W,n) = W(n+1) - W(n), for all n, where n is the index of the array W. The second function squares its argument. These functions are composed to calculate the distance squared. See the documentation for pd.Series.shift for more information & examples.

using lower-case column names for the del prefix above and the suffix 2 to mean squared:
df['x2'] = df.groupby(level=0).X.transform(f2)
df['y2'] = df.groupby(level=0).Y.transform(f2)
df['t'] = df.groupby(level=0).Y.transform(f)
df['v'] = np.sqrt(df.x2 + df.y2) / df.t

df.v.unstack(0)

produces the following which is similar to your output, but transposed.
MAC  ID1  ID2  ID3
1    NaN  NaN  1.0
2    1.0  1.0  1.0
3    1.0  NaN  NaN
4    NaN  1.0  1.0
5    1.0  1.0  1.0
6    1.0  1.0  1.0
7    NaN  NaN  NaN

you can filter out the last row (where the computed columns t, x2 & y2 are null), fill the np.nan in v with with 0, transpose, rename the columns & reset index to get at your desired result.
result = df[pd.notnull(df.t)].v.unstack(0).fillna(0).T
result.columns = ['V'+x for x in result.columns]
result.reset_index()
# outputs:

   MAC   V1   V2   V3   V4   V5   V6
0  ID1  0.0  1.0  1.0  0.0  1.0  1.0
1  ID2  0.0  1.0  0.0  1.0  1.0  1.0
2  ID3  1.0  1.0  0.0  1.0  1.0  1.0

A: I suggest you use Apache Spark if you want a real speed.
You can do that by passing your function to Spark as described here in this documentation:
Passing function to Spark


text:
Q: Do python scripts need to be exited? I've been using Python more and more recently, and I'd like to know if Python scripts need an exit statement at the end? If they don't is it proper to always add an exit statement at the end of a script?

A: No, python scripts do not need an exit- in fact, a raw quit() or exit() at the end of many things may break them - in the case of importing something, all top-level code is executed: if that contains an exit(), the whole importing program will exit, which is almost certainly not desired.
If in doubt, Python will almost always clean up after itself (zombie threads may be an exception, but that's way more advanced).

A: You do not need an exit statement in Python code, unless you want to set the exit code yourself

A: This is unnecessary. There is no such thing as an "exit statement" in Python, and calling a function like sys.exit() at the end of your program does the same thing as just letting execution flow off the end of your program.

redpajama_set_name: RedPajamaStackExchange


text:
Q: i386 C process - What happens in the remaining 1 GB of addressable space? It's documented that variables allocated on the heap are stored in the low address area and grow towards the stack and vice versa. I decided to test this out:
#include <stdio.h>
#include <stdlib.h>

const char my_const_global_var = '0';
char my_global_var = '0';

int main(void) {
    char my_stack_var = '0';
    char* my_heap_var = (char*) malloc(1);
    *my_heap_var = '0';
}

It appears that my_const_global_var and my_global_var are addressed in the low address area (shortly after 000XXXXX and before the heap) but what surprises me is that my_stack_var is addressed exactly around the 75% mark (around bffbdaXX). I'm guessing I'll get a segfault when my global/heap/stack variables exceed 3 GB of memory, so I did a search and found mention of a 3 GB barrier but no mention of what happens in the remaining 1 GB of addressable space.
What happens in the remaining 25% of the memory address space?

A: Protected mode operating systems running on 32-bit x86 CPUs usually divide the 32-bit virtual address space into to two main regions. The first is for user processes and the second is for the kernel. The virtual address space doesn't address physical memory directly. Instead it's mapped through a page table maintained by the kernel to physical memory. This allows the operating system to give each process its own virtual address space, isolating them from each other. When it switches processes it changes page tables so that the user area of the virtual address space points to the physical memory locations used by the new process.
However when it switches processes, the operating system doesn't change page table entries that correspond to the kernel region. This means that while each process has its own physical memory mapped into the user region, the kernel region remains the same for each process. Mapping the kernel memory into the virtual address space of each process allows for much quicker transition from user mode to kernel mode when performing system calls. If the kernel wasn't mapped into every process, the operating system would essentially have to switch processes (to a hypothetical kernel "process") to perform a system call. Switching processes is a much more expensive operation than just transitioning from user mode to kernel mode.
Most 64-bit x86 operating systems also have similar split, but since they have much bigger a virtual address space they divide the virtual address space into much larger chunks. When running 32-bit programs these operating systems usually give the program access to all or nearly all of the first 4 GB of virtual address space.
Note that how virtual memory is split into user and kernel regions is unaffected by the amount of physical memory in the system. Unless explicitly configured differently, a machine with only 64 MB of RAM will have the same user/kernel virtual address space split as a machine with 64 GB of memory when running the exact same operating system.


text:
Q: What is the difference between following two sentences? What is the difference between following two sentences ?

*

*How many hours do they have you working in the company ?

*How many hours do they have you work in the company ?

if i want to ask someone how many hours he is working in the company, do i have to use sentence 1. ? If i used sentence 2, would it be wrong ?

A: This is a peculiarity of English grammar. Many languages do not do this.
The word "working" is, in this instance, not a gerund but a participle; whereas work is just an infinitive with the particle "to" omitted.
Better idiom is probably sentence 2, "work," in most cases. However, if you mean to emphasize present continuation rather than general status, you might prefer sentence 1, "working."
The difference is the same as the difference between these:

*

*I am working.

*I work.
The distinction between these two is subtle. It is a distinction many languages lack.

A: The first sentence doesn't make sense to me. I would use the second.
These sentences both use "causative have" - "have someone do something" is similar inform and meaning to "make someone do something".
The difference may become clearer if we change "have" to "make" and also turn the sentences into declarations:

*

*They make me working in the company 9 hours a day.

*They make me work in the company 9 hours a day.

The second sentence fits what I think you mean. The first may be grammatically correct, but I don't see what it means and why anyone would use it; if the sentence is supposed to be in present progresive, it should use "They are making me work..." instead.
If I'm missing the point, please reply and explain.
Note that it may make more sense with past progressive instead: "they had me working 9 hours a day" means that, for a specific period in the past, you were forced to work 9 hours a day. I think the difference is that this period has started and has ended, unlike the present progressive which does not imply the end of the described action.


text:
Q: Spoon Feeding is it negative or positive Normally we use a phrase "spoon feeding"
Is it negative or positive phrase. or it's all about how we treat it.
Thank you so much!:)

A: Spoon feeding is necessary for babies who had not yet learned to use their hands sufficiently to even navigate the food into their own mouths.
In the metaphorical spoon-feeding of information to an adult, the adult is being implicitly compared to the aforementioned child in its very early developmental stage. It is implied that the recipient of the information is less prepared to receive and process the information as it was expected from them.
So the phrase is quite likely to express disapproval.
Yet, for completeness' sake, I appear to find at least two different scenarios:

*

*used with clear negative connotation, e.g. in emotionally saturated gossip,

*or used in a somewhat neutral, merely illustrative fashion, for the sake of efficiency, to describe someone's lack of faculties, or preparedness, to process information aimed at them.
(But take note, if it would happen in the described person's presence, it would still come across offensive. So it's probably negative, even then.)
On top of these, I would be surprised if someone found an example when it ever gets used with a positive connotation.


text:
Q: Debugging illegal access to a freed memory I am chasing a bug for few weeks now. I am working with multi threaded environment (C++, VC2010) and what I sometimes see is a crash on a new or delete.
When I look at the output I see a complain about a memory that was freed and after that was modified (HEAP: Free Heap block 55e6128 modified at 55e619c after it was freed). When I look at the memory at the same address (0x55e6128) I can see a pattern of 0xFEEE and then 00 00 00 00 then again FE EE.
It looks to me as a deleted object that has a long, 4 bytes, member (or a pointer) and someone tried to set this member to zero after the object was deleted.
Any idea how to debug that?

A: Is the 4-byte member public? If so, this is an example of why public data members are bad and you should almost always make them private or protected (and possibly provide getters/setters).
So if it's public, I suggest making it private and adding a getter and a setter. Then set a breakpoint at the setter and keep running the application, checking every time until you see the setter called on an object that has been deallocated.

A: I have found the problem after few weeks. There was a raw pointer to an object that was shared between 2 threads. You can't tell which thread finishes with it first so that is a problem who is responsible for the delete. One of them deleted the pointer and the other was still using it and set something to zero (hence the 4 bytes of zero that I saw on a deleted memory).
The solution was to use std::shared_ptr instead of a raw pointer with new and delete.
shared_ptr are thread safe.


text:
Q: Beautifulsoup class not contain multiple 'strings' Is there a way to scrape p tags that do not contain multiple classes? Here's my code so far (after compiling codes and researching StackOverflow):
import requests
import bs4
import re
url = 'https://www.sp2.upenn.edu/person/amy-hillier/'
req = requests.get(url).text
soup = bs4.BeautifulSoup(req,'html.parser')

regex = re.compile('^((?!Header|header|button|Root|root|logo|Title|title|Foot|foot|Publish|Story|story|Stories|stories|Link|link|color|space|email|address|download|capital).)*$')

for texts in soup.find_all('div'):
   for i in texts.findAll('p',{'class': regex}):
      print(i)

So my thought process is that I've created a regex to list strings that if exist, then the web scraper will not scrape the paragraph. To put it simply, if any of these words pop up on the class section, then don't scrape them.
Someone also recommend me to use a css selector syntax with :not() pseudo class and * contains operator, which I interpreted as:
for texts in soup.find_all('div'):
   for i in texts.select('p[class]:not([class*="Header|header|button|Root|root|logo|Title|title|Foot|foot|Publish|Story|story|Stories|stories|Link|link|color|space|email|address|download|capital"])'):
      print(i)

Unfortunately, neither of them works. Any help is greatly appreciated!
Edit
Adding examples of text:

 The world needs leaders equipped with tools to make a difference. The School of Social Policy & Practice (SP2) will prepare you to become one of those leaders, as a policy maker, practitioner, educator, activist, and more.

 Amy Hillier (she/her/her) currently teaches introductory-level GIS (mapping) courses for SP2 and Urban Studies program and chairs the MSW racism course sequence. Her doctoral and post-doctoral research focused on historical mortgage redlining. For more than a decade, her research focused on links between the built environment and public health. During that time, her primary faculty position was with the Department of City & Regional Planning in the Weitzman School of Design. She moved to SP2 in 2017 in order to pursue new research interests relating to LGBTQ communities, particularly trans youth. She is the founding director of the LGBTQ Certificate.

 Dr. Sahingur joined Penn Dental Medicine in September 2019 as Associate Dean of Graduate Studies and Student Research, providing leadership, strategic vision, and oversight to support and expand the graduate studies and student research endeavors at the School. She will be overseeing the Summer Student Research Program for the summer of 2020. Originally from Istanbul, Turkey, she received her DDS from Istanbul University, Turkey, in 1994 and then moved to the U.S. for her postgraduate education. She completed all of her postgraduate training at State University of New York at Buffalo, receiving a Master of Science degree in Oral Sciences in 1999 and then a PhD in Oral Biology with a clinical certificate in Periodontics in 2004.

I need to scrape the second and third paragraphs. My logic is since the first paragraph's class has the word 'color' in it, I can exclude that. The rest of the words that I listed on the regex variable are pretty much the words that I have found and needed to be excluded across multiple URLs. I hope that clarifies my question.

A: Perhaps you can use custom function when searching for the right
 tags. For example:
from bs4 import BeautifulSoup

html_doc = """\

 The world needs leaders equipped with tools to make a difference. The School of Social Policy & Practice (SP2) will prepare you to become one of those leaders, as a policy maker, practitioner, educator, activist, and more.

 Amy Hillier (she/her/her) currently teaches introductory-level GIS (mapping) courses for SP2 and Urban Studies program and chairs the MSW racism course sequence. Her doctoral and post-doctoral research focused on historical mortgage redlining. For more than a decade, her research focused on links between the built environment and public health. During that time, her primary faculty position was with the Department of City & Regional Planning in the Weitzman School of Design. She moved to SP2 in 2017 in order to pursue new research interests relating to LGBTQ communities, particularly trans youth. She is the founding director of the LGBTQ Certificate.

 Dr. Sahingur joined Penn Dental Medicine in September 2019 as Associate Dean of Graduate Studies and Student Research, providing leadership, strategic vision, and oversight to support and expand the graduate studies and student research endeavors at the School. She will be overseeing the Summer Student Research Program for the summer of 2020. Originally from Istanbul, Turkey, she received her DDS from Istanbul University, Turkey, in 1994 and then moved to the U.S. for her postgraduate education. She completed all of her postgraduate training at State University of New York at Buffalo, receiving a Master of Science degree in Oral Sciences in 1999 and then a PhD in Oral Biology with a clinical certificate in Periodontics in 2004.

"""

soup = BeautifulSoup(html_doc, "html.parser")

words = ["color"]

for p in soup.find_all(
    lambda t: t.name == "p"
    and all(w not in c.lower() for c in t.get("class", []) for w in words)
):
    print(p)
    print("-" * 80)

Prints:

 Amy Hillier (she/her/her) currently teaches introductory-level GIS (mapping) courses for SP2 and Urban Studies program and chairs the MSW racism course sequence. Her doctoral and post-doctoral research focused on historical mortgage redlining. For more than a decade, her research focused on links between the built environment and public health. During that time, her primary faculty position was with the Department of City & Regional Planning in the Weitzman School of Design. She moved to SP2 in 2017 in order to pursue new research interests relating to LGBTQ communities, particularly trans youth. She is the founding director of the LGBTQ Certificate.

--------------------------------------------------------------------------------

 Dr. Sahingur joined Penn Dental Medicine in September 2019 as Associate Dean of Graduate Studies and Student Research, providing leadership, strategic vision, and oversight to support and expand the graduate studies and student research endeavors at the School. She will be overseeing the Summer Student Research Program for the summer of 2020. Originally from Istanbul, Turkey, she received her DDS from Istanbul University, Turkey, in 1994 and then moved to the U.S. for her postgraduate education. She completed all of her postgraduate training at State University of New York at Buffalo, receiving a Master of Science degree in Oral Sciences in 1999 and then a PhD in Oral Biology with a clinical certificate in Periodontics in 2004.

--------------------------------------------------------------------------------


text:
Q: Identification of IC used on LCD control board - top markings [logo] SiW SW50008 ABGL0004F 1745
I need help with identification of this IC. It is on an LCD control board.

A: Looks like a product of Silicon Works: https://www.siliconworks.co.kr/en/web/main. Maybe you can contact the customer service.


text:
Q: How to wrap the fortran write-statement I want to wrap the fortran write-statement in a custom subroutine or function which includes some additional debug-logic.
But I'm currently stuck with defining the prototype of the function/subroutine.
Is this possible? If yes, how?

A: The title of your question exhibits a misunderstanding, though the text suggests you know better.  Nevertheless, for the record, write is a Fortran statement, it is neither a subroutine nor a function.
I think you have a number of options.  One, which I have used occasionally, would be to write a function which returns a string.  Perhaps
function error_message(error)
    character(len=*), intent(in) :: error
    character(len=:), allocatable :: error_message
    error_message = 'ERROR: '//trim(error)
end function error_message

which you can then use like this
write(*,*) error_message('Oh s**t')

You could certainly write a subroutine or a function with side effects which include writing to an ouput channel, but if you adopt this approach you have to be careful to observe the rules for recursive i/o.
EDIT
after OP's comment.
If you want to switch off debug messages another option you have is to direct them to a null device or file, eg /dev/null on Linux or NUL on Windows.  Something like
integer, parameter :: debug_channel = 99
logical, parameter :: debugging = .false.
...
if (debugging) then
   open(debug_channel, file='NUL')
else
   open(debug_channel, file='debuglog'
end if

and then
write(debug_channel,*) 'message'

A: a relatively simple way to accomplish most of what you want is to simply put the if inline in front of every write that is subject to debug control:
    if(debug)write(..,..)..

where debug is a global logical value, or even:
    if(debugf(level))write(..,..)..

where the logical function debugf determines whether to write based on some argument.

A: In addition to the other answers, you may be able to avoid using if (debug) write... with derived type IO.
I say "may", as it is quite silly unless you already have a suitable structure, and compiler support is currently rare.
However, as an example, compiled with ifort 14.0.1:
module errormod

  type error_t
     character(len=:), allocatable :: message
   contains
     procedure write_error
     generic :: write(formatted) => write_error
  end type error_t

  logical debug_verbose

contains

  subroutine write_error(err, unit, iotype, v_list, iostat, iomsg)
    class(error_t), intent(in)  :: err
    integer, intent(in)  :: unit
    character(len=*), intent(in)  :: iotype
    integer, intent(in), dimension(:)  :: v_list
    integer, intent(out)  :: iostat
    character(len=*), intent(inout)  :: iomsg

    if (debug_verbose) then
       write(unit, '("Error: ", A)', iostat=iostat, iomsg=iomsg) err%message
    else
       write(unit, '()', advance='no')
    end if

  end subroutine write_error

end module errormod

program test

  use errormod

  implicit none

  type(error_t) error

  debug_verbose = .TRUE.
  error%message = "This error will be reported."
  write(*, '(dt)') error

  debug_verbose = .FALSE.
  error%message = "This error will not be reported."
  write(*, '(dt)') error

  debug_verbose = .TRUE.
  error%message = "This final error will also be reported."
  write(*, '(dt)') error

end program test

The first and third messages will appear, but not the second.


text:
Q: Hibernate Spatial 5 and MySQL 5.7 I'm using Hibernate Spatial 5.0.7 and MySQL 5.7.
I need to use MySQL ST_* precise spatial operators, in order to do that I apply MySQLSpatial56Dialect, however if I use this dialect the Geometry datatype isn't correctly retrieved from the database. This didn't happen while using a version of MySQL 5.6.
I'm missing something?

A: Best to create a bug ticket for this in the Hibernate ORM issue tracker. Be sure to provide a stack trace.


text:
Q: Ideas about how to prevent malicious code to go into production especially in case of SAAS environments As nowadays SAAS is becoming popular way of developing and deploying the applications, and I have just started working at a company providing SaaS solution for payment authorization services.
Since past few days, I have been thinking what would happen if some "unsatisfied / angry" developer write a malicious code (lets say deleting transaction table !)which would activate on some particular time (so that it would not be caught during testing process) and can create havoc for any time critical SAAS application. Any good SAAS offering comes with proper backup strategy and hence data restoration could be possible upto certain extent but it would seriously hamper the availibility of system and in turn the image with clients.
Sometimes I think this could be controlled through code reviews but I have seen that most of the times the code reviews are not done properly and such malicious logic can be camouflaged behind some complicated string manipulations.
So I am just boucing my thoughts to community for some good ideas, which could be implemented in development process to catch such malicious activities early on.
P.S. : Sometimes though I am unsatisfied / angry developer but would never do such unethical things being a coding lover.

A: You're trying to solve a human problem with technology
A better approach is to make sure that code reviews are carried out responsibly. Other developers will not want to have to bear the brunt of the original developers malicious code so will quickly flag these kind of problems. Any "complex string manipulation" behaviour would have to be explained in detail and should rapidly show up.
Done well, a code review is pleasurable for both the author of the code and the reviewer(s). All the usual technical bug finding and documentation style requirements can be done automatically (think Findbugs, PMD, CPD etc) leaving just the interesting design and implementation discussions to take place.


text:
Q: Multiplication of two integer gives wrong value (ATMEL ATmega32A) The data and Uart data is added here.I really can't understand what's the problem..I tried different kinda solutions as changing data types,values,prints...
I'm using ATmega32A which is programmed by USBasp.
Here is the code:
https://hastebin.com/soqexihoni.cs
Here is the UART Com. log:
https://hastebin.com/muwekuniva.hs
Another version I change the data type of the variables.
But only 'temp' variable changed.I could read it.But the problem still goes on..
" temp = (5*data*100)/1024; " doesn't give any logical result..
Thanks for every comment (y)

A: You have to be careful with the data types and how you write the code.
The code (5*data*100)/1024 performs the operation in integer and then, converts it in float because temp is float.
You could try something like:
temp = ((float)5 * (float)data * (float)100) / (float)1024;

It might be over the top to cast all variables, but that is the principle.


text:
Q: what's the meaning of the PREPEND status in paging3? I have seen the demo given in google github. But it just retuen with MediatorResult.Success(endOfPaginationReached = true)
while, if it change it to MediatorResult.Success(endOfPaginationReached = false),my code also runing sussessfully.
so, i want to know what's the detail meaning of PREPEND?
the reason why I ask this question is when meeting the network error in refresing,and there is nothing in my Room,the Paging3 won't given any tip.(Though I can solve it by add a error tip view in mainView,I think it is inelegant.)

A: PREPEND is for non-positional data sources that allow dropping pages. So if you are on page 5, you dropped page 3 and before, then you scroll up and the boundary will load page 3 that had previously been dropped. It allows you to reinitialize from the middle of a paging source, rather than be forced to be at the beginning (see initialKey parameter).


text:
Q: How do I type a superscript in a subtitle? Here is a minimal version of what I am trying to compile:
\documentclass{book}

\begin{document}

\title{La vie au XXI\textsuperscript{e} si\`ecle}

\subtitle{La vie au XXI\textsuperscript{e} si\`ecle}

\maketitle

\end{document}

The command I type is pdflatex mydocument.
The weird thing is that the title works exactly as expected, but the subtitle does not : \textsuperscript triggers the dreaded error message ! Undefined control sequence. Unfortunately, I do need a superscript in the subtitle. How to achieve this?
I am using pdflatex, version: TeX Live 2019/Debian.

A: As some of the comments have already pointed out, the basic book document class does not offer a macro called \subtitle.
A general observation: When working with the book document class, the basic LaTeX \title, \author, and \date commands may not be sufficiently rich/flexible for you, i.e., they may not let you generate an elaborate title page. If that's the case for your document, do look into using various LaTeX packages that provide lots of extra flexibility.
If you don't want to go that route and simply wish to insert the subtitle string in a font that's slightly smaller than that of the main title string, you may do so by employing the code, shown below, that generates the following screenshot.

\documentclass[french]{book}
\usepackage{babel}

\usepackage{iftex}
\ifpdftex
   \usepackage[T1]{fontenc}
   \usepackage{cfr-lm} % or: "\usepackage{lmodern}"
\else
   \usepackage{fontspec}
   \setmainfont{Latin Modern Roman}[Numbers=OldStyle]
\fi

\begin{document}
\frontmatter

% Default relative font size for argument of \title: "\LARGE"
\title{La vie au XXI\textsuperscript{e} siècle\\[1\baselineskip]
       \Large % or "\large" % switch to a smaller relative font size
       La vie au XXI\textsuperscript{e} siècle} % subtitle
\author{Moi}
\date{\today}
\maketitle

\clearpage
% remainder of document

\end{document}


text:
Q: Mapping JSON object with lodash I'm trying to map a JSON object using lodash.  I'm calling the json object as follows:
var json = (function() {
var json = null;
$.ajax({
    'async': false,
    'global': false,
    'url': "{% url 'api_temp_income_statement' asset_details.id %}",
    'datatype': "json",
    'success': function (data) {
        json = data;
    }
});
return json;

})
Which returns a JSON object that looks like this:
[{"model": "tempincomestatement",
  "pk": 3,
  "fields": {"income_period": "2016-01-31", "lease_income_collected": "994174.0000", "storage_income_collected": "236216.0000", "tax_income_collected": "131020.0000", "other_income_collected": "0.0000"}
},... ]

I'm trying to create a map that has an Income Period : remaining fields relationship, so
 "2016-01-31" : {"lease_income_collected" : "994174", ... }

Reading the docs, it doesn't really address how to go about this...How would I accomplish this?

A: use _.keyBy to transform array to object by key
_.chain(data)
    .map('fields')
    .keyBy('income_period')
    .mapValues(function(val) {
        return _.omit(val, 'income_period');
    })
    .value();

A: You can use Object.keys(), computed property name, Array.prototype.reduce()

var data = [{
  "model": "tempincomestatement",
  "pk": 3,
  "fields": {
    "income_period": "2016-01-31",
    "lease_income_collected": "994174.0000",
    "storage_income_collected": "236216.0000",
    "tax_income_collected": "131020.0000",
    "other_income_collected": "0.0000"
  }
}];

var [, ...fields] = Object.keys(data[0].fields);
var res = {
  [data[0].fields.income_period]: fields.reduce((obj, prop) =>
  (obj[prop] = data[0].fields[prop], obj), {})
};

console.log(res);

A: You may use _.map:

var json = [{"model": "tempincomestatement",
          "pk": 3,
          "fields": {"income_period": "2016-01-31", "lease_income_collected": "994174.0000", "storage_income_collected": "236216.0000", "tax_income_collected": "131020.0000", "other_income_collected": "0.0000"}
         }, {"model": "1",
             "pk": 3,
             "fields": {"income_period": "2016-01-31", "lease_income_collected": "994174.0000", "storage_income_collected": "236216.0000", "tax_income_collected": "131020.0000", "other_income_collected": "0.0000"}
            }, {"model": "1",
             "pk": 3,
             "fields": {"lease_income_collected": "994174.0000", "storage_income_collected": "236216.0000", "tax_income_collected": "131020.0000", "other_income_collected": "0.0000"}
            } ];
var result = _.map(json, function(obj) {
  if (obj.fields.income_period !== undefined) {
    var result = {};
    var eleName = obj.fields.income_period;
    delete obj.fields.income_period;
    result[eleName] = obj.fields;
    return result;
  }
});
result = _.filter(result, Boolean);

console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>


text:
Q: setting a variable in specific type in dictionary Ok guys i have a dictionary like so:
mControllerTypes = new Dictionary<Type, ControllerBase>()
{
    { Type.Follow, new ControllerFollowTap() },
    { Type.Guide, new ControllerGuide() },
    { Type.Poke, new ControllerPoke() },
    { Type.Swipe, new ControllerSwipe() }
};

My problem is  that i want to access and edit a specific variables in the derived types in the dictionary instance. Like lets say in the ControllerSwipe i have a specific variable named SwipeLength which i don't want to include in the base class but want to set it in the dicitionary instance.How can i achieve this?

A: ((ControllerSwipe)mControllerTypes[Type.Swipe]).SwipeLength = 5;


text:
Q: simplexlsxgen saving file as xlsxxlsx I found out about SimpleXLSXGen while trying to save an sql procedure to xlsx, after 3 months in deploy, it started duplicating the extension xlsx while saving my files.
They are now something as "activosfijosTue,30 Mar 021.xlsxxlsx", making them unreadable until I change it back to xlsx, could you help me with that?
my code is as follows
session_start();
    date_default_timezone_set("America/Chihuahua");
    include_once('db.php');
    include_once('Conexion1.php');
    require('SimpleXLSXGen.php');

    //stored procedure

        $titulos = array('nombre_producto'=> 'Marca', 'modelo'=>  'Modelo', 'codigo_producto'=>  'Serie', 'inventario'=> 'Inventario', 'Descripcion'=> 'Caseta', 'carril'=> 'Carril', 'resguardante'=> 'Resguardante', 'nombre_categoria'=> 'Descripcion', 'estado'=> 'Estatus');
        $prueba = array_merge($titulos);
        $final= array_merge($prueba, $valores);

        $arquivo = 'activosfijos'.gmdate("D,d M Y").'xlsx';

    $xlsx = SimpleXLSXGen::fromArray( $final );
    $xlsx->downloadAs($arquivo);


text:
Q: Javascript variable missing characters I am setting a javascript variable from ASP.net <%=HttpContext.Current.User.Identity.Name%>
var username = '<%=HttpContext.Current.User.Identity.Name%>';

outputs "domain sername"
Basically it takes out the backslash and first letter of the username.  Why is it removing those two characters?

A: What you're doing is actually stamping something like:
var username = 'domain\username';

The \u is being treated as an escape sequence in the JavaScript string.  Depending on what the usernames actually are, you'll see different results, from newlines, to tabs, to syntax errors.
You need to properly encode it on the server using something like HttpUtility.JavaScriptStringEncode:
var username = '<%=HttpUtility.JavaScriptStringEncode(HttpContext.Current.User.Identity.Name)%>';

A: In JS (any many other languages) \ is used in a string with a special role, called ESCAPE CHARACTER. You need to use \\ to get \ in a string, test it out in the console:
console.log("\");
console.log("\\");

It's how you form special characters like \n for line break etc..
I think these are all cases when you would use escape character in JS:
\'  single quote
\"  double quote
\\  backslash
\b  Backspace
\r  Carriage Return
\f  Form Feed
\t  Horizontal Tabulator
\v  Vertical Tabulator

Long story short, JS thinks \character is one symbol (and not \ and character after it) in the string,\\ would represent \.


text:
Q: Prepare запрос возвращает не верный результат Есть простой запрос, который работает, но если ввести ', то он не сработает, чтобы этого не было пытался сделать prepare запрос, но он в результате выдаёт 0, хотя это не так и входит в условие. Как это исправить? Я пытался и через fetchColumn(), и через $empty = $query->rowCount() === 0;
var_dump($empty); if ($empty), но они оба не сработали
Рабочий запрос(действительно есть такой пользователь и в if не заходит)
$checkPoluch = mysqli_query($db, "SELECT * FROM users WHERE login = '$namePol'");
      $empty = mysqli_num_rows($checkPoluch);
      if ($empty == 0) {
        echo "Ошибка!";
        exit("");
      }

Через prepare (В if заходит, даже если есть такой логин)
$checkPoluch = "SELECT * FROM users WHERE login = ?";
  $query = $db->prepare($checkPoluch);
  $query->bind_param("s", $namePol);
  $query->execute();
  $empty = $query->num_rows;
  if ($empty == 0) {
    echo "Ошибка!";
    exit("");
  }

A: Как оказалось, необходимо было получить результат перед подсчётом строк. После редактирования, код сработал и выдал нужный результат:
$checkPoluch = "SELECT login FROM users WHERE login = ?";
$query = $db->prepare($checkPoluch);
$query->bind_param("s", $namePol);
$query->execute();

$query->store_result();
$query->bind_result($check);
$query->fetch();

$empty = $query->num_rows();

if ($empty == 0) {
  echo "Ошибка!";
  exit("");
}else{
  echo "Сработало!";
  exit("");
}


text:
Q: Simple program in c guessing word i am writing a word guess program in c, and i am having a problem in my code below while running it.
the code works for some cases but for other cases it doesn't. If the two words differ, it responds with a message containing a "/" for the characters
correct in correct position, a "+" for correct characters in position
errata, and a '*' for incorrect characters as they are not present in the word
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 40

int main(int argc, char *argv[])
 {

     int i,j,flag=0,k=0, N=5;
    char  par[5],cod[5], sol[5], sol2[5];

        printf("insert the segret word: ");
        scanf("%s[^n]",par);
        getchar();
        /*for(i=0; i<5; i++){
          if(par[i]==cod[i])
             k++;
        }*/

    while(flag==0){
        k=0;
        printf("INSERT WORD: ");
        scanf("%s[^n]",cod);
         getchar();
        for(i=0; i<5; i++){
          if(par[i]==cod[i])
             k++;
        }
        //printf("%d",k);
        if(k==4){
         printf("WINNER ....");
        flag=1;
        //printf("%d",flag);
        }

       else{
            for(i=0; i<5; i++){
              for(j=0; j<5; j++){
              /*if(i=0 && j==0 )
                printf("vollllll");*/
                  //sol[0]='/';*/
                if(par[i]==cod[j] && i==j){
                  sol[i]='/';
                  //sol2[i]= '/';
                  if(sol[i]=='*' || sol[i]=='+'){
                        sol[i]=' ';
                        sol[i]='/';
                    }
                }
                else if(par[i]==cod[j] && i!=j){
                    sol[j]== '+';
                    //sol2[j]== '+';
                    if(sol[j]=='*'){
                        sol[j]=' ';
                        sol[j]='+';
                    }
                }
                else if(i==j && par[i]!=cod[j]){
                //sol[j]==' ')
                    sol[i]= '*';
              }
            }
            }

            for(i=0;i<5;i++)
            printf("%c",sol[i]);
            printf("\n");
        }
    }
 return 0;
}

compliation error--> insert the secret word : amore
                     insert word: astio
                     /**** while its should display /***+


text:
Q: iTextSharp - PDF Bookmark not pointing to a page I have built a tree view to show the bookmarks of a given PDF document.
Using iTextSharp I get the bookmarks in a List object and use the Title value to show on the tree view, no problem.
The problem comes when I want the tree view node to reference a page number in the PDF document.
Some PDF documents have a value for Title, Page and Action for example:
Title: "Title Page",
Page: "1 XYZ -3 845 1.0",
Action: "GoTo"
However, others are in this format:
Title: "Title Page",
Named: "G1.1009819",
Action: "GoTo"
I have no idea what to do this the "Named" value. I have tried going through all the links in the document and comparing the value to the destination value of the link, but with no luck.
Does anyone know what this "Named" property represents?

A: It's a named destination, see the keyword list for some examples. It is a very common way to mark destinations in a document.
What do you want to do with the named destinations?
Do you want to consolidateNamedDestinations() so that they are no longer named destinations, but links to the specific place in the document.
Or do you want to create a link to a named destination? (That's probably more work. I don't think there are examples at hand.)
If you browse the examples, you'll discover the LinkActions where we use the SimpleNamedDestination object to retrieve the named destinations almost the same way you retrieve bookmarks using the SimpleBookmark class.
This code snippet gives us the bookmarks in the form of an XML file:
public void createXml(String src, String dest) throws IOException {
    PdfReader reader = new PdfReader(src);
    HashMap<String,String> map = SimpleNamedDestination.getNamedDestination(reader, false);
    SimpleNamedDestination.exportToXML(map, new FileOutputStream(dest),
            "ISO8859-1", true);
    reader.close();
}

See destinations.xml for the result.
The code is much easier because the structure isn't nested: each name corresponds with a single destination.


text:
Q: Better way to list subcategories instead of products I'm still learning Magento, I want to list subcategories instead of products, and I've done it, but I'm wondering if i've done it in the best way that can be done, and if I can move the logic from phtml to another file.
First I created a phtml file
<?php
    function getCurrentChildCategories()
    {
        $layer = Mage::getSingleton('catalog/layer');
        $category   = Mage::registry('current_category');
        /* @var $category Mage_Catalog_Model_Category */
        $collection = Mage::getModel('catalog/category')->getCollection();
        /* @var $collection
           Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
        $collection->addAttributeToSelect('url_key')
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('is_anchor')
            ->addAttributeToSelect('image')
            ->addAttributeToSelect('show_on_summary')
            ->addAttributeToFilter('is_active', 1)
            ->addAttributeToFilter('show_on_summary', 1)
            ->addIdFilter($category->getChildren())
            ->setOrder('position', 'ASC')
            ->joinUrlRewrite()
            ->load();

        $productCollection = Mage::getResourceModel('catalog/product_collection');
        $layer->prepareProductCollection($productCollection);
        $productCollection->addCountToCategories($collection);
        return $collection;
    }

    $_columnCount = 4;

?>

    <?php echo $this->getToolbarHtml() ?>
    <ul class="products-grid products-grid--max-<?php echo $_columnCount; ?>-col">
        <?php
            $_categories= getCurrentChildCategories();
            $count = $_categories->count();
            if($count):
                $i=0; foreach ($_categories as $_category):
                if($_category->getIsActive() && $_category->getShowOnSummary()):
                    $cur_category=Mage::getModel('catalog/category')->load($_category->getId());
                    $layer = Mage::getSingleton('catalog/layer');
                    $layer->setCurrentCategory($cur_category);
                    $catName = Mage::registry('current_category')->getName();
         ?>
                    <li class="item <?php if($i == 0): ?> first<?php elseif($i == $_columnCount-1): ?> last<?php endif; ?>">
                        <a href="<?php echo $_category->getURL() ?>" title="<?php echo $this->htmlEscape($_category->getName()) ?>">
                            <img src="<?php echo $_category->getImageUrl() ?>" width="100" alt="<?php echo $this->htmlEscape($_category->getName()) ?>" />

<?php echo $this->htmlEscape($_category->getName()) ?>

            <?php
            endif;
            if ($i == $_columnCount)
            {
                $i = 0;
            } else
            {
                $i++;
            }
        endforeach;
    else: ?>

<?php echo $this->__('There are no products matching the selection.') ?>

    <?
    endif;
    ?>

Second I created a static block in admin-menu->CMS->static block
{{block type="core/template" template="mycompany/mymodule/categories.phtml"}}

Third I went to admin-menu->Catalog->Manage-Categories->selected-category->Display-Settings and changed the display mode from products only to static block only and the I select the CMS Block that I just created.
Doing this I see the subcategories with pictures listed instead of products, but I think there is so much logic in the phtml file, I'm wondering if it's posible to move it to another place.
When I developed my own modules I moved this logic into the php files inside the block folder, and when I want to render any of them I call the block like this
<block type="mycompany_mymodule/topcategories" name="topcategories" template="mycompany/mymodule/topcategories.phtml" />

The type is where the php block file is with the functions that I call from phtml.
But when I make a static block in the CMS admin menu, I can't make reference to my php block file with the logic in one of my modules (it do not works), I am forced to use a app/code/core/mage route like core/template, and obviously my functions with my logic aren't there. And I shoudn't touch the core files with my own code.
Is there any way to move the logic from the phtml to another place in this case? Is there a better way to list the subcategories instead of products?
Thanks ;)

A: I found an easy and fast solution to use my own custom blocks from my modules in the CMS static blocks. It seems that they have to be whitelisted.
In the admin panel, you have to go to System->Permissions->Blocks and there click on + add new block, now you only have to write the route of you custom block (for example mycompany_mymodule/topcategories) and set the status to allowed.
Now you can call your templates with that custom blocks containing your own logic. And the views (phtml) will be free of logic.
{{block type="mycompany_mymodule/topcategories" name="topcategories" template="mycompany/mymodule/topcategories.phtml" }}


text:
Q: Time Complexity of Doubly Linked List Element Removal? A lot of what I'm reading says that removing an internal element in a doubly linked list (DLL) is O(1); but why is this the case?
I understand why it's O(n) for SLLs; traverse the list O(n) and remove O(1) but don't you still need to traverse the list in a DLL to find the element?

A: As it's stated where your link points to:

The cost for changing an internal element is based on already having a pointer to it, if you need to find the element first, the cost for retrieving the element is also taken.

So, for both DLL and SLL linear search is O(n), and removal via pointer is O(1).

A: The complexity of removal in DLL is O(1).
It can also be O(1) in SLL if provided pointer to preceding element and not to the element itself.
This complexity is assuming you know where the element is.
I.e. the operation signature is akin to remove_element(list* l, link* e)
Searching for the element is O(n) in both cases.

A: @Matuku: You are correct.
I humbly disagree with most answers here trying to justify how delete operation for DLL is O(1). It's not.
Let me explain.
Why are we considering the scenario that we 'would' have the pointer to the node that is being deleted? LinkedLists (Singly/Doubly) are traversed linearly, that's their definition. They have pointers only to the head/tail. How can we suddenly have a pointer to some node in between? That defeats the purpose of this data structure. And going by that assumption, if I have a DLL list of say 1 million nodes, then do I also have to maintain 1 million pointers (let's call them access pointers) pointing to each of those nodes so that I can delete them in O(1)? So how would I store those 1 millions access pointers? And how do I know which access pointer points to the correct data/node that I want to delete?
Can we have a real world example where we 'have' the pointer to the data that has to be deleted 100% of the time?
And if you know the exact location/pointer/reference of/to the node to be deleted, why to even use a LinkedList? Just use array! That's what arrays are for - direct access to what you want!
By assuming that you have direct access to any node you want in DLL is going against the whole idea of LinkedList as a conceptual Data Structure. So I agree with OP, he's correct. I will stick with this - Doubly LinkedLists cannot have O(1) for deleting any node. You still need to start either from head or tail, which brings it down to O(n).
" If " we have the pointer to the node to be deleted say X, then of course it's O(1) because we have pointers to the next and prev node we can delete X. But that big if is imaginary, not real.
We cannot play with the definition of the sacred Data Structure called LinkedLists for some weird assumptions we may have from time to time.

A: For a doubly linked list, it's constant time to remove an element once you know where it is.
For a singly linked list, it's constant time to remove an element once you know where it and its predecessor are.
Since that link you point to shows a singly linked list removal as O(n) and a doubly linked one as O(1), it's certain that's once you already know where the element is that you want to remove, but not anything else.
In that case, for a doubly linked list, you can just use the prev and next pointers to remove it, giving you O(1). Ignoring the edge cases where you're at the head or tail, that means something like:
corpse->prev->next = corpse->next
corpse->next->prev = corpse->prev
free (corpse)

However, in a singly linked list where you only know the node you want deleted, you can't use corpse->prev to get the one preceding it because there is no prev link.
You have to instead find the previous item by traversing the list from the head, looking for one which has a next of the element you want to remove. That will take O(n), after which it's once again O(1) for the actual removal, such as (again, ignoring the edge cases for simplicity):
lefty = head
while lefty->next != corpse:
    lefty = lefty-> next
lefty->next = corpse->next
free (corpse)

That's why the two complexities are different in that article.

As an aside, there are optimisations in a singly-linked list which can make the deletion O(n) (the deletion being effectively O(1) once you've found the item you want to delete, and the previous item). In code terms, that goes something like:
# Delete a node, returns true if found, otherwise false.

def deleteItem(key):
    # Special cases (empty list and deleting head).

    if head == null: return false
    if head.data == key:
        curr = head
        head = head.next
        free curr
        return true

    # Search non-head part of list (so prev always exists).

    prev = head
    curr = head.next
    while curr != null:
        if curr.data == key:
            # Found it so delete (using prev).

            prev.next = curr.next
            free curr
            return true

        # Advance to next item.

        prev = curr
        curr = curr.next

    # Not found, so fail.

    return false


text:
Q: GroupBox control in UWP? Getting acquainted with UWP. I'm developing an App for simulating electric circuits. There is a classic visual control called Frame, later called GroupBox in WPF.
It seems this control is absent in UWP.
There is a control called HeaderedContentControl in UWP.Toolkit library, but doesn't look the same. And seems the background and border properties don't work..
currently my code is:
  <controls:HeaderedContentControl Margin="5"
                                         BorderBrush="Black" BorderThickness="1"
                                         HorizontalAlignment="Stretch"
                                         HorizontalContentAlignment="Stretch">
            <controls:HeaderedContentControl.Header>
                <Border BorderBrush="Black" BorderThickness="1">
                    <Border.RenderTransform>
                        <TranslateTransform Y="-10"/>
                    </Border.RenderTransform>
                    <TextBlock Text="Resistor Value"/>
                </Border>
            </controls:HeaderedContentControl.Header>

            <local:ComponentValueBox Unit="Ohm" HorizontalAlignment="Left"
                                     Value="{x:Bind resistorValue, Mode=TwoWay}"
                                     ValueChanged="changeR"/>

        </controls:HeaderedContentControl>

And what I see (in the flyout) is:

Not quite like the GroupBox control..
What I would like to see is something like following:

What Should I do?

A: UWP is different from WPF. UWP is based on windows runtime, WPF is based on .NET Framework. They all use XAML to layout UI elments, but they have different XAML rendering engine. You could not think that MS dropped the old classic control. They're totally on the different platform. We call 'UWP' as Unversal Windows Platform. For now, you're not able to find such a 'GroupBox', but it's a new platform, you might be able to see such a control in the future. Anything is possible.
For your requirement, like @Muzib said, you entirely could make a custom control to meet your requirement. I used UserControl TextBlock Border ContentControl to make such a 'GroupBox' for your reference.
Please see my following code sample:
<UserControl
x:Class="AppGroupBox.GroupBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppGroupBox"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">

<Grid>
    <TextBlock x:Name="HeaderTitle" Text="Header" Margin="7 0 0 0" LayoutUpdated="HeaderTitle_LayoutUpdated"></TextBlock>
    <Border BorderBrush="Black" x:Name="border" BorderThickness="0 2 0 0" Margin="100 10 3 3" CornerRadius="0 5 0 0"></Border>
    <Border BorderBrush="Black" BorderThickness="2 0 2 2" Margin="3 10 3 3" CornerRadius="5">
        <ContentControl x:Name="Content" Margin="10 10 10 10">
        </ContentControl>
    </Border>
</Grid>

public sealed partial class GroupBox : UserControl
{
    public GroupBox()
    {
        this.InitializeComponent();
    }

    public string Header
    {
        get { return (string)GetValue(HeaderProperty); }
        set { SetValue(HeaderProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Header.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty HeaderProperty =
        DependencyProperty.Register("Header", typeof(string), typeof(GroupBox), new PropertyMetadata("Your Header", HeaderPropertyChangedCallback));

    public static void HeaderPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue != e.OldValue)
        {
            (d as GroupBox).HeaderTitle.Text = e.NewValue?.ToString();
            //(d as GroupBox).border.Margin = new Thickness((d as GroupBox).HeaderTitle.ActualWidth, 10, 3, 3);
        }
    }

    public object CustomContent
    {
        get { return (object)GetValue(CustomContentProperty); }
        set { SetValue(CustomContentProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Content.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CustomContentProperty =
        DependencyProperty.Register("CustomContent", typeof(object), typeof(GroupBox), new PropertyMetadata(null,PropertyChangedCallback));

    public static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue != e.OldValue)
        {
            (d as GroupBox).Content.Content = e.NewValue;
        }
    }

    private void HeaderTitle_LayoutUpdated(object sender, object e)
    {
        border.Margin = new Thickness(HeaderTitle.ActualWidth+10,10,3,3);
    }
}

<local:GroupBox Header="My GroupBox" Height="300" Width="500">
        <local:GroupBox.CustomContent>
            <StackPanel>
                <RadioButton Content="r1"></RadioButton>
                <TextBox></TextBox>
            </StackPanel>
        </local:GroupBox.CustomContent>
</local:GroupBox>

A: I don't think there's such controls in UWP. Most probably you have to make your own CustomControl to achieve something that looks exactly lik that in UWP.
But hey, you can achieve something like that with a 'customized' ListView. Look at this:
<ListView Header="I am a header" BorderThickness="1" BorderBrush="Red" Width="250" Height="200" SelectionMode="None">
    <ListView.HeaderTemplate>
        <DataTemplate>
            <ListViewHeaderItem Content="{Binding}"/>
        </DataTemplate>
    </ListView.HeaderTemplate>
    <RadioButton>Any Value</RadioButton>
    <RadioButton>1% standard?</RadioButton>
    <RadioButton>5% standard</RadioButton>
</ListView>

It produces this output:

Of course You can make these items more dense if you want so.


text:
Q: Triangular borders Hello i  would like to style the borders of my list element so that the border-top-right and the border-bottom-right meet in a triangular shape with only css.
like so:

or like so:
I want to achieve both of these two shapes using css alone, to maybe alter the borders to that shape, i would like to know if that is possible and how i can go about it.  The element in question is a list element.

A: If you're after that specific shape, you can use the :before and :after pseudo elements
Demo Fiddle (second shape)
HTML

CSS
div {
    display:inline-block;
    position:relative;
    height:30px;
    width:50px;
    background:Red;
}
div:before, div:after {
    content:'';
    position:absolute;
    display:inline-block;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 15px 0 15px 26.0px;
}
div:after {
    border-color: transparent transparent transparent red;
    right:-26px;
}
div:before {
    border-color: transparent transparent transparent white;
}

A: DEMO
div {
  background: #EF3E36;
  margin: 10px;
}
.arrow1 {
  position: relative;
  left: 50px;
  width: 250px; height: 100px;
}
.arrow1:before {
  display: block;
  content: "";
  width: 0;
  height: 0;
  position: absolute;
  left: -50px;
  border: 50px solid #EF3E36;
  border-left: 50px solid transparent;
  border-right: 0;
}
.arrow1:after {
  display: block;
  content: "";
  background: transparent;
  width: 0;
  height: 0;
  position: absolute;
  left: 250px;
  border: 50px solid transparent;
  border-left: 50px solid #EF3E36;
}
.arrow2 {
  position: relative;
  width: 300px; height: 100px;
}
.arrow2:after {
  display: block;
  content: "";
  background: transparent;
  width: 0;
  height: 0;
  position: absolute;
  left: 300px;
  border: 50px solid transparent;
  border-left: 50px solid #EF3E36;
}

A: code for your shapes:-
#breadcrumbs-two{
  overflow: hidden;
  width: 100%;
}

#breadcrumbs-two li{
  float: left;
  margin: 0 .5em 0 1em;
}

#breadcrumbs-two a{
  background: #ddd;
  padding: .7em 1em;
  float: left;
  text-decoration: none;
  color: #444;
  text-shadow: 0 1px 0 rgba(255,255,255,.5);
  position: relative;
}

#breadcrumbs-two a:hover{
  background: #99db76;
}

#breadcrumbs-two a::before{
  content: "";
  position: absolute;
  top: 50%;
  margin-top: -1.5em;
  border-width: 1.5em 0 1.5em 1em;
  border-style: solid;
  border-color: #ddd #ddd #ddd transparent;
  left: -1em;
}

#breadcrumbs-two a:hover::before{
  border-color: #99db76 #99db76 #99db76 transparent;
}

#breadcrumbs-two a::after{
  content: "";
  position: absolute;
  top: 50%;
  margin-top: -1.5em;
  border-top: 1.5em solid transparent;
  border-bottom: 1.5em solid transparent;
  border-left: 1em solid #ddd;
  right: -1em;
}

#breadcrumbs-two a:hover::after{
  border-left-color: #99db76;
}

#breadcrumbs-two .current,
#breadcrumbs-two .current:hover{
  font-weight: bold;
  background: none;
}

#breadcrumbs-two .current::after,
#breadcrumbs-two .current::before{
  content: normal;
}


text:
Q: Trouble with the program razercfg (make) CHECK BELOW FOR UPDATE
The installation process begins to fail on the make step, with some of the contents stating they have built successfully followed by a long error at the end.
I've already attempted all solutions to this problem shown here: checkinstall / make does not work for the program razercfg that I wish to install.
Here's my console output for cmake . and make:
anonymous@anonymous-AB350M-DS3H:~/razer$ cmake .
-- The C compiler identification is GNU 7.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
CMake Deprecation Warning at CMakeLists.txt:9 (cmake_policy):
  The OLD behavior for policy CMP0005 will be removed from a future version
  of CMake.

  The cmake-policies(7) manual explains that the OLD behaviors of all
  policies are deprecated and that a policy should be set to OLD only under
  specific short-term circumstances.  Projects should be ported to the NEW
  behavior and not rely on setting a policy to OLD.

-- Check if the system is big endian
-- Searching 16 bit integer
-- Looking for sys/types.h
-- Looking for sys/types.h - found
-- Looking for stdint.h
-- Looking for stdint.h - found
-- Looking for stddef.h
-- Looking for stddef.h - found
-- Check size of unsigned short
-- Check size of unsigned short - done
-- Using unsigned short
-- Check if the system is big endian - little endian
-- Looking for libusb.h
-- Looking for libusb.h - found
-- Configuring done
-- Generating done
-- Build files have been written to: /home/anonymous/razer
anonymous@anonymous-AB350M-DS3H:~/razer$ make
Scanning dependencies of target razer
[  4%] Building C object librazer/CMakeFiles/razer.dir/buttonmapping.o
[  8%] Building C object librazer/CMakeFiles/razer.dir/profile_emulation.o
[ 12%] Building C object librazer/CMakeFiles/razer.dir/librazer.o
[ 16%] Building C object librazer/CMakeFiles/razer.dir/config.o
[ 20%] Building C object librazer/CMakeFiles/razer.dir/util.o
[ 25%] Building C object librazer/CMakeFiles/razer.dir/synapse.o
[ 29%] Building C object librazer/CMakeFiles/razer.dir/cypress_bootloader.o
[ 33%] Building C object librazer/CMakeFiles/razer.dir/hw_boomslangce.o
[ 37%] Building C object librazer/CMakeFiles/razer.dir/hw_copperhead.o
[ 41%] Building C object librazer/CMakeFiles/razer.dir/hw_deathadder.o
[ 45%] Building C object librazer/CMakeFiles/razer.dir/hw_deathadder2013.o
[ 50%] Building C object librazer/CMakeFiles/razer.dir/hw_deathadder_chroma.o
[ 54%] Building C object librazer/CMakeFiles/razer.dir/hw_krait.o
[ 58%] Building C object librazer/CMakeFiles/razer.dir/hw_lachesis.o
[ 62%] Building C object librazer/CMakeFiles/razer.dir/hw_lachesis5k6.o
[ 66%] Building C object librazer/CMakeFiles/razer.dir/hw_naga.o
[ 70%] Building C object librazer/CMakeFiles/razer.dir/hw_imperator.o
[ 75%] Building C object librazer/CMakeFiles/razer.dir/hw_taipan.o
[ 79%] Building C object librazer/CMakeFiles/razer.dir/hw_mamba_tournament_edition.o
[ 83%] Building C object librazer/CMakeFiles/razer.dir/hw_diamondback_chroma.o
[ 87%] Linking C shared library librazer.so
[ 87%] Built target razer
Scanning dependencies of target razerd
[ 91%] Building C object razerd/CMakeFiles/razerd.dir/razerd.o
[ 95%] Linking C executable razerd
[ 95%] Built target razerd
Scanning dependencies of target pyrazer
[100%] Generating build/stamp
Traceback (most recent call last):
  File "/home/anonymous/razer/ui/setup.py", line 3, in <module>
    from distutils.core import setup
ModuleNotFoundError: No module named 'distutils.core'
ui/CMakeFiles/pyrazer.dir/build.make:61: recipe for target 'ui/build/stamp' failed
make[2]: *** [ui/build/stamp] Error 1
CMakeFiles/Makefile2:195: recipe for target 'ui/CMakeFiles/pyrazer.dir/all' failed
make[1]: *** [ui/CMakeFiles/pyrazer.dir/all] Error 2
Makefile:129: recipe for target 'all' failed
make: *** [all] Error 2

UPDATE
Thanks to the first comment, I installed python3-distutils and the program successfully goes through the make command. However, the installation instructions require a use of the command "make install" to finalize its installation, which unfortunately produces a new error.
anonymous@anonymous-AB350M-DS3H:~/razer$ make install
[ 87%] Built target razer
[ 95%] Built target razerd
[100%] Built target pyrazer
Install the project...
-- Install configuration: ""
-- Installing: /lib/udev/rules.d/80-razer.rules
CMake Error at cmake_install.cmake:49 (file):
  file INSTALL cannot copy file "/home/anonymous/razer/udev.rules" to
  "/lib/udev/rules.d/80-razer.rules".

Makefile:73: recipe for target 'install' failed
make: *** [install] Error 1


text:
Q: how to locate an recently opened pdf file and save it in a target folder using excel vba I want to locate an recently opened pdf file and save it in a target folder, right now i can able to locate the pdf file using its name and close it but i want to use Save As function.
Code tried to Locate and close the PDF
Option Explicit
Private Declare Function FindWindow Lib "user32" _
    Alias "FindWindowA" (ByVal lpClassName As String, _
    ByVal lpWindowName As String) As Long
Private Declare Function PostMessage Lib "user32" _
    Alias "PostMessageA" (ByVal hwnd As Long, _
    ByVal wMsg As Long, ByVal wParam As Long, _
    ByVal lParam As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" _
    (ByVal dwDesiredAccess As Long, _
    ByVal bInheritHandle As Long, _
    ByVal dwProcessId As Long) As Long
Private Declare Function GetWindowThreadProcessId _
    Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetWindowText Lib "user32" _
    Alias "GetWindowTextA" (ByVal hwnd As Long, _
    ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, _
    ByVal wCmd As Long) As Long

Const GW_HWNDNEXT = 2
Const WM_CLOSE = &H10
Const SYNCHRONIZE = &H100000
Public Sub Test()
    Dim hWindow As Long
    Dim hProcess As Long
    Dim lProcessId As Long
    Dim lngReturnValue As Long

    hWindow = SearchHndByWndName_Parent("vieworder.pdf.php")
    hProcess = OpenProcess(SYNCHRONIZE, 0&, lProcessId)
    lngReturnValue = PostMessage(hWindow, WM_CLOSE, 0&, 0&)
End Sub
Private Function SearchHndByWndName_Parent(strSearch As String) As Long
    Dim strTMP As String * 100
    Dim nhWnd As Long
    nhWnd = FindWindow(vbNullString, vbNullString)
    Do While Not nhWnd = 0
        If GetParent(nhWnd) = 0 Then
            GetWindowText nhWnd, strTMP, 100
            If InStr(strTMP, strSearch) > 0 Then
                SearchHndByWndName_Parent = nhWnd
                Exit Do
            End If
        End If
        nhWnd = GetWindow(nhWnd, GW_HWNDNEXT)

    Loop
End Function

I am working in a restricted environment so I cant add any Adobe dll as reference, also the file which i am looking for is not yet saved in any folder.
Please share your suggestions.
Thank You


text:
Q: Transmission Line open and short analysis I have a transmission line with the following given parameters:
Characteristic impedance at 50 ohms, phase as measured using VNA or PNA and frequency. (I can get S parameters as well) Other information such as physical length are available as well.
The components that were measured were a transmission line very similar to a short coax, and a line very similar to an open coax.
How can I derive the Capacitance from the open circuit line and the inductance of the short circuit line? How is phase shift related to these values.

A:
How can I derive the Capacitance from the open circuit line and the
  inductance of the short circuit line? How is phase shift related to
  these values.

A short open circuit line can be used to measure the capacitance per metre but you need to do it at a low enough frequency so that the inductance isn't starting to affect readings. Because the line is open circuit and you are using low frequencies, small volt drops due to inductance are minimized. I'm also assuming the the parallel conductance of the line is negligible.
You can measure line capacitance by measuring the impedance the short open-line presents to a voltage source - this is largely Xc if you ensure the frequency is relatively low i.e. 1 kHz for example.
You could then do a short circuit test and calculate inductance but, if you already know the characteristic impedance of the t-line then you can use the following formula: -
\$Z_0 = \sqrt{\frac{L}{C}}\$
You have measured C and you know Z0 so L is calculated.

How is phase shift related to these values

I assume you mean the phase difference between input and output. This is determined by the velocity of propagation of the cable. As a percentage of the speed of light it is: -
Velocity factor = \$\dfrac{1}{c_0\sqrt{LC}}\$
So, if your short cable is 1 metre long and VF = 50% then it will take 6.667 ns for a signal to reach the end. This means that if you stimulus frequency is a sinewave of 75 MHz (period = 13.333 ns), it will undergo a phase shift of 180 degrees on that 1 metre length of cable.


text:
Q: Will Git tell you if you are behind your remote repo? When working in a repo, Git will display a message when calling git status that your ahead of origin/branchName by x amount of commits. But if the remote repository was updated for example, by someone else on another computer and they push, so I am actually behind the remote repository. Will calling git status notify me of this?

A: git fetch followed by git status will tell you if are behind on your current branch if it tracks a remote branch. Running git fetch won't touch any local refs, and you can use --dry-run if you are paranoid about what it will do.
This is possibly a duplicate of git ahead/behind info between master and branch?

A: You need to do git fetch that means pulling only information of the remote repository.


text:
Q: Azure REST API get resource parentResourcePath parameter Context
I am willing to get a resource details with the Azure REST API. And more particularly, I want to get the IAM associated with a resource.
Problem
So, I searched in the doc reference and found that endpoint: https://learn.microsoft.com/en-us/rest/api/resources/resources/get which provides an identity response attribute that meets my needs.
However, I can't find any information about the required path parameter parentResourcePath. What does that parameter mean and how can I get its value for a specific resource ?
Also, when I tried going through the resources group path, I can get a path to the resource details but without the parentResourcePath parameter, and the response doesn't include the identity attribute.
Finally, am I going the right way (using GET resource API) ? And if so, where can I find that parentResourcePath value ?

A: Actually, you have a better choice - Resources - Get By Id.
The /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName} in the api  Resources - Get named resourceId which used in the Resources - Get By Id.
But if you combinate the properties manually, it is not easy, Azure has many different resource providers, resourcetype.
Generally, you could find the resourceId in your resource in the portal -> Properties. Also, the response of this API will include the identity which you need.
Sample:
Get a web app resource.
The resourceId is like /subscriptions/xxxxxxx/resourceGroups/joywebapp/providers/Microsoft.Web/sites/joywebapp2.
You can click Try it in the doc to try the api.
Response:

A: Well I made it throught the Role assignment list for scope endpoint, giving the subscription/resourcegroup/resource in the scope. And the output contains a principalId attribute that seems to point to a user or group or service principal.
Ref: https://learn.microsoft.com/en-us/rest/api/authorization/roleassignments/listforscope


text:
Q: Getting garbage value at the end of some strings I scraped a website to get some mcqs for a c assignment. I wrote the data to a plaintext file separating every entry with null chars.
The pattern is:
Question with choices NULL Answer NULL Question...
Here is a sample of the file. the red dots are '\0' chars:

Here is a link to get the full file.
Code to read this file in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Question{
    char question[1000];
    char answer;
};

int main(){
struct Question questions[100];
FILE *fp;
char buffer[1000],choice;
int ch,i=0,c=1,k=0,score=0;
fp=fopen("quiz_questions.txt","r");
ch = 1;
  while (ch != EOF)
  {
    ch = getc(fp);
    buffer[i]=ch;
    i++;
    if(ch=='\0'){
    buffer[i]='\0';
    c++;
    i=0;
    continue;
    }
    if(c%2){ //question
    strcpy(questions[k].question,buffer);

    }
    else{ //answer
    questions[k].answer=buffer[0];
    k++;

    }
 }

for(i=0;i<35;i++){
printf("\nQuestion:\n%s\nAnswer: %c\n",questions[i].question,questions[i].answer);
}

return 0;
}

OUTPUT:

What am I missing? Help please. It seems the buffer isn't getting null terminated properly and is retaining chars from last assignment.
PS: Is there a better way to consume this data from c? Scraping done via python.
EDIT: I now realize writing a separate answerkey file would have been much better. Stupid me.

A:     strcpy(questions[k].question,buffer);

This statement is executed for every single character you read (if c is odd). At this point, buffer is not null terminated yet (and not a string).
ch = getc(fp);
buffer[i]=ch;

These two lines write to buffer[i] even if the end of file was reached. You only check for EOF after having processed it as if it were a normal character.
i++;
if(ch=='\0'){
buffer[i]='\0';

This is redundant. If ch is '\0', then you've just null terminated buffer in buffer[i]=ch;. There's no need to add another '\0'.

A: Modified version of your code to solve the problem:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Question{
    char question[1000];
    char answer;
};

int main()
{
    struct Question questions[100];
    FILE *fp;
    char buffer[1000],choice;
    int ch,i=0,c=0,k=0,score=0;    **<-- EDIT:change done here to initialize c = 0**

    fp=fopen("quiz_questions.txt","r");

    ch = 1;

    while (ch != EOF)
    {
        ch = getc(fp);
        buffer[i]=ch;
        i++;

        if(ch =='\0')
        {
            //buffer[i]='\0';  <-- Change done here, unnecessary assignment
            c++;
            i=0;

            if(c%2)            <-- Change done here, moved inside if (ch == '\0') case
            {
                //question
                strcpy(questions[k].question,buffer);
            }
            else
            {
                //answer
                questions[k].answer=buffer[0];
                k++;
            }
        }
    }

    for(i=0;i<35;i++)
    {
        printf("\nQuestion:\n%s\nAnswer: %c\n",questions[i].question,questions[i].answer);
    }

    return 0;
}


text:
Q: Use MATCH with concatenation I am using the following formula to match values from two columns:
=MATCH(C2,"000"&'Diversity Reports_12312013.xlsx'!snapshot[PERSONNEL_NUM],0)

but it is not working.
How might I match to another column but left pad three zeros to the value in that column?

A: According to OP:

@barryhoudini, your +0 did the trick, thanks!

@barry's 'trick' being:
 RIGHT(C2,LEN(C2)-3)+0

where "the +0 converts to a number".


text:
Q: Intermediate lattices $C\mathbb{Z}^n \subseteq \Lambda \subseteq \mathbb{Z}^n$ Let $C \in \mathfrak{gl}(\mathbb{Z},n)$ be a symmetric full rank integer valued matrix (in my case its the symmetric part of a Cartan matrix).. Let $\Lambda \subseteq  \mathbb{Z}^n$ be a full rank sublattice, s.t. $C\mathbb{Z}^n \subseteq\Lambda \subseteq  \mathbb{Z}^n$. One can think of $\Lambda$ as a lattice in between of a root lattice $\Lambda_R=C\mathbb{Z}^n$ and the co-weight lattice $\Lambda_W^\vee=\mathbb{Z}^n$. Question: Is there a symmetric matrix $C'$, s.t. $\Lambda=C'\mathbb{Z}^n$?

A: First of all, every full rank sublattice $\Lambda\subseteq \mathbb Z^n$ contains $\Lambda'=c\mathbb Z^n$ for some positive integer $c$. This $\Lambda'$ may serve as $C\mathbb Z^n$; so the question can in fact be reformulated as follows: Does every full rank sublattice $\Lambda\subseteq \mathbb Z^n$ have a symmetric base, i.e. a matrix $B=B^T$ with $\Lambda=B\mathbb Z^n$?
The answer seems to be yes, and, as Igor Rivin has suggested, the Smith normal form indeed helps. Let $\Lambda=A\mathbb Z^n$, and let $A=PDQ$ be the Smith decomposition of $A$, so $D$ is diagonal, and $P,Q\in SL(\mathbb Z,n)$. Then also $Q^{-1}P^T\in SL(\mathbb Z,n)$, and $B=AQ^{-1}P^T=PDP^T$ is a symmetric matrix satisfying $B\mathbb Z^n=AQ^{-1}P^T\mathbb Z^n=A\mathbb Z^n=\Lambda$.
(We did ot use the full rank condition; however, if $A$ is degenerate, then $B$ is degenerate as well, so surely it does not provide a base.)


text:
Q: how can I update google play services in eclipse My question is that I have an android application which developed in Eclipse. I need to update Google play services but i don't know how to do that.
May you help me please how to update ?

A: first of all download updated google play services and import into project.


text:
Q: Email Security: TLS and S/MIME My understanding is that TLS is an encryption technique that allowing two STMP servers to communicate with each other securely.  If HTTPS is used to connect to an STMP serve is that the same as using S/MIME?

A:
HTTPS is used to connect to an STMP

There seems to be a misunderstanding regarding what HTTPS and SMTP are. HTTP and SMTP are two distinct protocols. HTTPS is essentially HTTP over SSL/TLS, which secures the communication between the client and the server. Similarly, communications between an SMTP client and an SMTP server can be secured using SSL/TLS (there are two variants: SMTP over SSL/TLS directly, on a specific port, or TLS initiated via STARTTLS within the SMTP protocol; either way, HTTPS isn't used to connect to an SMTP server). In both cases, this is transport-level security.
In contrast, S/MIME is about message-level security, where the messages are encrypted (even when they've been received and are sitting in your inbox).
What can be relevant to both SSL/TLS (for HTTP, SMTP, ...) and S/MIME is the notion of certificates and PKI (Public Key Infrastructure), which is what helps make decision regarding the trust in the remote party, necessary for security.

A: No. TLS encrypts the communication channel. S/MIME encrypts the message. I.e., it's the difference between "talking openly on a secure line" and "talking in code on an insecure line."


text:
Q: What is the derivative of a squared variable matrix "wrapping around" a constant matrix? Sorry for the possibly poor choice of words describing the question. What i'm asking is how to find the derivative of:
$$ \frac{d(X^TA^TAX)}{dx} $$
Given that $X$ is a matrix of $M\times Q$ dimension and elements containing the variable $x$, and $A$ is of dimensions $N\times M$ containing only constants.
I know the answer is going to be
$$ A^2\cdot 2X $$ since $$\frac{d(X^TX)}{dx}=2X$$ And $A$ has to match the dimensions of $X$ for multiplication. But how is this derived?


text:
Q: htaccess rewrite stopped working after update I am using this code in my htaccess file, and I am confident that it is right, but it is not working on my new server. You can find my phpinfo file here: http://www.saint57records.com/test.php. I just updated my apache, so I don't know if it is something there. I have tried finding other information but I can't find any.
RewriteEngine On

RewriteCond %{REQUEST_URI} !^/artists/index.php.*
RewriteRule    ^artists/(.+)$    artists/index.php?artist=$1 [L]

A: Check httpd.conf or apache2.conf inside  , AllowOverride must be set to All
If you are using Ubuntu check this in /etc/apache2/apache2.conf
<Directory /your/directory>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>


text:
Q: Crashing application caused by ApiClientException in Api gateway I want to call webservice using Api gateway but having an issue using Cognito. but application is crashing, I have no idea about it,Please guys help to solve it!!! my code is like below
AwsActivity.java
class AwsActivity extends Activity {
private String AMAZON_COGNITO_IDENTITY_POOL_ID = "us-east-1**********";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new MyAsyncTask("1").execute();
    }

    private class MyAsyncTask extends AsyncTask<String, Void, String> {
        private String userId = "";

        public MyAsyncTask(String userId) {
            this.userId = userId;
            Log.d("111111111111", "111111111111");
        }

        @Override
        protected String doInBackground(String... strings) {
            Log.d("22222222222222222", "2222222222222222222");
            AWSCredentialsProvider credenetialsProvider = new CognitoCachingCredentialsProvider(
                    AwsActivity.this,          // activity context
                    AMAZON_COGNITO_IDENTITY_POOL_ID, // Cognito identity pool id
                    Regions.US_EAST_1 // region of Cognito identity pool
            );
            ApiClientFactory factory = new ApiClientFactory()
                    .credentialsProvider(credenetialsProvider)
                    .region("us-east-1")
                    .endpoint("https://abcd")
                    .apiKey("gsjddjflkjdsljaskds");

            // MyClient is the AWS Android SDK Generated class

            final MyClient client = factory.build(MyClient.class);

            client.viewprofileGet(userId);
            // String str = client.testGet().toString();
            Log.d("###", "here after test" + client.viewprofileGet(""));

            return "DONE";
        }

        @Override
        protected void onPostExecute(String temp) {
            Log.d("####", "onPostExecute");
        }
    }}

MyClient.java
@com.amazonaws.mobileconnectors.apigateway.annotation.Service(endpoint = "https://abcde")
public interface MyClient {
    @com.amazonaws.mobileconnectors.apigateway.annotation.Operation(path = "/loginclient", method = "GET")
    Empty loginclientGet(
            @com.amazonaws.mobileconnectors.apigateway.annotation.Parameter(name = "user_id", location = "query")
            String userId);
}

My Error Log is below
07-01 06:35:17.840 17476-17558/com.example.android.awsapidemo E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                                java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                                at android.os.AsyncTask$3.done(AsyncTask.java:299)
                                                                                at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
                                                                                at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:239)
                                                                                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
                                                                                at java.lang.Thread.run(Thread.java:841)

Caused by: com.amazonaws.mobileconnectors.apigateway.ApiClientException: {"Message":"User: arn:aws:sts::686770309549:assumed-role/Cognito_bookmixnewUnauth_Role/CognitoIdentityCredentials is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-east-1:********9549:abcde/mycleint/GET/login/login"}
                                                                             (Service: MyClient; Status Code: 403; Error Code: null; Request ID: 80ede0b7-3f77-13435e6-45345-24325435)
                                                                                at com.amazonaws.mobileconnectors.apigateway.ApiClientHandler.handleResponse(ApiClientHandler.java:240)
                                                                                at com.amazonaws.mobileconnectors.apigateway.ApiClientHandler.invoke(ApiClientHandler.java:93)
                                                                                at $Proxy1.viewprofileGet(Native Method)
                                                                                at com.example.android.awsapidemo.AwsActivity$MyAsyncTask.doInBackground(AwsActivity.java:63)
                                                                                at com.example.android.awsapidemo.AwsActivity$MyAsyncTask.doInBackground(AwsActivity.java:37)
                                                                                at android.os.AsyncTask$2.call(AsyncTask.java:287)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:234)
                                                                                ... 4 more

A: The key detail in your error log is this message:

"User: arn:aws:sts::686770309549:assumed-role/Cognito_bookmixnewUnauth_Role/CognitoIdentityCredentials is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-east-1:********9549:abcde/mycleint/GET/login/login"

There is a role associated with each Cognito identity pool.  You need to add policy to your role to give it permissions to the "execute-api:Invoke" action on the resource ARN given above.
The policy should look something like this:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "execute-api:Invoke"
      ],
      "Resource": [
        "arn:aws:execute-api:us-east-1:********9549:abcde/mycleint/GET/login/login"
      ]
    }
  ]
}

Also, the resource path in your ARN looks odd, so double check that you built the correct URL for invoking your API.  The general format for the ARN is:
arn:aws:execute-api:us-east-1:my-aws-account-id:my-api-id/my-stage/GET/my-resource-path
Base on the ARN in your error log, we have:
my-aws-account-id: ********9549
my-api-id: abcde
my-stage: mycleint
HTTP method: GET
my-resource-path: /login/login`

Is "mycleint" the name of your stage?
Is the resource path really "/login/login"?
Also, it seems a bit odd to be using both a Cognito identity pool and a custom login method.  Usually people use one or the other.  With this set-up the user has to authenticate via the Cognito identity pool before they can call the custom login method.

A: Try like this
AmazonDynamoDBClient ddbClient = Region.getRegion(Regions.EU_WEST_1) // CRUCIAL
    .createClient(
        AmazonDynamoDBClient.class,
        credentialsProvider,
        new ClientConfiguration()
    );

Check this value

Region.getRegion(Regions.EU_WEST_1) // CRUCIAL

if your database in a different region you need to specify it properly.other wise it will not work


text:
Q: How do I throw InterruptedException when using Mockito Static mocking in Junit 5? Please do not suggest PowerMock.
I am trying to test something like the following
            try {
                ...
                Thread.sleep(config.getRetryInterval());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.error("...");
            }

I try to test like...
 try (MockedStatic<Thread> u2 = Mockito.mockStatic(Thread.class)) {
     u2.when(() -> Thread.sleep(500)).thenThrow(new InterruptedException(""));
     assertThrows(...);
 }

But I get

org.mockito.exceptions.base.MockitoException: It is not possible to mock static methods of java.lang.Thread to avoid interfering with class loading what leads to infinite loops

What is the proper way to handle something like this in Mockito with the new Static setup?


text:
Q: Android: ImageView with svg looks blurry I'm many svg exported from Adobe illustrator, it only have a size of 9.36*10.8.
When I use the xml vector of this svg (converted by Android Studio) as the src of ImageView with a size of 19.5dp * 22.5dp, the imageview looks blurr.
Shouldn't have svg have the ability to scale without any blurr?
I can't change the viewportWidth or viewportHeight.
P.S: I have enabled hardwareAcclerate, does that have issue with vector drawable too?
Sample SVG (I used this in BottomNavigationView item, it looks very blurry):
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="6.4771dp"
    android:height="7.92dp"
    android:viewportWidth="6.4771"
    android:viewportHeight="7.92">
  <path
      android:fillColor="#cacaca"
      android:pathData="M3.2386,4.3201c1.0975,0 1.9791,-0.9702 1.9791,-2.16S4.3361,0 3.2386,0c-1.0975,0 -1.9791,0.9702 -1.9791,2.16s0.8816,2.16 1.9791,2.16ZM6.2722,5.625c-0.2732,-0.4733 -0.778,-0.765 -1.3244,-0.765L1.5293,4.86c-0.8446,0 -1.5293,0.685 -1.5293,1.53 0.001,0.8446 0.6851,1.5291 1.5293,1.53h3.4185c0.5464,0 1.0512,-0.2916 1.3244,-0.765s0.2732,-1.0566 0,-1.53Z" />
</vector>

I'm running Android 13 with AndroidX, Target Version 32 without any support library. Gradle 7.5.1


text:
Q: How to solve 'No module named pymysql' I use computer that is Window 10 and my Python version is 3.6.
I installed pymysql and MySQLdb as in the picture below.

But When I tried to run python, I got this error : No module named 'pymysql'
also, MySQLdb...
How can I solved it?

A: Try to use pip3 install PyMySQL and import pymysql


text:
Q: Android Studio : Error running 'app' Default activity not found I'm new to android studio and doing my first project.  I made changes to my layout xml file after which getting the above mentioned error. i didn't add any new activity and also the android manifest.xml file has default activity mentioned.
I have tried to invalidate the cache and restart the Android studio but still the error exists and I'm not able to execute my program.

A: You can configure it from "app" -> "Configurations"

A: In this scenario You have missed by telling the manifest about Which activity to run, Like I have Removed these Lines From Menifest
        <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

This error will accour, Just add the above Lines in menifest and Your error will Gone.
Like I have tested By removing the above line for Yourself from Menifest I face the Error just Like You..

Here the main Activity will be the One You want to start First After Installation Of Apk


text:
Q: Cannot open a csv file I  have a csv file on which i need to work in my jupyter notebook ,even though i am able to view the contents in the file using the code in the picture
When i am trying to convert the data into a data frame i get a "no columns to parse from file error"
i have no headers. My csv file looks like this and also i have saved it in the UTF-8 format

A: Try to use pandas to read the csv file:
df = pd.read_csv("BON3_NC_CUISINES.csv)
print(df)


text:
Q: Bootstrap 5 form-group, form-row, form-inline not working I'm trying to update my app from Bootstrap 4 to Bootstrap 5, but all the elements that were using  form classes such as form-group, form-row, form-inline are completely broken.

A: The reason is form-group, form-row, and form-inline classes have been removed in Bootstrap 5:

Breaking change: Dropped form-specific layout classes for our grid system. Use our grid and utilities instead of .form-group, .form-row, or .form-inline.

https://getbootstrap.com/docs/5.0/migration/#forms
So Grid and Utilities are supposed to be used instead.
...but if you are looking for a quick solution, here's how these classes were working in Bootstrap 4:
.form-group {
  margin-bottom: 1rem;
}

.form-inline .form-control {
  display: inline-block;
  width: auto;
  vertical-align: middle;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-right: -5px;
  margin-left: -5px;
}

.form-row > .col {
  padding-left: 5px;
  padding-right: 5px;
}

label {
  margin-bottom: 0.5rem;
}

A: The fix is easier than this. Wrap all your rows in
, then change class="form-row" to class="row", and convert class="form-group col-md-3" (for example) to class="col-md-3".

A: How to migrate an .inline-form to Bootstrap 5+
TLDR:

*

*Replace the Bootstrap 4 inline-form class with flexbox helper classes: d-flex flex-row align-items-center flex-wrap.

*If you used the mr-* class to space your form elements, replace these with the equivalent me-* classes ("margin end"). E.x. mr-2 becomes me-2. Similarly, ml-* becomes ms-* ("margin start").

*Consult the Bootstrap 5 form documentation to migrate your input elements. For example, on a select element the class custom-select in v4 becomes form-select in v5.

Full Example
Compare the Bootstrap 4 inline form below with the exact equivalent form in Bootstrap 5.
Example (trimmed) from Bootstrap 4's docs (Codesandbox).
This is Bootstrap 4 code.
<form class="form-inline">
  Preference
  <select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref">
    <option selected>Choose...</option>
  </select>

    <input type="checkbox" class="custom-control-input" id="customControlInline">
    Remember my preference

  <button type="submit" class="btn btn-primary my-1">Submit</button>
</form>

Same form in Bootstrap 5 (Codesandbox)
<form class="d-flex flex-row align-items-center flex-wrap">
  Preference
  <select class="form-select my-1 me-sm-2 w-auto" id="inlineFormCustomSelectPref">
    <option selected>Choose...</option>
  </select>

    <input type="checkbox" class="form-check-input" id="customControlInline" />
    Remember my preference

  <button type="submit" class="btn btn-primary my-1">Submit</button>
</form>

What to do with the deprecated form-group, form-row and form-inline classes in Bootstrap 5
As others have mentioned, the classes form-group, form-row and form-inline are removed in Bootstrap 5. Here's how they can be replaced:

*

*form-group can be replaced with mb-3, since it previously applied the property margin-bottom: 1rem which the mb-3 class will do by default as well.

*Form specific layout classes are dropped (source: Migration guide). form-row can be replaced with row in most instances.

*As described above, form-inline can be recreated by applying the following classes: d-flex flex-row align-items-center flex-wrap.

Hope this helps!

A: Because form-group, form-row, and form-inline classes have been removed in Bootstrap 5:
I have resorted to using gy-. eg(gy-2)

               <select class="form-control">
                   <option>invoice</option>
                   <option>qoutation</option>
               </select>

               <select class="form-control product-select" name="state">
                   <option value="AL">Search Product..</option>
               </select>


text:
Q: Assigning an anonymous function to a variable in javascript I'm running this javasrcipt code on google chrome browser as an html script tag.
<script type="text/javascript">
    var bar=function() {
        var name='tanzeel';
        console.log('inside a function');
    }
    console.log('My name is ' +bar.name);
</script>

I'm coming from java and cpp background. My knowledge about oop says that function in js are instantiated as an object and here variable bar is pointing to that object. So I can access all the properties of that object. Then why console.log('My name is ' +bar.name) is printing My name is bar instead of the string My name is tanzeel.
Please correct me where i am wrong and what else do i need to know. Thanks.

A: Your variable may be "pointing" (dat cpp lingo ;)) to an object, but you can't just treat that object any how you want. The object is a function in this case, so you cannot treat the function's body as having fields in the sense of a regular class.
The output you get is the name of the function.

To have this work, you must instantiate the object using new keyword. You also have to assign properties to the class in order to access them.
var bar=function() {
    this.name='tanzeel';
    //console.log('inside a function');
}
var b = new bar()
console.log(b.name);

A: There are two separate issues here.
First, functions are objects and can have properties. Variables defined in the scope of a function are completely different to properties of the function object. They exist only while the function is running (although c.f. closures) and are referred to directly and not in relation to the function.
Second, functions can have names. Typically this comes from an explicit name in the function expression:
var bar = function foo () { };

… but since a change in JS a few years ago, anonymous function expressions get a name from the variable that they are assigned to.
var bar = function () { };

The fact that you have a variable named name inside the function is unrelated to the function having a property called name.

A: When you assign string tanzeel to variable name, you don't change name property of the bar function. Instead you just create name variable in the lexical environment of bar function.
bar.name in console.log statement evaluates to bar because the function infers it from it's syntactic position

A: The expected behaviour is understandable. This is because functions are treated as objects in javascript. Each object has a set of properties. Similarly, functions have a property name in their prototype chain which evaluates to the name of the function. Read more here:
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Function/name
Also, check out the console in the image below. You can see a name property there inside the constructor.