text:
Q: Четность/нечетность отрицательных чисел Возможно глупая ошибка, но сам разобраться не могу. Есть цикл на проверку четности в программе. Все нечетные числа нужно поделить на среднее арифметическое всех чисел. Вот фрагмент.
void input (ofstream &in) {
vector <int> arr;
generate_n (back_inserter (arr), 100,
            [] {return rand() % 101 - 50;});
transform(arr.begin(),arr.end(),
          ostream_iterator<int>(in, "   "),
          [] (int x) {return x;});
}
vector <int> inputfile(ifstream & out) {
    vector <int> arr;
    transform(istream_iterator<int>(out),istream_iterator<int>(), back_inserter(arr), [] (int x) {return x;});
    return arr;
}
vector <int> modify (vector <int> & other) {
    int var = 0;
    vector <int> arr;
    var = accumulate(other.begin(), other.end(), 0) / 100;
    cout << "Sum of Array = " << var << endl << endl;
    transform(other.begin(), other.end(), back_inserter(arr), [&var] (int x) {
        if (x % 2 == 1) //здеcь задается условие проверки
            x /= var;
        return x;
        });
    return arr;
}

Дело в том что программа делит только положительные нечетные числа, а отрицательные игнорирует

A: Замените условие
if (x % 2 == 1)

на условие
if (x % 2 != 0)

Проблема в том, что первое условие для отрицательных чисел дает отрицательный остаток.:) Посмотрите результат этой демонстрационной программы
#include <iostream>

int main()
{
    int x = -11;

    std::cout << x % 2 << '\n';

    return 0;
}

Вывод на консоль:
-1

Обратите внимание на то, что вместо алгоритма std::transform в том контексте, в котором вы его используете, проще использовать алгоритм std::copy.

A: Возможна проверка используя операцию логическое И.
    int a = -10;
    int b = -11;

    std::cout<< (a & 1)<<'\n';
    std::cout<< (b & 1)<< '\n';

output:
0
1


text:
Q: Two overlapping squares $ABCD$ is a square. $BEFG$ is another square drawn with the common vertex $B$ such that $E,\ F$ fall inside the square $ABCD$. Then prove that $DF^2=2\cdot AE^2$.

A: Let $ABCD$ be the unit square with $A =(0,0)$, and let $E = (x,y)$. Then $\vec{BE} = (x-1,y)$, so $\vec{EF} = (y,1-x)$, giving $F = E + \vec{EF} = (x+y, y+1-x)$.
Thus $\vec{DF} = F - D = (x+y, y+1-x) - (0, 1) = (x+y, y-x)$.
Hence $DF^2 = (x+y)^2 + (y-x)^2 = 2(x^2+y^2) = 2 AE^2$.
This is true wherever $E$ and $F$ are, and whatever the orientation of $BEFG$.

A: HINT: there's only one (two, if you count mirror reflections) orientation available for the inner square... though I wouldn't exactly call $E$ and $F$ "inside".

A:
$(NB)^2+(EN)^2=(EB)^2=y^2$$(NB)^2=y^2-(EN)^2$$(x-AN)^2=y^2-(y\sin\theta)^2=(y\cos\theta)^2$$x-AN=\pm y\cos\theta$$AN=x-y\cos\theta(\because y,\cos\theta \text{ both positive})$$(AE)^2=(AN)^2+(EN)^2$$(AE)^2=(x-y\cos\theta)^2+(y\sin\theta)^2$$(AE)^2=x^2-2xy\cos\theta+y^2\cos^2\theta+y^2\sin^2\theta=x^2-2xy\cos\theta+y^2$
$\sin(90-\theta)=\frac{EM}{y}, \therefore EM=y \cos\theta \therefore MN=y(\cos\theta+\sin\theta)$
$\therefore DP=x-y(\cos\theta+\sin\theta)$
$\cos(90-\theta)=\frac{MF}{y} \therefore MF=y\sin\theta \text{ and }PM=x-NB=x-y\cos\theta$
$PF=x-y(\cos\theta-\sin\theta)$
$(DF)^2=(DP)^2+(PF)^2$
Substitute and simplify to get $2(x^2+y^2-2xy\cos\theta)$
Hence $(DF)^2=2(AE)^2$

A: Let's solve the problem using complex numbers. WLOG, let $B$ be the origin and let $BADC$ and $BEFG$ be squares with points in that order counterclockwise. Let $z = BA$ and $w = BE$
Since $BC$ is just $BA$ rotated by $90^{\circ}$ CCW, we have $BC = i \cdot BA = iz$.
Then, since $BC = AD$, we have $BD = BA+AD = BA+BC = z+iz = (1+i)z$.
Similarly, $BG$ is just $BE$ rotated by $90^{\circ}$ CCW, so $BG = i \cdot BE = iw$.
Then, since $BG = EF$, we have $BF = BE+EF = BE+BG = w+iw = (1+i)w$.
Therefore, we have $|DF|^2 = |BF-BD|^2 = |(1+i)w-(1+i)z|^2 = |(1+i)(w-z)|^2$ $= |1+i|^2|w-z|^2 = 2|w-z|^2 = 2|BE-BA|^2 = 2|AE|^2$, as desired.
Note that this holds even if $E,F$ do not lie inside $ABCD$. Also, note that the above is a fancy way of showing that line segment $DF$ can be obtained by rotating line segment $AE$ about $B$ by $45^{\circ}$ and dilating by $\sqrt{2}$ about $B$.

A: ∆ABE and ∆DBF are similar
(SAS similarity criterion).
BF/BE = √2.
The assertion follows.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show style and ul li tag in android Textview I have String with ul,li and style tag in it. And I am trying to show them in HTML formatting in textview.
String


text:
Q: How to get AutoHotkey to capture Right Windows Key I have some AutoHotKey scripts that use or override some of the Win+char combinations.  On my laptop or work keyboard, where I only have 1 windows key, these work fine.  On my home desktop, my keyboard has a Right Windows key, which does not respond the same.  On the AHK site I can see that for the windows keys, there are special characters for that key because of this difference, however I can't figure out how to make it grab my combos.  For example, I have this one to override the default action with OneNote:
#n::Send #N

When I do that with the right windows key, it does nothing.  I've tried a variety of scripts, based on suggestions I've found around the interwebs, but nothing seems to work.  The only one I've found that AHK will even load is
RWin & n::Send #N

But that just ends up sending an uppercase N.  Anyone know how to properly capture RWin key combinations?

A: @techturtle, Reading your question still leaves me uncertain as to what you want. Do you want your RWin to behave like the normal Win key (Rwin::Lwin) or do you want to create a new set of different combinations with the RWin key?


text:
Q: Count of posts by different parameters? I need to get the count of posts (just a number, nothing else) by custom taxonomy AND post meta(string) but I can't find a good way to combine them both.
Im fairly new to programming & WP, Im not sure where to start from.

A: Use WP_Query with a tax_query and a meta_query argument, and return only IDs to save a bit of server resource.
$args = array(
  'post_type' => 'post',
  'tax_query' => array(
    array(
      'taxonomy' => 'people',
      'field'    => 'slug',
      'terms'    => 'bob',
    ),
  ),
  'meta_query' => array(
    array(
      'key'     => 'age',
      'value'   => array( 3, 4 ),
      'compare' => 'IN',
    ),
  ),
  'fields' => 'ids'.
);
$query = new WP_Query( $args );

And check the found_posts element of $query-- var_dump($query->found_posts);


text:
Q: How to manage accents in UISearchbar? well I have a big toruble.
Im parsing a JSON in a tableview with a UISearchBarController, so my app is in spanish and some of the json entries  have accents and when I make the search ex. if im looking for "México" I type "Mexico" and the result is nil because I didnt write the accent in the search.
So the question is, ¿How can I solve this? I want the accents be invisible for the search. Hope I explain well
Heres the searchbar method:
NSMutableArray *allObject;
    NSMutableArray *displayObject;

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
    {
        if([searchString length] == 0)
        {
            [displayObject removeAllObjects];
            [displayObject addObjectsFromArray:allObject];
        }
        else
        {
            [displayObject removeAllObjects];
            for(NSDictionary *tmpDict in allObject)
            {
                NSString *val = [tmpDict objectForKey:doctorname];
                NSRange r = [val rangeOfString:searchString options:NSCaseInsensitiveSearch];

                NSString *val2 = [tmpDict objectForKey:doctoresp];
                NSRange r2 = [val2 rangeOfString:searchString options:NSCaseInsensitiveSearch];

                NSString *val3 = [tmpDict objectForKey:direccion];
                NSRange r3 = [val3 rangeOfString:searchString options:NSCaseInsensitiveSearch];

                if(r2.location != NSNotFound || r.location != NSNotFound || r3.location != NSNotFound)
                {
                    [displayObject addObject:tmpDict];
                }
            }
        }
        return YES;
    }

A: Add the NSDiacriticInsensitiveSearch option, so e will match é.


text:
Q: Spring Boot Webflux Security - reading Principal in service class when writing tests I am quite new to the Spring ecosystem in general and Webflux. There are 2 things that I am trying to figure out and cannot find any specifics about.
My Setup:
I am writing a Spring Boot 2 REST API using WebFlux (not using controllers but rather handler functions). The authentication server is a separate service which issues JWT tokens and those get attached to each request as Authentication headers. Here is a simple example of a request method:
public Mono<ServerResponse> all(ServerRequest serverRequest) {
        return principal(serverRequest).flatMap(principal ->
                ReactiveResponses.listResponse(this.projectService.all(principal)));
    }

Which i use to react to a GET request for a list of all "Projects" that a user has access to.
I afterwards have a service which retrieves the list of projects for this user and i render a json response.
The Problems:
Now in order to filter the projects based on the current user id i need to read it from the request principal. One issue here is that i have plenty service methods which need the current user information and passing it through to the service seems like an overkill. One solution is to read the principal inside the service from:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Question 1:
Is this a good practice in general when writing functional code (If i do this instead of propagating the principal)? is this a good approach despite the complexity of reading and sending the principal from the request to the service in each method?
Question 2:
Should i instead use the SecurityContextHolder Thread Local to fetch the principal, and if i do that how do i write tests for my service?
If i use the Security Context how do i test my service implementations which are expecting a principal that is of type JWTAuthenticationToken
and i always get null when trying to do something like described here: Unit testing with Spring Security
In the service tests, In tests what i've managed to do so far is to propagate the principal to the service methods and use mockito to mock the principal. This is quite straightforward.
In the Endpoint Tests i am using @WithMockUser to populate the principal when doing requests and i mock out the service layer. This has the downside of the principal type being different.
Here is how my test class for the service layer looks:
@DataMongoTest
@Import({ProjectServiceImpl.class})
class ProjectServiceImplTest extends BaseServiceTest {

    @Autowired
    ProjectServiceImpl projectService;

    @Autowired
    ProjectRepository projectRepository;

    @Mock
    Principal principal;

    @Mock
    Principal principal2;

    @BeforeEach
    void setUp() {
        initMocks(this);

        when(principal.getName()).thenReturn("uuid");
        when(principal2.getName()).thenReturn("uuid2");
    }

    // Cleaned for brevity

    @Test
    public void all_returnsOnlyOwnedProjects() {
        Flux<Project> saved = projectRepository.saveAll(
                Flux.just(
                        new Project(null, "First", "uuid"),
                        new Project(null, "Second", "uuid2"),
                        new Project(null, "Third", "uuid3")
                )
        );
        Flux<Project> all = projectService.all(principal2);
        Flux<Project> composite = saved.thenMany(all);

        StepVerifier
                .create(composite)
                .consumeNextWith(project -> {
                    assertThat(project.getOwnerUserId()).isEqualTo("uuid2");
                })
                .verifyComplete();
    }

}

A: Based on the other answer, i managed to solve this problem in the following way.
I added the following methods to read the id from claims where it normally resides within the JWT token.
    public static Mono<String> currentUserId() {
        return jwt().map(jwt -> jwt.getClaimAsString(USER_ID_CLAIM_NAME));
    }

    public static Mono<Jwt> jwt() {
        return ReactiveSecurityContextHolder.getContext()
                .map(context -> context.getAuthentication().getPrincipal())
                .cast(Jwt.class);
    }

Then i use this within my services wherever needed, and i am not forwarding it through the handler to the service.
The tricky part was always testing. I am able to resolve this using the custom SecurityContextFactory. I created an annotation which i can attach the same way as @WithMockUser, but with some of the claim details i need instead.
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockTokenSecurityContextFactory.class)
public @interface WithMockToken {
    String sub() default "uuid";
    String email() default "test@test.com";
    String name() default "Test User";
}

Then the Factory:
String token = "....ANY_JWT_TOKEN_GOES_HERE";

    @Override
    public SecurityContext createSecurityContext(WithMockToken tokenAnnotation) {
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        HashMap<String, Object> headers = new HashMap<>();
        headers.put("kid", "SOME_ID");
        headers.put("typ", "JWT");
        headers.put("alg", "RS256");
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("sub", tokenAnnotation.sub());
        claims.put("aud", new ArrayList<>() {{
            add("SOME_ID_HERE");
        }});
        claims.put("updated_at", "2019-06-24T12:16:17.384Z");
        claims.put("nickname", tokenAnnotation.email().substring(0, tokenAnnotation.email().indexOf("@")));
        claims.put("name", tokenAnnotation.name());
        claims.put("exp", new Date());
        claims.put("iat", new Date());
        claims.put("email", tokenAnnotation.email());
        Jwt jwt = new Jwt(token, Instant.now(), Instant.now().plus(1, ChronoUnit.HOURS), headers,
                claims);
        JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(jwt, AuthorityUtils.NO_AUTHORITIES); // Authorities are needed to pass authentication in the Integration tests
        context.setAuthentication(jwtAuthenticationToken);

        return context;
    }

Then a simple test will look like this:
    @Test
    @WithMockToken(sub = "uuid2")
    public void delete_whenNotOwner() {
        Mono<Void> deleted = this.projectService.create(projectDTO)
                .flatMap(saved -> this.projectService.delete(saved.getId()));

        StepVerifier
                .create(deleted)
                .verifyError(ProjectDeleteNotAllowedException.class);
    }

A: As you are using Webflux you should be using the ReactiveSecurityContextHolder to retrieve the principal like so : Object principal = ReactiveSecurityContextHolder.getContext().getAuthentication().getPrincipal();
The use of the non-reactive one will return null as you are seeing.
There is more info related to the topic in this answer - https://stackoverflow.com/a/51350355/197342


text:
Q: Rails Apps - scaffold error I'm having a rails app problem when executing the scaffold command in my command line. I used the rails generate scaffold User name:string email:string command that our teacher showed us today. His worked, but mine gets the following.
c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activerecord-3.2.13/lib/active_record/dynamic_matchers.rb:55:in `method_missing': undefined method `migration_error=' for ActiveRecord::Base:Class (NoMethodError)
    from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activerecord-3.2.13/lib/active_record/railtie.rb:66:in `block (3 levels) in <class:Railtie>'
    from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activerecord-3.2.13/lib/active_record/railtie.rb:65:in `each'
    from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activerecord-3.2.13/lib/active_record/railtie.rb:65:in `block (2 levels) in <class:Railtie>'
    from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/lazy_load_hooks.rb:36:in `instance_eval'

There are more lines, but I would hope that you get the idea. If I need to post the rest, I will. Beyond that, if there is another question that has the answer to this, please point me in that direction. Thank you in advance.

A: Try set up your database first by running this command
rake db:drop db:create db:migrate

or
rake db:reset


text:
Q: how to use a pointer inside struct in C I have a two struct, one is linked list.
typedef struct Mark{
       int  people;
       Node *nodeyy;
}Mark

typedef struct Node{
       struct node next;
       int value;
}Node

if i allocated memory for a node, let say
 Node *node1=malloc( sizeof(struct Node));

And I also allocated memory for a bookmark, let say
 Mark *mark1=malloc( sizeof(struct Mark));

I want to make the pointer nodeyy in the mark1 points to the same thing as node1, how can i do that?
I think that
 mark1->nodeyy=node1;

is definitely wrong.

A: its correct now:
You will have to initialize the pointer or point it to an existing variable that you know won't go out-of-scope. BUT since node1 is dynamically allocated, you're just assigning one pointer to another, this creates a sort of reference to the newly allocated memory pointed by node1.
mark1->nodeyy = node1;

After this statement, mark1->nodeyy and node1 point to the memory location returned by the malloc(sizeof(Node)).

A: change the int* in struct Mark to Node*
typedef struct Mark{
       int  people;
       Node *nodeyy;
}Mark

then you can do
mark -> nodeyy =  (Node *) malloc(sizeof(Node))


text:
Q: Check if there is any 12-character word available in the string. If available, extract the word I have been looking to extract only a 12-character word from the string if it exists.
Need to check if first 5 characters are from a given list and check last 3 character are numbers.
Input data (Data.xlsx):
Description                                                  Number

CHQ -AQBCN222Q546 from India Federation Pvt Ltd
CHQN#DJBNK220Q329 from Indiana Basics Software Ltd -BC003
CASH- NJRQC225J987^ from US Fertilizers LLP
CHQ - from India Bulls Pvt Ltd
AQBCN222Q989 from India Bulls Pvt Ltd
CHQ -AQCCN222Q546 from India Federation Pvt Ltd
CASH - AQBCN222Q546289 from India Federation Pvt Ltd

list_Character - ['AQBCN','PUCNQ','DJBNK','ADJBC','NJRQC']

Expected output:
Description                                                          Number

CHQ -AQBCN222Q546 from India Federation Pvt Ltd                    AQBCN222Q546
CHQN#DJBNK220Q329 from Indiana Basics Software Ltd -BC003          DJBNK220Q329
CASH- NJRQC225J987^ from US Fertilizers LLP                        NJRQC225J987
CHQ - from India Bulls Pvt Ltd
AQBCN222Q989 from India Bulls Pvt Ltd                              AQBCN222Q989
CHQ -AQCCN222Q546 from India Federation Pvt Ltd
CASH - AQBCN222Q546289 from India Federation Pvt Ltd

Code:
import pandas as pd
import re

df = pd.read_excel(r'D:/Users/Data.xlsx')
list_Character - ['AQBCN','PUCNQ','DJBNK','ADJBC','NJRQC']

regex = r'[#-]((?:' + r'|'.join(list_Character) + r')\w{5})\b'
df["Number"] = df["Description"].str.extract(regex)

I am not finding the solution.
I have tried getting the reference from Check if there is any 10 character word available in the string If Exist Extract the word But it did not work.

A: You can slightly modify the regex to remove the leading character match and match 7 extra characters:
list_Character = ['AQBCN','PUCNQ','DJBNK','ADJBC','NJRQC']

regex = r'((?:' + r'|'.join(list_Character) + r')\w{7})\b'
df["Number"] = df["Description"].str.extract(regex)

Output:
                                         Description        Number
0    CHQ -AQBCN222Q546 from India Federation Pvt Ltd  AQBCN222Q546
1  CHQN#DJBNK220Q329 from Indiana Basics Software...  DJBNK220Q329
2        CASH- NJRQC225J987^ from US Fertilizers LLP  NJRQC225J987
3                     CHQ - from India Bulls Pvt Ltd           NaN
4              AQBCN222Q989 from India Bulls Pvt Ltd  AQBCN222Q989
5    CHQ -AQCCN222Q546 from India Federation Pvt Ltd           NaN
6  CASH - AQBCN222Q546289 from India Federation P...           NaN


text:
Q: Non-closed subgroups of Lie groups The following are my impressions from playing with a line of irrational slope $\gamma$ in the standard torus $S^1\times S^1=\mathbb{R}^2/\mathbb{Z}^2$, $\mathbb{R}\hookrightarrow \mathbb{R}\mathbb\times\gamma\mathbb{R}$.  The topology induced on $\mathbb{R}$ by restricting open sets of $T^2$ is strictly coarser than the usual order topology on $\mathbb{R}$.  In fact, the basis consists of countable unions of neighborhoods.  The topology has a sort of "fractal" feel to it: for any integer $N$, $\epsilon>0$, there exists some $x>N$ with $d(x,0)<\epsilon$.  In fact, for a fixed $\epsilon$, the ball of radius $\epsilon$ about $0$ "unwraps" to intervals which, loosely speaking, approach length $2\epsilon$ as one approaches $\infty$.  The spacing of the intervals also seems like it is regular and governed by $\gamma$ and $\epsilon$.  That seems pretty neat to me.
Based on this and motivated by idle curiosity, I'm asking for (preferably modern) references which contain a systematic study of non-closed subgroups of Lie groups, as opposed to the usual off-hand mention that they exist and are not interesting.  I've turned up a couple of papers in the early '90s, but none of them are quite what I'm looking for.  The closest is probably Virgos, "Non-closed Lie Subgroups of Lie Groups" (Annals of Global Analysis and Geometry 11, 1993)  Content: Homotopy obstructions to existence of connected nonclosed Lie subgroups, construction of some examples.  But this is still not quite the sort of analysis I'm looking for.
Apparently there was a bit of work done in the '40s and '50s on the topic; names like Malcev and Van Est turn up in the "modern" references. I've also run across a paper by Goto.
To more precisely restate my question:

Is there any modern work studying non-closed Lie subgroups of Lie groups, or any survey papers or syntheses of older results?  By "modern" I mean from the last twenty years (aside from the already-mentioned papers by Virgos and Kubarski)


text:
Q: Get-QADUser Mailbox? I have a really generic/basic question. (Please close if not allowed)
Currently, I've been adding the quest.activeroles.admanagement snapin to run the QAD cmdlets. Is anyone familiar with how to find Organizational Mailboxes a user is attached to? Their regular user accounts other users are added/given permissions to, in order for them to send emails from and stuff of that nature.
The following is what I've been using to get what distros a user is a part of based on the container in AD:
Get-QADGroup -SearchRoot 'Distribution Lists' -ContainsMember abraham.alaniz

Unfortunately, since the objects are regular user accounts there's no option/parameter to search what other mailboxes they may be attached to.
The following returns the users/mailboxes that are part of the container for "Org Boxes".
Get-QADUser -SearchRoot 'Organizational Accounts'

There's no attribute in AD that gives me that information (or at least that I am aware of). Does anyone know how this can be accomplished (in regards to finding other user accounts/mailboxes a user is a part of)? Pardon if this comes off as confusing.
What we have is just a list of all the organization mailboxes/accounts, that are queried for each user in that account


text:
Q: Регулярное выражение для буквенно-цифровой строки в 10 символов Привет. Мне нужно составить выражение для файла urls.py
Get-переменная var может быть буквенно-цифровой строкой в 10 символов.
Ссылка выглядит так

http://127.0.0.1:8000/?var=fea40u7b94

Мой вариант примерно такой url(r'^(?P<var>\w+)$',
Правильно ли я составил выражение?

A: Чтобы найти десять цифробуквенных символов в конце строки, можно использовать
(?P<var>[a-zA-Z0-9]{10})$

См. онлайн-демо выражения.
Подробности

*

*(?P<var>[a-zA-Z0-9]{10}) - Именная захватывающая группа, находит ровно 10 букв/цифр ASCII

*$ - конец строки.

Вариации:

*

*10 символов после =: =(?P<var>[a-zA-Z0-9]{10})$

*От 1 до 10 символов: =(?P<var>[a-zA-Z0-9]{1,10})$

*Если не хотите писать [a-zA-Z0-9], используйте [^\W_].


text:
Q: Can I send http/2 request with OkHttp over NPN Negotiation? I notice that OkHttp support h2 over ALPN in Android 5.0+.
From some article,I learned that we can use NPN Negotiation for http/2 request.
Can I send http/2 request with OkHttp over NPN Negotiation?
So that it's possible to support h2 on android 4.1+ with better network performance :-D

A: We dropped NPN support. ALPN is the future.


text: Q: express requests one at a time In Express, is it possible to handle requests to a single route one at a time? I have a "checkout queue," and each time a checkout is created, stock is decreased. However, a simultaneous POST request to create a checkout checks the stock before stock is decreased in the first request, which causes overselling. Is there any way I can configure a route to accept requests one-at-a-time?


text:
Q: Getting a blank value or - + number $value to show in Regex MsgType=GetMarketAuction&Symbol=XLF&AuctionPrice=24.50&AuctionSize=57138&AuctionImbalance=0&AuctionImbalanceMkt=0&AuctionIndNetChange=&ClosingPrice=24.54&BidPrice=24.36&AskPrice=24.37&EC=0&ES=&AuctionImbalanceStatus=&AuctionMktImbalanceStatus=&Delta=

I am trying to pull all the data needed out of this regex line above. Using VB.net I have the first 5 things but am stuck once there is a -/+ $ number needed that sometimes displays as no character.
This works so far.
Dim r As New System.Text.RegularExpressions.Regex("Symbol=(?<1>.\w+)\&AuctionPrice=(?<2>.\d.\d+)\&AuctionSize=(?<3>.\d+)\&AuctionImbalance=(?<4>.a*)\&AuctionImbalanceMkt=(?<5>.a*)")

AuctionIndNetChange=(I am looking for something here to pull the value from)
Thanks!

A: You can use the following regex:
Symbol=(?<1>[^&]*)&AuctionPrice=(?<2>[^&]*)&AuctionSize=(?<3>[^&]*)&AuctionImbalance=(?<4>[^&]*)&AuctionImbalanceMkt=(?<5>[^&]*)&AuctionIndNetChange=(?<6>[^&]*)

See demo
Note that you do not have to use numbers in the names of capture groups, you can remove all ?<n> and you will get the same result.
Also, I replaced all your subpatterns in the capturing groups with [^&]* that means 0 or more characters other then &, since all of them are inside the query string.
HOWEVER, you can use a non-regex way with System.Web.HttpUtility.ParseQueryString (do not forget to add a reference to System.Web!):
Dim querystr As String = "MsgType=GetMarketAuction&Symbol=XLF&AuctionPrice=24.50&AuctionSize=57138&AuctionImbalance=0&AuctionImbalanceMkt=0&AuctionIndNetChange=&ClosingPrice=24.54&BidPrice=24.36&AskPrice=24.37&EC=0&ES=&AuctionImbalanceStatus=&AuctionMktImbalanceStatus=&Delta="
        Dim qscoll As System.Collections.Specialized.NameValueCollection = HttpUtility.ParseQueryString(querystr)
        Console.WriteLine(String.Format("AuctionSize: {0}, Symbol: {1}, AuctionPrice: {2}, AuctionSize: {3}, AuctionImbalance: {4}, AuctionImbalanceMkt: {5}, AuctionIndNetChange: {6}",
        qscoll("AuctionSize"), _
        qscoll("Symbol"), _
        qscoll("AuctionPrice"), _
        qscoll("AuctionSize"), _
        qscoll("AuctionImbalance"), _
        qscoll("AuctionImbalanceMkt"), _
        qscoll("AuctionIndNetChange")))

Output:
AuctionSize: 57138, Symbol: XLF, AuctionPrice: 24.50, AuctionSize: 57138, AuctionImbalance: 0, AuctionImbalanceMkt: 0, AuctionIndNetChange:


text:
Q: How to modify strings in js array It was supposed to capitalize first characters of each string but it doesn't. Please tell me how I can solve this problem.
    let array = ["string1", "string2", "string3", "string4"];
    let btn = document.getElementById("btn");

    array.forEach(function (item) {
      item.charAt(0).toUpperCase();
    })

    btn.addEventListener("click", function () {
      document.getElementById("p").innerHTML = array.join(" ")
    })```

A: You are getting the first letter and converting it to uppercase, but you aren't doing anything with it.
You need to concatenate the rest of the string to the first character, then reassign back.

let array = ["string1", "string2", "string3", "string4"];

array.forEach(function(item, i) {
  array[i] = item.charAt(0).toUpperCase() + item.substring(1)
})

console.log(array.join(" "))


text:
Q: How to compress data in C# to be decompressed in zlib python I have a python zlib decompressor that takes default parameters as follows, where data is string:
  import zlib
  data_decompressed = zlib.decompress(data)

But, I don't know how I can compress a string in c# to be decompressed in python. I've tray the next piece of code but when I trie to decompresse 'incorrect header check' exception is trown.
    static byte[] ZipContent(string entryName)
    {
        // remove whitespace from xml and convert to byte array
        byte[] normalBytes;
        using (StringWriter writer = new StringWriter())
        {
            //xml.Save(writer, SaveOptions.DisableFormatting);
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            normalBytes = encoding.GetBytes(writer.ToString());
        }

        // zip into new, zipped, byte array
        using (Stream memOutput = new MemoryStream())
        using (ZipOutputStream zipOutput = new ZipOutputStream(memOutput))
        {
            zipOutput.SetLevel(6);

            ZipEntry entry = new ZipEntry(entryName);
            entry.CompressionMethod = CompressionMethod.Deflated;
            entry.DateTime = DateTime.Now;
            zipOutput.PutNextEntry(entry);

            zipOutput.Write(normalBytes, 0, normalBytes.Length);
            zipOutput.Finish();

            byte[] newBytes = new byte[memOutput.Length];
            memOutput.Seek(0, SeekOrigin.Begin);
            memOutput.Read(newBytes, 0, newBytes.Length);

            zipOutput.Close();

            return newBytes;
        }
    }

Anyone could help me please?
Thank you.
UPDATE 1:
I've tried with defalte function as Shiraz Bhaiji has posted:
    public static byte[] Deflate(byte[] data)
    {
        if (null == data || data.Length < 1) return null;
        byte[] compressedBytes;

        //write into a new memory stream wrapped by a deflate stream
        using (MemoryStream ms = new MemoryStream())
        {
            using (DeflateStream deflateStream = new DeflateStream(ms, CompressionMode.Compress, true))
            {
                //write byte buffer into memorystream
                deflateStream.Write(data, 0, data.Length);
                deflateStream.Close();

                //rewind memory stream and write to base 64 string
                compressedBytes = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(compressedBytes, 0, (int)ms.Length);

            }
        }
        return compressedBytes;
    }

The problem is that to work properly in python code I've to add the "-zlib.MAX_WBITS" argument to decompress as follows:
    data_decompressed = zlib.decompress(data, -zlib.MAX_WBITS)

So, my new question is: is it possible to code a deflate method in C# which compression result could be decompressed with zlib.decompress(data) as defaults?

A: In C# the DeflateStream class supports zlib. See:
https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.deflatestream?view=netframework-4.8

A: As you described with your edit, zlib.decompress(data, -zlib.MAX_WBITS) is the correct way to decompress data from C#'s DeflateStream. There are two formats at play here:

*

*deflate - as in specification RFC 1951 - this is what's C# is producing

*zlib - as in specification RFC 1950 - this is what's Python is expecting by default

What is the difference between the two? It's small, really:
zlib = [compression flag byte] + [flags byte] + deflate + [adler checksum]
(there are also optional dictionary bytes but we don't have to worry about them)
Therefore, to get zlib format from deflate, we need to prepend two bytes of flags, and append Adler-32 checksum. Luckily we have an answer on stackoverflow for the flags, see What does a zlib header look like? and implementing Adler-32 is not that hard. So suppose you have your MemoryStream ms, we would first write the two flag bytes
ms.Write(new byte[] {0x78,0x9c});

...then we would do exactly what's in your answer
using (DeflateStream deflateStream = new DeflateStream(ms, CompressionMode.Compress, true))
{
       deflateStream.Write(data, 0, data.Length);
       deflateStream.Close();

}

and, at last, compute the checksum and append it to the end of the stream:
uint a = 0;
uint b = 0;
for(int i = 0; i < data.Length; ++i)
{
    a = (a + data[i]) % 65521;
    b = (b + a) % 65521;
}

Sadly, I don't know a pretty way of writing uints into the stream. This is an ugly way:
ms.Write(new byte[] { (byte)(b>>8),
                      (byte)b,
                      (byte)(a>>8),
                      (byte)a
});


text:
Q: How to remove duplicates within a string from the table in SQL server 2016 I got a table which contains a column of strings. Those strings are separated by a ;. Now I want to remove the duplicates after the string is splitted. For example:
-----------
| w;w;e;e |
-----------
| q;r;r;q |
-----------
| b;n;n;b |
-----------

The result should be:
-------
| w;e |
-------
| q;r |
-------
| b;n |
-------

Also it should not be a Select function but a (not 100% sure) delete function. So the values in the original table won't be duplicated anymore.

A: For an update statement, this will de-duplicate your column:
update t
  set col = stuff((
    select distinct
      ';'+s.Value
    from string_split(t.col,';') as s
    for xml path (''), type).value('.','varchar(1024)')
    ,1,1,'');

In sql server 2016, you can use string_split() along with the stuff() with select ... for xml path ('') method of string concatenation to concatenate only distinct values.
select
    t.id
  , t.col
  , dedup = stuff((
    select distinct
      ';'+s.Value
    from string_split(t.col,';') as s
    for xml path (''), type).value('.','varchar(1024)')
    ,1,1,'')
from t

dbfiddle demo: here
rextester demo: http://rextester.com/MAME55141; this demo uses a CSV Splitter function by Jeff Moden in the absence of string_split().
returns:
+----+---------+-------+
| id |   col   | dedup |
+----+---------+-------+
|  1 | w;w;e;e | e;w   |
|  2 | q;r;r;q | q;r   |
|  3 | b;n;n;b | b;n   |
+----+---------+-------+

splitting strings reference:

*

*Tally OH! An Improved SQL 8K "CSV Splitter" Function - Jeff Moden

*Splitting Strings : A Follow-Up - Aaron Bertrand

*Split strings the right way – or the next best way - Aaron Bertrand

*string_split() in SQL Server 2016 : Follow-Up #1 - Aaron Bertrand

A: If "e", "r", and "w" are the only values in the string, then the simplest way is to reconstruct the string:
select stuff( (case when string like '%e%' then ';e' else '' end) +
              (case when string like '%r%' then ';r' else '' end) +
              (case when string like '%w%' then ';w' else '' end),
              1, 1, ''
            )

I suspect the values might be limited, because these look like file permissions (read/write/execute).  Otherwise, you will need to parse the string into separate rows (using XML, a UDF, or a recursive CTE) and recombine the values.
You should learn a lesson here.  Don't store lists in strings.  These values should either be flags (if I am right about there only being a handful of values).  Or, they should be on separate rows of a another table.


text:
Q: Java JPA GenerationType.Auto value always null I have several classes in the same project in which the id is always autogenerated. However in this specific case the value of my id happens to be always null. I'm really wondering what is wrong, because after some changes it stopped working. And comparing it with the other classes the code seems to be the same.
package com.checkin.model.entity;
import javax.persistence.*;

@Entity
public class Checkin {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(nullable = false)
private String date;

public Checkin(){

}

public Checkin(String date){
    this.date = date;
    System.out.println(this.id);
    System.out.println(this.getId());
}

public Long getId() {return id;}

public void setId(Long id) {this.id = id;}

public String getDate() {return date;}

public void setDate(String date) {this.date = date;}

}

This is the repository where the objects are saved:
package com.checkin.model.repository;

import com.checkin.model.entity.Checkin;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository("checkinRepository")
public interface CheckinRepository extends CrudRepository<Checkin, Long> {
   Checkin findById(Long id);

}

and finally this is the result that I get from Postman
enter image description here

A: The Generation type AUTO sets the the underlying database to generate the ID
http://docs.oracle.com/javaee/6/api/javax/persistence/GenerationType.html#AUTO
In this case, what you want to check is if the H2 database id column has the attribute to generate IDs. I am guessing it does not. I dont use AUTO much myself so I am assuming if your Auto works for other Entities then those are setup correctly.
You may need to do one of the following:

*

*migration here

*update column in H2

*recreate the table


text:
Q: how to freeze go button in soft keyboard I have a webView in my project, When I click go buttton in soft keyboard, the form submits and an error is returned. I want to hide the keyboard instead of form submission. plz help.

A: I read about this a little and i think you might be looking for android:imeOptions="actionDone" (or maybe actionNone).
Didn't try it myself yet... see more info here:
http://android-developers.blogspot.co.il/2009/04/updating-applications-for-on-screen.html
under "Controlling the action buttons"


text:
Q: Error converting month number to datetime object Trying to convert a column in a dataframe from the months 1-420 (35 years of monthly data from 1985 to 2010) to a datetime object.
Sample dataframe:
import pandas as pd
import numpy as np
dates = pd.Series(range(1,421))
df2 = pd.DataFrame(np.random.randn(420,4),index=dates,columns=list('ABCD'))

Convert index to a datetime object:
df2.index = pd.to_datetime(df2.index,unit='M', origin='1981-01-01')

Gives the error:
ValueError: cannot cast unit M

I don't know why it won't cast the unit M, as when I try 'd' instead of 'M' it works, and goes up daily - why won't it go up monthly? I got the units from here.
using 'm' output looks like this:
                       A           B            C            D
1981-01-01 00:01:00 0.672397    0.753926    0.865845    0.711594
1981-01-01 00:02:00 0.786754    0.658421    -0.111609   -1.459447
1981-01-01 00:03:00 0.200273    -1.485525   -1.939203   0.921833
1981-01-01 00:04:00 -1.589668   0.109760    -1.349790   -1.951316
1981-01-01 00:05:00 0.133847    -0.359300   -1.246740   -0.835645
1981-01-01 00:06:00 -0.843962   1.222129    -0.121450   -1.223132
1981-01-01 00:07:00 -0.818932   0.731127    0.984731    -1.028384

which goes up in minutes, I want it to go up in Months like this:
                            A           B            C           D
    1981-01-01 00:00:00 0.672397    0.753926    0.865845    0.711594
    1981-02-01 00:00:00 0.786754    0.658421    -0.111609   -1.459447
    1981-03-01 00:00:00 0.200273    -1.485525   -1.939203   0.921833

A: You should use date_range:
df2.index = pd.date_range('1981/1/1', periods=len(df2), freq='MS')

Output:
                A           B           C            D
1981-01-01  -0.761933   0.726808    0.589712    -1.170934
1981-02-01  0.030521    -0.892427   -1.366809   -1.515724
1981-03-01  -0.282887   1.068047    0.244493    -0.247356

Have a look at offset alias for more information.
EDIT: As OP said, the 425 days are repeating over 200,000 rows. Below code would provide repeated indices.
daterange = pd.date_range('1981/1/1', periods=420, freq='MS')

Then expand it to fit your dataframe by repeating it.
df2.index = list(daterange) * math.floor(len(df2)/len(list(daterange))) + list(daterange)[0:math.floor(len(df2)%len(list(daterange)))]


text:
Q: Should Health Checks call other App Health Checks I have two API's A and B that I control and both have readiness and liveness health checks. A has a dependency on B.
A
/foo - This endpoint makes a call to /bar in B
/status/live
/status/ready

B
/bar
/status/live
/status/ready

Should the readiness health check for A make a call to the readiness health check for API B because of the dependency?

A: Referencing Microsoft's Implementing Resilient Applications tutorials. Specifically the Health monitoring, it is suggested that if the overall status of the current service is dependent on the status of a dependency then the healthy status of the service should only be healthy if its dependencies are healthy

However, the MVC web application of eShopOnContainers has multiple dependencies on the rest of the microservices. Therefore, it calls one AddUrlCheck method for each microservice, as shown in the following example:

// Startup.cs from the MVC web app
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.Configure<AppSettings>(Configuration);
        services.AddHealthChecks(checks =>
        {
            checks.AddUrlCheck(Configuration["CatalogUrl"]);
            checks.AddUrlCheck(Configuration["OrderingUrl"]);
            checks.AddUrlCheck(Configuration["BasketUrl"]);
            checks.AddUrlCheck(Configuration["IdentityUrl"]);
        });
    }
}

Thus, a microservice will not provide a "healthy" status until all its checks are healthy as well.

emphasis mine
So to more directly answer your question about

Should the readiness health check for A make a call to the readiness health check for API B because of the dependency?

I would say yes it should. Especially if the health of the dependency B directly affects the stability of A .

A: There is Readiness and Liveness.  and I don't think there is obvious answer. only a guideline -
Alive means the service is simply responsive. e.g. able to respond with 200/OK.
Ready means functioning on what it is expected to do.  (it's most used API)
For example, at startup stage, a service may be alive bot not yet ready as dependent components/services are not alive or ready yet. (e.g. DB not connected yet).
Therefore, I would say that Yes, for readiness you might need to make sure other essential components are alive or also ready.  All you have to decide is which ones are essentials to be checked for readiness.

A: Service A is ready if it can serve business requests. So if being able to reach B is part of what it needs to do (which it seems it is) then it should check B.
An advantage of having A check for B is you can then fail fast on a bad rolling upgrade. Say your A gets misconfigured so that the upgrade features a wrong connection detail for B - maybe B's service name is injected as an environment variable and the new version has a typo. If your A instances check to Bs on startup then you can more easily ensure that the upgrade fails and that no traffic goes to the new misconfigured Pods. For more on this see https://medium.com/spire-labs/utilizing-kubernetes-liveness-and-readiness-probes-to-automatically-recover-from-failure-2fe0314f2b2e
It would typically be enough for A to check B's liveness endpoint or any minimal availability endpoint rather than B's readiness endpoint. This is because kubernetes will be checking B's readiness probe for you anyway so any B instance that A can reach will be a ready one. Calling B's liveness endpoint rather than readiness can make a difference if B's readiness endpoint performs more checks than the liveness one. Keep in mind that kubernetes will be calling these probes regularly - readiness as well as liveness - they both have a period. The difference is whether the Pod is withdrawn from serving traffic (if readiness fails) or restarted (if liveness fails). You're not trying to do end-to-end transaction checks, you want these checks to contain minimal logic and not use up too much load.
It is preferable if the code within A's implementation of readiness does the check rather than doing the check at the k8s level (in the Pod spec itself). It is second-best to do it at the k8s level as ideally you want to know that the code running in the container really does connect.
Another way to check dependent services are available is with a check in an initContainer. Using initContainers avoids seeing multiple restarts during startup (by ensuring correct ordering) but doing the checks to dependencies through probes can go deeper (if implemented in the app's code) and the probes will continue to run periodically after startup. So it can be advantageous to use both.
Be careful of checking other services from readiness too liberally as it can lead to cascading unavailability. For example, if a backend briefly goes down and a frontend is probing to it then the frontend will also become unavailable and so won't be able to display a good error message. You might want to start with simple probes and carefully add complexity as you go.

A: When I implement the health endpoint in one application I follow the best practice to check all the dependencies that the application requires to work.
If one of these dependencies doesn't work, my application can not work so It is marked as unhealthy.

A: No, You dont need to check healthchek on other microservices. Single microservice should work regardless of other microservices (according to microservice definition). If one microservice depends on another then you can use fallBack, circuit breaker patterns against other microservices so it can work without failing.


text:
Q: how to create a file and write some output to it from server side java script I am new to java script. I have execute some API from server-side java script and stored their status in a array now i want to create a file at desired location on same machine and write output to it.

A: You must have to use server-side language to do this js won't do that!
Lets take the example of the ASP.NET
@{
    var userData = /* data stored in the array */
    var dataFile = Server.MapPath("~/App_Data/data.txt"); // file location
    File.AppendAllText (@dataFile, userData); // save it!
}

This way, you will be able to save the data in the file on the server-side. If you wanted to save it without reloading the page (like many developers love to) then you can try using ajax request. For that, you will be using jQuery AJAX but still to write the data to a file you will require the server-side. Here
$.ajax({
  url: 'url/where/file_is.txt'
});

And the in page, you will have the server-side code which will

*

*Get the array data

*Split it relatively

*Write it to the file.
This way you will have the user's data written to the file.
For more: http://www.asp.net/web-pages/tutorials/files,-images,-and-media/working-with-files
If you're using PHP, you can do a Google search for that!


text:
Q: get "error :lvalue required as left operand of assignment " when set value for register I can't not solve this problem. I don't understand why. Here is my simple code
mjpeg.h:
    #define START_REG                 (*(volatile unsigned int*) BASE+0x000)
    #define MJPEG_PIC_START_RD                                  (0x00000001)

mjpeg.c:
    void encStreamInit(void){
    START_REG |= MJPEG_PIC_START_RD;
    }

test.c:
    int main(void){
     encStreamInit();
     return 0;
    }

It get "error: lvalue required as left operand of assignment" when compiling.
Please help me. Thank for your help.

A: Your code does not make any sense. Prefix * has higher operator precedence than binary +. Thus (*(volatile unsigned int*) BASE+0x000)  will get interpreted as this:

*

*I assume BASE is an int or unsigned int.

*Cast BASE to the type (volatile unsigned int*).

*Take the contents of that pointer. The result is an unsigned int.

*Add the value 0x0000 to that result. The result is of type unsigned int.

*Since this result is not a lvalue, you cannot use |= on it.

The fix is simple:
(*(volatile unsigned int*) (BASE+0x000))

A: START_REG gets expanded to (*(volatile unsigned int*) BASE+0x000) so you can not call  |= on it. What you do is the same as (a+1) |= 2 - a + 1 is temporary, you can not use it for |=.
EDIT: maybe the problem you have is that you meant to |= the value pointed by the adress. To achieve this, move the asterisk out of the brackets in the START_REG macro:
#define START_REG                 *((volatile unsigned int*) BASE+0x000)

A: What about:
mjpeg.h:
    volatile unsigned int * START_REG = BASE+0x000; /* BASE needs to be #define here- */
    #define MJPEG_PIC_START_RD                                  (0x00000001)

mjpeg.c:
    void encStreamInit(void){
    (*START_REG) |= MJPEG_PIC_START_RD;
    }

A: When you use define, it will just make a substitution of text. What it will not do, is defining a variable. In your case, you want to use those constants as variables and use operator between them.
a |= b

is equivalent to
a = a | b

So this means you use OR operator for your constants and try to assign the result to START_REG constant, which is not applicable.


text:
Q: Combine Table with DateObject I am trying to implement Table with a DateObject with the goal to obtain a series of increasing dates:
Table[
 DateObject[Today],
 {DateRange[Today, DatePlus[Today, Quantity[5, "Days"]]]}
]

The problem is that I obtain the same DateObject instead of increasing days:
{DateObject[{2020, 12, 29}, "Day", "Gregorian", 1.],
 DateObject[{2020, 12, 29}, "Day", "Gregorian", 1.],
 DateObject[{2020, 12, 29}, "Day", "Gregorian", 1.],
 DateObject[{2020, 12, 29}, "Day", "Gregorian", 1.],
 DateObject[{2020, 12, 29}, "Day", "Gregorian", 1.],
 DateObject[{2020, 12, 29}, "Day", "Gregorian", 1.]}

How can I obtain a series of increasing days with Table?

A: If you insist on Table:
Table[
  i,
 {i, Today, DatePlus[Today, Quantity[5, "Days"]], Quantity[1, "Days"]}
]

But as Rohit mentioned in their comment, you don't need Table at all. This is literally what DateRange is for:
DateRange[Today, DatePlus[Today, Quantity[5, "Days"]]]

Both produce the same result:
{DateObject[{2020, 12, 29}, "Day", "Gregorian", -6.],
 DateObject[{2020, 12, 30}, "Day", "Gregorian", -6.],
 DateObject[{2020, 12, 31}, "Day", "Gregorian", -6.],
 DateObject[{2021,  1,  1}, "Day", "Gregorian", -6.],
 DateObject[{2021,  1,  2}, "Day", "Gregorian", -6.],
 DateObject[{2021,  1,  3}, "Day", "Gregorian", -6.]}


text:
Q: What is difference in memory address and Java HashCode

Even if you have two different strings with the same value, they will have the same hashcode.

In the below example HashCode is the same? But the memory address is the same? How I can get it in java.

jshell> var a = new String("Ranga")
a ==> "Ranga"
jshell> var b = new String("Ranga")
b ==> "Ranga"
jshell> a.hashCode()
$31 ==> 78727449
jshell> b.hashCode()
$32 ==> 78727449
jshell> a == b
$33 ==> false

A: If you want to see the original hashCode for the String before it was altered you can do this:
String foo = ...some string
System.out.println(System.identityHashCode(foo));

According to the documenation for the hashCode

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)


text:
Q: Visual Studio/.NET 6.0 User Secret File and Seeding Data via EntityFrameworkCore I am getting myself familiar with using the User Secrets feature for keeping sensitive data protected.
My DB context inherits from the IdentityDBContext and is a separate project from my WebApi project.
How do I go about seeding data (ie: the administrative user and related roles) when I store that info in the secrets.json file? Is there a pattern for this?
Thank you for your help!


text:
Q: Removing JSON children by key in PHP My goal is to have a function that can remove a specified json child, which could also be nested inside deeper.
My function looks like this:
private function removeJsonChild(String $jsonKey, String $jsonString)
{
    $json = json_decode($jsonString, true);
    $arr_index = array();

    foreach ($json as $key => $value) {
        if (is_array($value)) {
            $json[$key] = $this->removeJsonChild($jsonKey, json_encode($value));
        }

        if ($key == $jsonKey) {
            $arr_index[] = $key;
        }
    }

    foreach ($arr_index as $i) {
        unset($json[$i]);
    }

    return json_encode($json);
}

The function would work if i wouldn't check if a $value is an array and then call the function again recursively. But there is the problem i think. In the statement where i assign the return value of the function to $json[$key]. What am i doing wrong?
EDIT: definitely forgot a json_decode. New code looks like this:
private function removeJsonChild(String $jsonKey, String $jsonString)
{
    $json = json_decode($jsonString, true);
    $arr_index = array();

    foreach ($json as $key => $value) {
        if (is_array($value)) {
            $json[$key] = json_decode($this->removeJsonChild($jsonKey, json_encode($value)));
        }

        if ($key == $jsonKey) {
            $arr_index[] = $key;
        }
    }

    foreach ($arr_index as $i) {
        unset($json[$i]);
    }

    return json_encode($json);
}

EDIT2:
The function works now, however it slightly changes the json schema.
An JSON like this:
[
  {
    "id": 1,
    "name": "oyzadsaigny647"
  }
]

now becomes this:
{
  "1": {
    "id": 1,
    "name": "oyzadsaigny647"
  }
}

A: private function removeJsonChild(String $jsonKey, String $jsonString) {

   $data = json_decode($jsonString, true);

   $data = $this->removeKeyFromArray($key, $data);

   return json_encode($data);

}

private function removeKeyFromArray(String $deleteKey, array $data) {

  unset($data[$deleteKey]); // No need to check if it exists, it just does nothing in that case

  foreach($data as $key => value) {
    if(is_array($value)) {
        $data[$key] = $this->removeKeyFromArray($deleteKey, $value);
    }
  }
  return $data;
}

NOTE: this will work in case of dictionaries, i.e. array with actual keys. If you have a plain array such as [1, 10, 23, 15] the unset behaviour is wrong, as pointed out by @deceze♦


text:
Q: PHP run SQL result in another SQL statement Is this possible? I need to run the result of one sql statement into another..
$result= mysqli_query($dbconn,"Select max(cartid) from cart;");
$row = mysqli_fetch_assoc($result);

$sql1 = "insert into cart(cartid) values('".$row['max(cartid)']."');";
mysqli_query($dbconn,$mysql1);

EDIT:
Added in my sql tables to show a better example of what im trying to do
This is my cart table
This is my transaction table

Basically I want to transfer the row where cartid = 5 from cart table, into the transaction table where the new transaction id will be = 5. As you can see, the transaction table also has a cartid. Not sure how im going to bring over this cartid and insert into the transaction table as a new row. FYI, in order to get cartid=5 i would like to use
order by cartid desc limit 1 to get the last possible row in the cart table
The new transaction table's row will look something like this.
transactionid outletid nric cartid transactiondate totalbeforediscount totalafterdiscount transactiontime username
     5           0      0     5         0                 0                       0                 0            0

A: You can combine the queries into one.
Please give it a try:
INSERT INTO cart(cartid) SELECT MAX(cartid) FROM cart
WORKING DEMO
EDIT:
In order to insert mulitiple values like that your query would look like below:
INSERT INTO cart(cartid,rowid) SELECT MAX(cartid),MAX(rowid) FROM cart
WORKING DEMO
But I don't understand why are trying to insert the columns having max value in the same table. Since your table contains those already.
Edit2:
INSERT INTO transaction_table(cartid) SELECT MAX(cartid) FROM cart;


text:
Q: IIS service is running as Local System account, so how do I give it shared directory permissions? My ASP page reads a file from a shared directory and sends it to the user.
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition:", string.Format("attachment; filename={0}", fileName));
        Response.WriteFile(filePath);
        Response.End();

This ASP code runs on the web server, I suppose it is running as Local System account because IIS is. filePath points to a file on the file server \\fileserver\shared\abc.pdf
When I debug the code on my local machine, the file is read correctly from ASP page. However when I run it on the web server, it can not read the file. What permission do I need to give \fileserver\shared so that the ASP page will correctly read the file? Obviously Local System is not a valid user logon in the permission page.

A: IIS by default runs it's application pools as "Network Service". This is a local account on the IIS box. If you want to access a network share then you need to reconfigure the application pool identity to an account with has access to the share, for example a domain account.
If both boxes are not in a domain then you can create a username and password on both machines (identical on both machines) and use that for the application pool, setting the permissions on the share to allow access by that (local) user on the fileserver

A: You may try to impersonate with a user allowed to access the share. Add this in your web.config:
<identity impersonate="true" userName="accountname" password="password" />


text:
Q: What is bluetooth le multi advertising? I couldn't find a clear explanation what  is Bluetooth le multi advertising.
For example, in Specification of the Bluetooth System, I see only
description of BLE advertising but not multi advertising.
What the difference between BLE advertising and multi advertising?
Thanks

A: LE Multi advertising refers to a specific offload (non bluetooth specification) feature that has been implemented in the Android releases by Google, starting from the L release.
What multi advertising means is, that your Android phone or a device with Android stack, can enable multiple advertisement trains at the same time. For instance, one specific app can set certain advertisement data (example supported services etc.), advertisement parameters and enable advertisement, and so can N number of other apps, on the same device.
At the hardware level (or physical layer), these advertisement trains are interleaved between the three advertisement channels (37, 38, 39) and thus your phone behaves as multiple peripheral devices at the same time. All these advertisement trains also have a separate Random private address, so they are seen distinctly by the remote scanner.

A: Bluetooth Smart has two ways of communicating. The first one is using advertisements, where a BLE peripheral device broadcasts packets to every device around it. The receiving device can then act on this information or connect to receive more information. The second way to communicate is to receive packets using a connection, where both the peripheral and central send packets. We will focus on advertisement for several reasons:
You can't create a connection between two devices without using advertisements. Defining the data and format of advertisement packets is usually the first thing you work on when developing a BLE device.
A large number of BLE products sleep most of the time, waking up only to advertise and connect when needed. This means advertisements have a big impact on power consumption.
Users want responsive products, and the advertising interval is critical in quick connections.
Advertising is by design unidirectional. A Central device can't send any data to the Peripheral device without a connection. But a single peripheral can advertise to multiple masters in the area.
ref:http://www.argenox.com/bluetooth-low-energy-ble-v4-0-development/library/a-ble-advertising-primer/


text:
Q: What is Plo Koon's real face? Everyone has a face behind their mask, even Vader. What is Plo Koon's? Has anyone ever seen it, behind those eye-patches and breathing apparatus?

A: Assuming you're happy with an out-of-universe image, this is character actor Alan Ruscoe in his makeup, but without his trademark mask covering his mouth and eyes.

Interestingly, the Star Wars Databank article on Plo Koon used to contain an image with just his breather, however this appears to have now been removed.

A: He hasn't been shown without his mask in the new canon, but we have seen his bare face in Legends.
From Star Wars: Purge: Seconds to Die:

A 2010 action-figure gives him the same appearance.


text:
Q: Parse excel document string without file path in ruby Is there a way or a gem to parse an xlsx document string without having a file? I was using Roo to parse the excel file when it was on my local machine but I would like to do it without downloading the actual document. I receive it in my google mailbox, and can pull the excel document string but can't find any way to parse just the string without a file path. Any ideas would be appreciated.

A: You can not parse a file without supplying it to your parser.
So at one point or another you will have to download the file, so that the parser has anything he can read for parsing.

A: You should be able to wrap your string in a StringIO object that will expose a similar API as File objects. Unfortunately, it looks like Roo has a lot of file handling built in to the various classes, and expects a pathname in the initialize method. As I see it you have a few options:

*

*Subclass one of Roo's spreadsheet classes to override the file handling, and substitute in your StringIO object.

*Save the string to a Tempfile and pass the temporary path into one of Roo's standard initializers (I suspect this would be easier to implement).


text:
Q: how to change vector elements by passing them to a function I've got a c++ exam coming up soon, so I decided to study by writing a random program that would implement most of the material that's been covered in the class so far. What I came up with is a program that reads numerical data from an input file, copies it to a vector, performs a few calculations via a few custom functions, sorts the vector from lowest value to highest, and displays the data in standard output.
Everything works fine, except for the sorting function. I can't seem to figure out how to change the values of a vector. When running the program the vector elements stay in their original order. I'm pretty sure I need to reference the vector in order for the function to be able to change the actual data, but I can't figure out how to do so properly.
Here's the code (it requires a file named "input.txt" to work) :
https://pastebin.com/5Q8GP3mY
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;
void icountSumAvg(vector<double>, int, int &icount, double &sum, double &avg);
void display(int, double, double);
void display(int, double, double, vector<double>, int);
void swap(vector<double>, int);

int main()
{
    ifstream ifile;
    const string FILENAME = "input.txt";
    ifile.open(FILENAME);
    int count = 0;
    double sum = 0, avg = 0;
    if (!(ifile.fail()))
    {
        bool testSwap = true; // displays each element if true
        vector<double> vect;
        double value = 0.0;
        while (!ifile.eof())
        {
            ifile >> value;
            vect.push_back(value);
        }
        int vectSize = vect.size();

        icountSumAvg(vect, vectSize, count, sum, avg);

        if (testSwap == true)
        {
            swap(vect, vectSize);
            display(count, sum, avg, vect, vectSize);
        }
        else
            display(count, sum, avg);

        ifile.close();
    }
    else
        cout << "There was an error opening the file: " << FILENAME << endl;
    system("pause");
}

void icountSumAvg(vector<double> values, int size, int &icount, double &sum, double &avg)
{
    for (int i = 0; i < size; i++)
    {
        icount++;
        sum += values[i];
    }
    avg = sum / icount;
}

void swap(vector<double> values, int size)
{
    double temp;
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if (values[j] < values[i])
            {
                temp = values[i];
                values[i] = values[j];
                values[j] = temp;
            }
        }
    }
}

void display(int count, double sum, double avg, vector<double> values, int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << "Element " << i + 1 << ": " << values[i] << endl;
    }
    cout <<"Total count:        " << count << endl
        << "Total sum:          " << sum << endl
        << "Average of numbers: " << avg << endl;
}

void display(int count, double sum, double avg)
{
    cout <<"Total count:        " << count << endl
        << "Total sum:          " << sum << endl
        << "Average of numbers: " << avg << endl;
}

A: You're swap() function is only modifying the vector copied to the function. Send the vector by reference to the swap() function to get the desire effect. This will avoid extra copying also.
Since icountSumAvg() and display() is not supposed to modify the vector parameter, declare them as const reference too like so:
void swap(vector<double>&, int);
void icountSumAvg(const vector<double>&, int, int &icount, double &sum, double &avg);
void display(int, double, double, const vector<double>&, int);

A: In the swap function, the values function doesn't receive a pointer/reference to the vector object, therefore accepting a copy of the object, and as the method is void you are just changing the value of the copy not the object itself.


text:
Q: Emacs org-mode: specify raw area for HTML exporter I have a problem when exporting org-mode buffers to html. The following table is not properly exported:
|-------+----------------+----------|
| HOST  | DB             | COMMENTS |
|-------+----------------+----------|
| rhea  | numbering_test |          |
| rhea  | phones         |          |
| dione | phonenumbers   |          |
| dione | numbering_test |          |
|-------+----------------+----------|

The problem is that the underscore tells the HTML exported to use subscripts. This is not what I want. I want numbering_test to appear like normal text.
The same problem when using those kind of identifiers embedded inside normal text, like this:
The numbering_test database is too big.

Again the same problem with the HTML exporter.
Is there a way to tell the HTML exporter to put some text in raw mode, as provided, without adding extra HTML formatting to it?
Markdown (as used here in StackOverflow) has the very useful backticks to embed raw code inside normal text. I need something similar for org-mode.

A: There are directives for org-export so it ignores the underscore as a subscript.
http://orgmode.org/manual/Export-options.html#Export-options
The one you are interested in is
#+OPTIONS:     ^:nil

which instructs the exporter to only sub/superscript text within explicit {...} brackets.
You can insert the whole template via the export dispatcher: C-c C-e t. Then you change/remove as will, and C-c C-c to refresh settings.


text:
Q: Amazon Rekognition for Video - getFaceSearch: index number I'm new using Amazon Rekognition to analyze faces on a video.
I'm using startFaceSearch to start my analysis. After the job is completed successfully, I'm using the JobId generated to call getFaceSearch.
On my first video analyzed, the results were as expected. But when I analyze the second example some strange behavior occurs and I can't understand why.
Viewing the JSON generated as results for my second video, completely different faces are identified with the same index number.
Please see the results below.
{
    "Timestamp": 35960,
    "Person": {
        "Index": 11,
        "BoundingBox": {
            "Width": 0.09375,
            "Height": 0.24583333730698,
            "Left": 0.1875,
            "Top": 0.375
        },
        "Face": {
            "BoundingBox": {
                "Width": 0.06993006914854,
                "Height": 0.10256410390139,
                "Left": 0.24475525319576,
                "Top": 0.375
            },
            "Landmarks": [
                {
                    "Type": "eyeLeft",
                    "X": 0.26899611949921,
                    "Y": 0.40649232268333
                },
                {
                    "Type": "eyeRight",
                    "X": 0.28330621123314,
                    "Y": 0.41610333323479
                },
                {
                    "Type": "nose",
                    "X": 0.27063181996346,
                    "Y": 0.43293061852455
                },
                {
                    "Type": "mouthLeft",
                    "X": 0.25983560085297,
                    "Y": 0.44362303614616
                },
                {
                    "Type": "mouthRight",
                    "X": 0.27296212315559,
                    "Y": 0.44758656620979
                }
            ],
            "Pose": {
                "Roll": 22.106262207031,
                "Yaw": 6.3516845703125,
                "Pitch": -6.2676968574524
            },
            "Quality": {
                "Brightness": 41.875026702881,
                "Sharpness": 65.948883056641
            },
            "Confidence": 90.114051818848
        }
    }
}

{
    "Timestamp": 46520,
    "Person": {
        "Index": 11,
        "BoundingBox": {
            "Width": 0.19034090638161,
            "Height": 0.42083331942558,
            "Left": 0.30681818723679,
            "Top": 0.17916665971279
        },
        "Face": {
            "BoundingBox": {
                "Width": 0.076486013829708,
                "Height": 0.11217948794365,
                "Left": 0.38680067658424,
                "Top": 0.26923078298569
            },
            "Landmarks": [
                {
                    "Type": "eyeLeft",
                    "X": 0.40642243623734,
                    "Y": 0.32347011566162
                },
                {
                    "Type": "eyeRight",
                    "X": 0.43237379193306,
                    "Y": 0.32369664311409
                },
                {
                    "Type": "nose",
                    "X": 0.42121160030365,
                    "Y": 0.34618207812309
                },
                {
                    "Type": "mouthLeft",
                    "X": 0.41044121980667,
                    "Y": 0.36520344018936
                },
                {
                    "Type": "mouthRight",
                    "X": 0.43202903866768,
                    "Y": 0.36483728885651
                }
            ],
            "Pose": {
                "Roll": 0.3165397644043,
                "Yaw": 2.038902759552,
                "Pitch": -1.9931464195251
            },
            "Quality": {
                "Brightness": 54.697460174561,
                "Sharpness": 53.806159973145
            },
            "Confidence": 95.216400146484
        }
    }
}

In fact, in this video, all faces have the same index number, regardless of they are different. Any suggestions?

A: PersonDetail object is the result of the API . "index" is the identifier for the person detected in the video. So the index doesn't span across videos. It is just an internal reference.
Link below which details Index
https://docs.aws.amazon.com/rekognition/latest/dg/API_PersonDetail.html


text:
Q: Java - Differentiate ZIP file from CSV file I'm using a webservice that is always sending me a plain/text file. However, that file can either be a zip or a csv but I'm not being informed of its type beforehand.
Is there a way to know the file type by looking through its content programmatically wise of course. As one is in byte code and the other one an actually readeable text.
I've already thought of looking for lots of commas in the file content but that seems inaccurate.

A: You can use java.util.zip.ZipFile, if the constructor throws a ZipException, it's not a zip file...
try(ZipFile zip = new ZipFile(filename)) {
    // It's a zip file
}
catch(ZipException e) {
    // Not a valid zip
}

A: You could make use of the ZIP file structure.
As per the file header, each file should start with the bytes: 0x04 0x03 0x4b 0x50.
You could also use a MIME detection library such as Apache Tika    import org.apache.tika.Tika;
    import org.apache.tika.mime.MediaType;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Detect {

    /**
     * Resolves the MediaType using Tika and prints it to the standard output.
     * @param file the path of the file to probe.
     * @throws IOException whenever an I/O exception occurs.
     */
    private void detect(Path file) throws IOException {
        Tika tika = new Tika();
        try(InputStream is = Files.newInputStream(file)){
            MediaType mediaType = MediaType.parse(tika.detect(is));
            System.out.println(mediaType);
        }
    }

    public static void main(String[] args) throws IOException {
        Detect d = new Detect();
        d.detect(Paths.get("zip_file"));
        d.detect(Paths.get("csv_file"));
    }
}


text:
Q: User input via cin.getline I wrote a code where user is asked to input a line of text up to 132 characters (Array size is 133 for \0 at the end of the array).
I have used while loop to catch if the user did not input anything and hit return.
#include <iostream>
using namespace std;

const short SIZE = 133;

int main()
{
    char InputArray[SIZE];
    cout << "Enter a line of text up to 132 characters: " << endl;
    cin.getline(InputArray, SIZE);
    count = strlen(InputArray);

    while (count == 0)
    {
        cout << "You did not enter any entry! Try again." << endl;
        cout << "Please enter a line of text up to 132 characters.: " << endl;
        cin.getline(InputArray, SIZE);
        count = strlen(InputArray);
    }

cout << "You had entered: " << InputArray << endl;
cout << "The character count was: " << count << endl;

system ('pause');

return 0;
}

How can I catch the user if they go over the size of the array? and generate a text of message saying user input was invalid and ask them to cin.getline again?
Thank you!

A: You may use the get function. Please see here. This will read only as much input as you want.
Example:
#include <iostream>

constexpr size_t numberOfBytes = 6;

int main() {

    std::cout << "\nPlease enter up to " << numberOfBytes-1 << " characters:  ";
    char data[numberOfBytes];
    std::cin.get(data, numberOfBytes);

    std::cout << "\nEntered: " << data << "\n";
    return 0;
}

If you want to read any number of charcters and then check the size afterwards, then use a std::string. You should do anyway.
So:
std::string s{};
std::cin >> s;
if (s.length() > ....) {
....
}


text:
Q: Android keyboard doesn't show in Chrome when  is focus() I am working on a website where the first action of the user is entering text.
I can focus() the <input> element, but the keyboard doesn't show up in Chrome (86) on Android (11). I found answers mentionning click() but it doesn't change anything.
My code is below.
Thank you very much for your help.

<html>

<head>
</head>

<body>
<input/>
<script>
window.onload = e => {
  let input = document.querySelector("input");
  input.focus();
  input.click();
};
</script>
</body>

</html>

Note however that if I have the following div, it works when I click on it: <div onclick='document.querySelector("input").focus()'/>
Does it mean that the keyboard cannot be shown outside a user driven event?


text:
Q: .env is not being detected in Django I have done pip install python-dotenv and then created a .env file in the same folder as the settings.py. The values from the .env is not working.
settings:
SECRET_KEY = os.environ.get('SECRET_KEY')

.env file:
SECRET_KEY=mysecretkey

What should I do?


text:
Q: Одностраничный сайт на html Скажите, пожалуйста.
Сделал на сайте две формы для имени и адреса. И кнопку сабмит.
Вопрос 1. Как сделать так, чтобы при нажатии кнопки имя и фамилия сохранялись на этой же странице?
Вопрос 2: Можно ли сделать так, чтобы все данные на странице очищались в определенное время?

A: Данные можно сохранить на странице при помощи JS, но они в любой момент они могут быть утеряны, да и видеть их будет только человек добавивший их.(т.к. сохранены они на клиентской стороне, браузере пользователя)
Чтобы сохранять и выводить необходимые Вам данные, вам нужна серверная сторона.
Т.е.
Клиент <=> HTML страница <=> Сервер
Нужно чтобы при клике на кнопку, данные отправлялись на сервер, после чего там обрабатывались и сохранялись. В последующем Вы сможете делать с этими данными все что только захотите. Но средствами HTML этого не добиться.

A: Ну а вот простенькая реализация на js, так как думаю, что автор не о сервере речь вел.

var message;

function letsdoit() {
var fname = document.getElementById('fname');
var lname = document.getElementById('lname');
message = document.getElementById('welcomemess');
var ticks = document.getElementById('ticks').value;
message.innerHTML = "Привет, " + fname.value + " " + lname.value;
setTimeout(ticktock, 1000*ticks);
}

function ticktock() {
message.innerHTML='';
}

<input id="fname" placeholder="Имя">
<input id="lname" placeholder="Фамилия">
<input id="ticks" placeholder="Секунд до скрытия">
<button onclick="letsdoit()">Отправить</button>

А вообще, да, конечно сервак
UPD: Добавил очищение данных спустя заданное количество секунд

A: Можно хранить заполненные данные в браузере посетителя. Разумеется, они будут видны только ему. Другие посетители страницы будут иметь дело каждый со своими данными. Иначе нужен общий сервер.
Пример использует localStorage и сохраняет заполненные данные, даже если браузер закрыть. В песочнице SO не работает, вот работающая копия на jsFiddle.

var people = []
  ,saved = localStorage.getItem("people")
  ,in_name = document.getElementById('in-name')
  ,in_addr = document.getElementById('in-addr')
;

if( saved) {
  people = JSON.parse(saved);
  render();
}

document.getElementById('btn-save').addEventListener(
  'click',
  function(){
    people.push({
      name: in_name.value,
      addr: in_addr.value
    });
    localStorage.setItem("people", JSON.stringify( people));
    render();
  }
);

function render() {
  var div = document.getElementById('out'), i, html = '', p;
  for( i=0; i<people.length; i++) {
    p = people[i];
    html += '
'+p.name+'

'+p.addr+'
';
  }
  div.innerHTML = html;
}
<link href="https://yastatic.net/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<input id="in-name" type="text" name="name" placeholder="Ваше имя">
<input id="in-addr" type="text" name="addr" placeholder="Адрес">
<button id="btn-save">Сохранить</button>

A: Можно сохранять в сессии или куки, например.
Когда нажимается на кнопку, отправляется запрос скрипту-обработчику.
Принимайте им данные из нужных полей, например, так:
if(isset($_POST['name']) && !empty($_POST['name'])) {
    $_SESSION['input_name'] = $_POST['name'];
}

А при загрузке страницы:
$name = "";
if(!empty($_SESSION['input_name'])) {
    $name = $_SESSION['input_name'];
}

Только сайт уже не на html получится, а на php.
Можете, конечно, использовать библиотеку jquery-cookie, с ее помощью сохранять данные в cookie и так же при генерации страницы проверять наличие содержимого полей в них, но уже средствами jquery.


text:
Q: How to avoid fetching the source jar from a flatDir dependency with Gradle I have a Gradle build script, with mixed Maven dependencies (I use Maven Central for dependencies resolution) and a local directory. The snippet is this:
repositories {
    mavenCentral()

    flatDir name: 'directoryRepository', dirs: 'tools/libs'
}

Then I need to declare my local dependencies this way:
dependencies {
    compile ":commons-cli:1.0@jar"
}

I cannot use the files('...') notation (because other parts of the script would fail with a class cast exception from Array to HashMap, and I cannot change that part).
The jar files are added to the build path correctly. The problem is that Gradle wants to fetch, for every jar in the 'tools/libs', another '-source' jar.
Indeed, if I have in the tools/libs folder:
commons-cli-1.0.jar
commons-cli-1.0-sources.jar

all works fine. If I remove the source jar, it gives the error "unable to resolve dependency", poiting out the -source jar.
I have more then 50 files to be managed this way, and of course I haven't the source jars (nor I'm interested to have).
How can I exclude the source jar fetching?
Many thanks in advance for any hints.
Fabio Da Soghe

A: If you are using IDEA there's a module-wide setting ideaModule.downloadSources = false which can help, but it will disable all source downloading for IDEA.
Not sure what you meant by files(...) notation, but how about trying this?:
dependencies{
  ...
  compile fileTree( dir: "toos/lib", include: '*.jar' )
  ... or ...
  compile fileTree( dir: "toos/lib", includes: ['*.jar'] )
}

Edit:
There appears to be an associated bug report, fixed in milestone 5. Giving it a try revealed that the error is still there but now it's just a warning and the build will succeed. Apparently the warning is coming from Ivy so there is no easy fix for it :(


text:
Q: See SOAP/XML returned by WCF Say I have the standard Service.svc deployed like this:
public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

and a client like this:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        ServiceReference1.Service1Client s1 = new ServiceReference1.Service1Client();
         string str = s1.GetData(1);

    }
}

The web service returns the following text to the str variable (as expected): "You entered: 1".  How do I see the SOAP/XML that was generated?
I realise I could use Fiddler, however I want to see it in .NET i.e. returned to the str variable..

A: One of the main benefits WCF has to offer is abstracting you from any serialization/transport issues. Since your service contract returns CompositeType you get an instance of it automatically reconstructed from the underlying XML message on the client side.
However, if you want to get a raw XML you can still do that by performing direct call depending on what transport is supported by your WCF server. if it's basicHttpBinding/wsHttpBinding you can perform HTTP request and read a response which will be pure XML. Of course, all the dirty work like authentication and security is on you.
If you need this just for debugging/studying purposes you can enable message logging or use standard WcfTestClient.exe utility.


text:
Q: firefox window thumbnails not showing from Favorites icon I have launched firefox and have several windows open. At one time, I could right-click on the firefox icon in the Favorites bar and I can click on "All Windows" and I would see thumbnail images of all the windows, in a single row, and I could click on one to bring that window forward.
Now, when I right-click on the firefox icon and click on "All Windows", I see, at the very top of the screen, a few pixels of a picture. It is as if the pictures are being displayed above the actual window and I can only see 5 pixels of the bottom thumbnail.
How can this be fixed? Other than re-installing my system? I am running 20.0.4 and firefox is "Mozilla Firefox 103.0".
I would also like to extend the behavior of the context menu that one sees from the firefox icon in the Favorites bar. If anyone has coding suggestions, please speak up. Much thanx.

A: See what happens in full-screen mode f11 If you're using a version downloaded off of Mozilla.org, try the version that comes with your version of Ubuntu. If F11 works to see the thumbs, try moving the scroll bar to make the thumbs visible. Otherwise, after you click all windows, wait for a few seconds. Firefox sometimes hides parts of the screen until it's still for a few seconds, or scrolled to the top.


text:
Q: Google App Engine Over quota error The recommended way by Google to capture the over quota error when you run out of money on your credit card seems not to capture the error:
error_handlers:
    - error_code: over_quota
      file: over_quota.html
handlers:
- url: /_ah/queue/deferred
  script: djangoappengine/deferred/handler.py
  login: admin

- url: /test.*
  login: admin
  script: groupbuy/tests/gaeunit.py

- url: /_ah/stats/.*
  script: djangoappengine/appstats/ui.py

- url: /media/admin
  static_dir: django/contrib/admin/media
  expiration: '0'

- url: /static
  static_dir: groupbuy/static

- url: /robots.txt
  static_files: groupbuy/static/robots.txt
  upload: groupbuy/static/robots.txt

- url: /.*
  script: djangoappengine/main/main.py

It seems the error handler over_quota.html is not captured, what could be wrong in the urls or is it ordering?


text:
Q: The OutputPath property is not set for the C# project I got this error message while debug/recompiling a C# Project:

The OutputPath property is not set for project 'Example.csproj'.
Please check to make sure that you have specified a valid combination
of Configuration and Platform for this project.  Configuration='Debug'
Platform='x86'.  This error may also appear if some other project is
trying to follow a project-to-project reference to this project, this
project has been unloaded or is not included in the solution, and the
referencing project does not build using the same or an equivalent
Configuration or Platform.

I don't know what could be wrong in project configurations:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <PropertyGroup>
    <ProjectType>local</ProjectType>
    <ProjectVersion>7.10.377</ProjectVersion>
    <OutputPath>bin\x86\</OutputPath>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{E34FF2B3-527D-4006-B312-3D88C491ADBC}</ProjectGuid>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <AssemblyName>Example</AssemblyName>
    <OutputType>WinExe</OutputType>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\x86\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <GenerateSerializationAssemblies>On</GenerateSerializationAssemblies>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\x86\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>

Someone have an idea? Thanks in advance!

A: There are three methods you can try:

*

*Please delete the bin and obj folders in the project root directory then rebuild the program.

*Please place OutputPath before <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />. As follows:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
......
</PropertyGroup>
<PropertyGroup>
......
</PropertyGroup>
<PropertyGroup>
...
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
......
</ItemGroup>
</Project>

*Please check whether an uninstalled project is referenced. Deleting the offending reference can solve this problem.


text:
Q: Selenium IE special characters In my automation project I'm trying to register a user, it needs to work on Chrome, FF and IE.
It works proerly in Chrome and FF but not in IE. When I enter the email address:
setValue(emailField,"test@test.com");

IE changes "@" for "2" (in my keyboard the "@" and "2" are in the same key). I've being looking for an explanation but I couldn't find the reason why it changes it and in Chrome and FF it works perfectly, any ideas? Thanks!
setValue()
public static void setValue(WebElement element, String value) {

        String tagName = element.getTagName();

        //check if WebElement is input or textarea
        if(ConstantsFramework.INPUT.equalsIgnoreCase(tagName) || ConstantsFramework.TEXTAREA_MIN.equalsIgnoreCase(tagName) ) {
            // write value in field
            element.sendKeys(value);
        } else if (ConstantsFramework.SELECT.equalsIgnoreCase(tagName)) {
            // select element in combobox
            select(element, value);
        } else {
            throw new IllegalArgumentException(ConstantsFramework.ADD_CODE_TO_SET_VALUE_FOR + tagName + ConstantsFramework.CLOSE_BRACKET);
        }
    }

A: To type "@" in IE I must press the keys Control+Alt+2 (in my Spanish keyboard):

setValue(emailField, email_value.replace("@", Keys.chord(Keys.CONTROL,
  Keys.ALT, "2")));


text:
Q: Transfer a MySQL database from one AMPPS installation to a newer one I've just upgraded macos to Catalina and the version I had of AMPPS stopped working.
I've installed the newest one available, however the mysql database came empty (of course).
How can I move all tables and databases from the older AMPPS installation to the newer one? Runing the previous AMPPS installation in order to export as SQL isn't an option because Catalina won't run it :-(
In the old installation all tables are stored as .frm and .ibd files. I tried copying the var folder to the new AMPPS installation and it didn't work. Tried to merge the contents of the old var folder with the new one and it didn't work either.

A: I found out that the newer version of AMPPS came with MySQL 8, which is incompatible with MySQL 5.4, from the previous AMPPS version. I ended up losing the data from the previous database, which was not such a great problem because it was just test data from several apps in development.
Perhaps if I installed MySQL 5.4 on macos Catalina without AMPPS I would be able to copy the files from the previous AMPPS version and then export it to MySQL 8, but haven't really tried it.


text:
Q: if there is no electric field then any charge exists or not? If we assume a region of space in which there is no electric field, can we say that no electric charge exists?
I think that there is no electric charge particles to create electric field for this specific region of space, am I right?

A:
No, this is not true all the times for every region in space.
Take this example: If you have two charges with the negative charge. At the middle of the straight line that connects them, the electric field(the force) will be equal to zero because the force from the electric field of each charge will be equal in magnitude but they will have opposite direction at that point, so they will cancel out.
There is also an example where this happens to a bigger region in space. Say you have two plates, each of equal charge of the same sign. Then, between the two plates, the net electric field will be approximately zero.(approximately because at some points between the plates it is nearly zero for reasons that are not to be analyzed here).


text:
Q: Building a C++ project across different branches My project has more than 1000 files. In this let's say there is a file A.cpp & A.h. When I move to a new branch on my machine & I compile, it compiles everything including A.cpp  even though I had just compiled A.cpp on an old branch.
I heard some companies while downloading cpp files also downloads the corresponding .obj & .lib files, there by speeding up the compilation very fast .
Is this true? What is it called so that I can to incorporate it
I started with https://interrupt.memfault.com/blog/improving-compilation-times-c-cpp-projects but the ideas there are not on this line of thought.


text:
Q: How to match a sequence of events in Splunk? My SPL expertise are limited. I'm trying to write a search which matches a sequence of events.
I'm working with sysmon logs from a windows machine.
first event is a file creation event where Image ends with dllhost.exe and TargetFilename starts with *C:\windows\system32*. something like:
index=sysmon EventID=11 Image="*dllhost.exe" TargetFilename="C:\\windows\\system32\\*"
next event is an image load event where Image starts with *C:\windows\system32* and Signature does not start with the keyword "Microsoft ". something like
index=sysmon EventID=7 Image="C:\\windows\\system32\\*" Signature != "Microsoft *"
Value of TargetFilename in Event 1 must be equal to value of ImageLoaded  field in Event 2.
And Event 2 must occur within 1 minute of Event 1.
I tried inner join, where I join results based on TargetFilename from Event 1 and ImageLoaded  (renamed) from Event 2, But this solves only first part of the puzzle. I want both events to occur in a sequence i.e. join if Event 2 time is less than 1 minute of Event 1 time.  I don't know how to articulate this with SPL.
Also I'd nice if someone can show me how to do all this with tstats :)
Thanks

A: Consider using stats to group items by a field.
First, make a column that you can use for matching.
Make sure the match field is empty for anything you don't want to group.
Then use the stats command to group the events
| eval Match=case(EventID==11,TargetFilename,EventID==7,ImageLoaded)
| table Match EventID Image TargetFilename Signature ImageLoaded
| stats list(*) as * by Match

Here is a "run anywhere" example that makes the events and the joins them up
| makeresults
| eval _raw="
EventID Image                 TargetFilename         Signature ImageLoaded
11      dllhost.exe           C:\windows\system32\X  Microsoft IL
9       I                     TF                     S         IL
7       C:\windows\system32\I TF                     Apple     C:\windows\system32\X
"
| multikv forceheader=1 fields EventID Image TargetFilename Signature ImageLoaded

| eval Match=case(EventID==11,TargetFilename,EventID==7,ImageLoaded)
| table Match EventID Image TargetFilename Signature ImageLoaded
| stats list(*) as * by Match


text:
Q: How to solve [$injector:unpr] error for AngularJS? I have started learning AngularJS and facing issue while injecting a service which is in another file. I have tried many ways but nothing is working out.
This is my index.html:
` <!DOCTYPE html>

    <title>Employee Directory</title>
    <link type="text/css" rel="stylesheet" href="./../bootstrap.min.css" />

Employee Directory

                    Name
                    Email
                    Date of Birth
                    Department
                    Gender
                    Age

                    <form>

                            <input class="form-control" ng-model="employee.name" required placeholder="Name" />

                            <input type="email" ng-model="employee.email" required class="form-control" placeholder="abc@xyz.com" />

                            <input type="text" ng-model="employee.dob" id="datepicker" class="form-control" required placeholder="YYYY-MM-DD" />

                            <input ng-model="employee.department" required class="form-control" placeholder="Department" />

                            <input ng-model="employee.gender" required class="form-control" placeholder="Gender" />

                            <input type="number" ng-model="employee.age" disabled class="form-control" placeholder="Age" />

                            <button class="btn btn-primary btn-md" ng-click="vm.addEmployee()">Add Employee</button>
                            <button class="btn btn-info btn-md" ng-click="updateEmployee()">Update Employee</button>

                    </form>

`

This is my controller:
(function () {
    'use strict';

    angular.module('employeedirectory', [])
        .controller('homeController', ['homeService',homeController]);

    function homeController() {
        var vm = this;
        vm.addEmployee = function () {
            console.log("in add employee");

            // homeService.addEmployee();

        }
    }
})();

this is my service
(function () {
    'use strict';
    angular
        .module('employeedirectory')
        .service('homeService', homeService);

    function homeService() {
        // var service = {};

        // service.addEmployee = function (details) {
        //     console.log("in home service");
        // };
        // return service;
    }
})();

I am getting this error:
angular.min.js:123 Error: [$injector:unpr] http://errors.angularjs.org/1.6.4/$injector/unpr?p0=homeServiceProvider%20%3C-%20homeService%20%3C-%20homeController
    at angular.min.js:6
    at angular.min.js:45
    at Object.d [as get] (angular.min.js:43)
    at angular.min.js:45
    at d (angular.min.js:43)
    at e (angular.min.js:43)
    at Object.invoke (angular.min.js:43)
    at S.instance (angular.min.js:94)
    at n (angular.min.js:69)
    at g (angular.min.js:61)

A: you have to reference your service in the index.html

    <title>Employee Directory</title>
    <link type="text/css" rel="stylesheet" href="./../bootstrap.min.css" />

    //  .....

This way the controller will know what you are trying to inject.


text:
Q: How "==" works in JavaScript? I found == is little confusing for newbies, So I want someone to explain how it works.
For example -
new String("a") == "a" and "a" == new String("a") are both true.
new String("a") == new String("a") is false.

Why?

A: == is called comparison/equality operator, it compares 2 values, but not their data types so for example
1 == '1' will return true, for stricter comparison, use === which will compare the data types too so 1 === '1' will return false

A: == is a comparison operator that means "equal to" but does not take variable typing into account.
=== is a stricter comparison operator that means "equal to and same type".
So if you have a string called numberStr with a value of 2 and an integer called numberInt with a value of 2, they will evaluate as follows:
numberStr == numberInt  // evaluates to true
numberStr === numberInt // evaluates to false because types are different