text:
Q: Generics of SuperClass I'm trying to using generics with the reactive webclient, so far I've create a class that holds the webClient and some methods
    public class CustomWebClient<T> {

    private final WebClient webClient;

            public CustomWebClient(WebClient.Builder builder, ClientProperties properties) {
                String rootUrl = properties.getHttp().getRootUrl();
                webClient = builder
                        .baseUrl(rootUrl)
                        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                        .defaultHeaders(httpHeaders -> httpHeaders.setAll(properties.getHeaders()))
                        .build();
            }

     public Mono<ResponseEntity<T>> setRequest(final String uri,
                                               final HttpMethod httpMethod,
                                               final Class<T> classToMap) {
     WebClient.RequestHeadersSpec<?> requestHeadersSpec = webClient.method(httpMethod).uri(uri);
     WebClient.ResponseSpec responseSpec = setRetrievingOptions(requestHeadersSpec);
       return setEntity(responseSpec, classToMap);

  }

private WebClient.ResponseSpec setRetrievingOptions(final WebClient.RequestHeadersSpec<?> requestHeadersSpec) {
    return requestHeadersSpec.retrieve()
            .onStatus(HttpStatus::is4xxClientError,
                    clientResponse -> Mono.error(new ResponseStatusException(clientResponse.statusCode(), NOT_FOUND_MSG)))
            .onStatus(HttpStatus::is5xxServerError,
                    clientResponse -> Mono.error(new ResponseStatusException(clientResponse.statusCode(), INTERNAL_SERVER_ERROR_MSG)));
}

private Mono<ResponseEntity<T>> setEntity(final WebClient.ResponseSpec responseSpec, Class<T> classToMap) {
    return responseSpec.toEntity(classToMap);
}
 }

then I inject the CustomWebClient into another class which is a service
      public class ABCServiceImpl implements ABCService {

         private final CustomWebClient<? extends BaseResponse> customClient;

         private Mono<PageResponse> invokeGetPageFromABC(final String storeId, final String site, final MultiValueMap<String, String> queryParams) {
          Mono<ResponseEntity<PageResult>> responseEntityMono = customClient.setRequest(String.format(PAGE_ENDPOINT, site), HttpMethod.GET, queryParams, PageResult.class);

      return responseEntityMono.map(content ->
                    new ContentResponse(content.getStatusCode(), customWebClient.SUCCESS_MSG, createContent(content.getBody())));
        }

    private ContentDTO createContent(ContentResult contentResult){
        return Optional.ofNullable(contentResult)
                .filter(c -> Objects.nonNull(c.getContent()))
                .map(ContentResult::getContent)
                .orElse(new ContentDTO());
    }
}

at this point a get a compile time error which is
Required type: Class <capture of ? extends BaseResponse>
Provided: Class <ContentResult>

Here is the object I'm passing
public class ContentResult extends BaseResponse {

    private ContentDTO content;
}

Since I'm new with generics probably there is something I'm missing or I didn't fully understand. Any clue about what could be the problem?
Honestly I've expected to work given the fact that I've actually specified the super class while injecting the customWebClient.
Thank you in advance!

A: I've combed through this, and I think I understand what you're trying to do. I recommend not using the wildcard ("?") in this way. When you call customClient.setRequest(..), the compiler can't figure out what version of customClient you have (i.e. what subclass of BaseResponse), so it throws an error when you try to pass in the parameterized type Class object (which looks to be PageResult.class)
You could fix this by turning ABCServiceImpl into a parameterized class i.e.
ABCServiceImpl<T extends BaseResponse> with a field property of private final CustomWebClient<T extends BaseResponse> customClient;
But I still wouldn't do that either, because it looks like your custom client does not need to be a parameterized type at all!
So I'd recommend this:

*

*Remove the parameterized type from CustomWebClient. (i.e. public class CustomWebClient instead of public class CustomWebClient<T>)

*Make the public Mono<ResponseEntity<T>> setRequest(..) method a parameterized method instead: public <T> Mono<ResponseEntity<T>> setRequest(..)

*Call the method on customWebClient like so:
customWebClient.<ContentResult>setRequest(ContentResult.class, ...etc);


text:
Q: How to construct a grammar $G$ such that $L(G) = \{ a^nb^m|n \neq 2m,m,n \ge 0\} $? Construct a grammar $G$ such that $$L(G) = \{ a^nb^m|n \neq 2m,m,n \ge  0\}$$
My attempt:
I first constructed a grammar for the langugage $L(G_1) = \{ a^nb^m|n = 2m,m,n \ge = 0\}$,
$G_1 = (\{ S\}, \{a,b\},P,S) $ where $P$ consists of $S\to aaSb|\lambda$
For violating this condition, I modified the above as
$G = (\{ S,A,B\}, \{a,b\},P,S) $ where $P$ consists of $$S\to aaSb|A, A\to aBb, B\to aB|bB|\lambda$$
My question is this correct? If not where exactly I am going wrong?

A: Your grammar
\begin{align}
S &\to aSbb \mid A \\
A &\to aBb \mid A \\
B &\to aB \mid \lambda
\end{align}
does not work because of two issues. First, did you mean $\{a^{2m}b^{m}\}$ or $\{a^{n}b^{2n}\}$? Second thing is that in your grammar $\#b \leq 2\cdot\#a$, but $L$ should include words like $b^{123}$. What you could do is split the grammar into two:
$$L_1 = \{a^nb^m\mid n > 2m \geq 0\},$$
$$L_2 = \{a^nb^m\mid 0 \leq n < 2m\}.$$
Then $G_1$ would be
\begin{align}
S_1 &\to aaS_1b \mid A, \\
A &\to aA \mid a,
\end{align}
and $G_2$
\begin{align}
S_2 &\to aaS_2b \mid aB \mid B, \\
B &\to bB \mid b.
\end{align}
Some other (maybe more intuitive) $S_2$ could look like:
\begin{align}
S_2 &\to AAS_2b \mid Ab,\\
A &\to a \mid \lambda.
\end{align}
Hope this helps ;-)
Edit 1: I see that you fixed your grammar, but now you can create words like $ba$ which should not be in the language.
Edit 2: Expanded abbreviations into proper CFG and added second version of $S_2$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I set the style of an element to the values in a parent style sheet in a media query? I'm using the 960 Smart Grid to design a website. It's a mobile first grid system, and I'm having a bit of trouble. In order for the grid system to work, the padding-left element cannot change or it breaks, except in the default layout when everything is a single column.
I needed to adjust the padding for an element in the mobile view, which screws up the element when it's larger than the single-column view width (so greater than 768 px). I need to change the padding back to what the original smart-grid style sheet says, but I'm not sure how to do that.
I'm fairly new to this, I don't have the site live at the moment but I can share any code needed. I'm adjusting the padding on a paragraph element, set inside of a div element.

Sample Text.

Essentially, I need to set a 6% padding for the paragraph element in the mobile view. Once it reaches a minimu width of 768 pixels, I need to eliminate the 6% padding because it breaks the offset-two portion of the tag. The offset is achieved in the smart grid style sheet using a padding-left value based upon the screen size. I'd like to switch back to the default padding from the smart grid style sheet for all of the media queries, if possible. You can check out the basic grid documentation on the site I linked to at the beginning of the question.
Thanks for the help.

A: I'm not sure if I understood your problem, but it looks like you just need to overwrite the padding for when the browser is less than 768 pixels.
To do this, you just need to add, at the end of your main css (or in a new one, but called after the other one):
@media screen and (max-width: 768px) {
   .columns.eight.offset-two {
   padding: 6%;
   }
}

This means that this style will only be applied if the browser is smaller than 768px, and once it gets bigger, it will bring back the 'default' padding for your element. You don't need to specify the padding again for bigger resolutions,l because the second the browser gets past the number, it completely forgets about the media query (it's like it doesn't exist anymore). The only thing you need to keep in mind is, unless you set another smaller media query after this one, it will apply the 6% to all smaller sizes.
It's important that you keep your media queries at the end, because css is read from top to bottom, and the last style read will be the last applied.


text:
Q: Is there an official interface to TOrderedListEditDlg? In an expert, I'd like to re-use the dialog that Delphi displays to edit a project's library path and for similar purposes:

I found a hack for using it (look for TOrderedListEditDlg on the page). As I think the guy who wrote the linked article knows what he does I don't have too much hope for a less hacky solution, but who knows... So: Do you know an official interface (most probably OTA) to TOrderedListEditDlg?
PS: I'm aware that it's probably trivial to recreate the whole dialog but I like consistency and the DRY principle.

A: You're right, I couldn't find an official way, that's the only reason I used this hack.
BTW, check out the INTAEnvironmentOptionsServices and INTAAddInOptions interfaces mentioned here. You can incorporate your configuration in Delphi's Environment Options treeview. But TOrderedListDlg still doesn't seem to be exposed officially.


text:
Q: OROCRM Nginx Virtual Host Configuration Not Working I have installed a orocrm on a AWS Lightsail VPS with Nginx & PHP7. orocrm installed without a hitch but I'm using Nginx for the first time and my virtual host doesn't seem to be working.
sites-available/default:
    server {
            listen 80 default_server;
            listen [::]:80 default_server;
        root /var/www/html;
        index app.php index.php index.html;
        server_name 34.127.224.10;

        location / {
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                fastcgi_pass   unix:/run/php/php7.0-fpm.sock;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
                include        fastcgi_params;
        }

        location ~ /\.ht {
                deny all;
        }
}

I then purchased & pointed crmdomain.com to my instance and created another file.
sites-available/crm:
server {
        listen 80;
        server_name crmdomain.com www.crmdomain.com;
        root /var/www/html/crm/web;

        index app.php;

        error_log /var/log/nginx/orocrm_error.log;
        access_log /var/log/nginx/orocrm_access.log;

        location = /favicon.ico { access_log off; log_not_found off; }
        location = /robots.txt  { access_log off; log_not_found off; }

        location @rewrite { rewrite ^/(.*)$ /app.php/$1; }

        location / {
                try_files $uri /app.php$is_args$args;
        }

        location ~ [^/]\.php(/|$) {
                fastcgi_split_path_info ^(.+?\.php)(/.*)$;
                if (!-f $document_root$fastcgi_script_name) {
                        return 404;
                }
                fastcgi_index app.php;
                fastcgi_read_timeout 10m;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }
}

I honestly don't know most of what is above, it's mostly based on tutorial and apache experience.
Errors
Domain based
 - crmdomain.com -> 403 Forbidden nginx/1.10.0 (Ubuntu)
 - crmdomain.com/app.php -> No input file specified.
 - crmdomain.com/app_dev.php -> No input file specified.
 - crmdomain.com/index.nginx-debian.html -> Welcome to nginx!
 - crmdomain.com/user/login -> 404 Not Found nginx/1.10.0 (Ubuntu) **This is what should word**

Static IP based
 - 34.127.224.10 -> 403 Forbidden nginx/1.10.0 (Ubuntu)
 - 34.127.224.10/crm/web/ - No input file specified.
 - 34.127.224.10/crm/web/app.php - No input file specified.
 - 34.127.224.10/crm/web/app_dev.php - No input file specified.
 - 34.127.224.10/index.nginx-debian.html -> Welcome to nginx!
 - 34.127.224.10/crm/web/app.php/user/login -> 404 Not Found nginx/1.10.0 (Ubuntu) **This is what should word**

What am I doing wrong?

A: It's weird how often I answer my own questions:
I was able to change the default files and remove the extra virtual host. Since the server was only going to host the one app.
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        server_name 34.127.224.10 crmdomain.com www.crmdomain.com;
        root /var/www/html/crm/web;
        index app.php app_dev.php index.php;

        location / {
                # try to serve file directly, fallback to app.php
                try_files $uri /app.php$is_args$args;
        }

    location ~ ^/(app|app_dev|config|install)\.php(/|$) {
            #fastcgi_pass 127.0.0.1:9000;
            # or
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param HTTPS off;
    }

        error_log /var/log/nginx/orocrm_error.log;
        access_log /var/log/nginx/orocrm_access.log;
}


text:
Q: Mkv files random stops playing on my blu-ray player, Why? I am a holder of LG BD390 Blu-ray player...it has always worked well but lately is giving me problems with reading mkv files from external hard drive.
Let me explain...
Lately I've noticed that while I'm playing a mkv file the player randomly stops play video and return to the menu, but I have not touched anything! It happens very frequently.
Initially I thought the problem was related to the mkv file that I was seeing, but then I noticed that the same problem occurred on all other mkv I had; so I came to suspect it might depend on the hard disk, I thought it was damaged, so I tried a new one but the problem continues to occur (both are 2TB HD with external power supply). As a last test I tried to put the mkv file on a USB key and in that case instead everything worked properly.
Among other things I tried to do a restore factory settings of the player but nothing has changed.
Have any of you ever had to deal with a problem like mine? Ever happened to anyone? What do you advise me to do?
Thank you in advance for any useful information about it.

A: Matroska Video Files (*.mkv) Commonly are used on very good quality videos. Full HD or even UltraHD. These kind of resolutions needs some specific transfer rate between your drive and your Blu-Ray Player. One guess would be , that your external drive is unable to deliver the data on time to the blu-ray player with result the short pause of your video, until the device gets the next data to continue.
There are many reasons that can cause that, such as

*

*a damaged usb/power cable,

*damaged drive (as u said it happened to 2 of your hdds)

*Blu-Ray's USB to not support this big transfer rates etc... (as u said it does play with a usb flash drive)

*Drive's Speed is not enough to stream this kind of video file.

So based on your saying we exclude 2,3
I Would suggest you to run a speed test on both of your hdds, open these kind of files with VLC Player on a Computer and check the bandwidth. Then you will be able to check if you can stream this movie on your blu-ray player or not via your HDDs.
If your HDD's transfer rate is enough, then check your power/usb cables. Sometimes when the drives operate with less power have less performance... (Happened to me twice)


text:
Q: jquery click event on bootstrap 3 tabs I have this code:

Tab One

Tab Two

Tab Three

I want to capture the any tab click event and alert the id of the tab being activated by the click. How is this done?

A:

$('a[data-toggle=tab]').click(function(){
    alert(this.id);
});

Tab One

Tab Two

Tab Three

A: I would use the bootstrap events API instead of adding additional click handlers
$('.yourTabsClass a').on('show.bs.tab', function(e){
    alert('ID clicked = ' + e.target.id)
});

Reference: bootstrap tabs docs
DEMO

A: $("a[data-toggle='tab']").click(function() {
    alert($(this).attr("id"))
});

Here is jsfiddle


text:
Q: Adicionar caracter caso seja igual depois do mesmo MIPS Eu quero fazer um programa em MIPS em que depois de encontrar uma vogal, adicione a consoante a seguir nela.
Por exemplo, depois do a, adicionar b, depois do e adicionar f.
No final fica assim:

Palavra introduzida: Olae
Palavra final: Olabef

Isso aqui é o que eu tenho, mas apenas substitui uma letra e não 2...
.data
string: .asciiz "ola"

a: .ascii "a"
a1: .ascii "ab"

e: .ascii "e"
e1: .ascii "ef"

i: .ascii "i"
i1: .ascii "ij"

o: .ascii "o"
o1: .ascii "op"

u: .ascii "u"
u1: .ascii "uv"

tam: .word 3

.text

main:
lw $t6, tam #string length
lb $t1, string($t0) #read bit by bit

lh $s0, a #save in register the char that we want to search
lh $s1, a1 #save in register the char that we want to replace

beq $t0, $t6, done

beq $t1, $s0, continua #if the char of (bit by bit) its like the char of         chars, swap it
bne $t1, $s0, else #if not, saves
else:
lb $s0, e
lhu $s1, e1

beq $t1, $s0, continua
bne $t1, $s0, else2

else2:
lb $s0, i
lh $s1, i1

beq $t1, $s0, continua
bne $t1, $s0, else3

else3:
lb $s0, o
lh $s1, o1

beq $t1, $s0, continua
bne $t1, $s0, else4

else4:
lb $s0, u
lh $s1, u1

beq $t1, $s0, continua
bne $t1, $s0, store

continua:
la $a0, a
li $v0, 4
syscall
sb $s1, string($t0) #do the swap
addi $t0, $t0, 1 #+1 in the index
j main

store:
la $a0, a
li $v0, 4
syscall
sh $t1, string($t0) #saves
addi $t0, $t0, 1 #+1 in the index
j main
done:
li $v0, 10
syscall

Alguma dica?


text:
Q: Streaming data to text files I can stream viewable data in the Windows Console, I also stream the data into a text file using
--raw>output.txt as the command line
This text file will continue to grow in size as long as data is streaming. Is it possible to end streaming into the initial text file and start streaming into a second text file? Perhaps after 10 minutes?

A: you need to use pipe operator to redirect output to a tool that will perform required cutting. cutting can be implemented easily by yourself or probably you'll find something ready for use


text:
Q: c# array of Point Currently I store X and Y using
Point[] points1 = new Point[] {
    new Point { X = 262, Y = 321 },
    new Point { X = 325, Y = 334 },
    new Point { X = 278, Y = 387 }
};

how can I set variable 'points1' globally ? so I can using loop to pull the data X and Y.
Sample Code what I've tried
Point[] points1 = new Point[]{};

for(int i = 0 ; i <10 ;i ++)
{
  points1 = new Point[] { new Point { X = i, Y = i++}};
}

but always get the last result instead of in array list.

A: Instead of creating a new array (which is of type Point[]) at each iteration, you should create a new array-element (which is of type Point) and put it into the array:
for(int i = 0; i < 10; i++)
{
    points1[i] = new Point { X = i, Y = i++ };
}

Furthermore you are incrementing i twice, once in the for-loop-declaration and once when creating the new Point. Therefor you get the following values for your X- and Y-coords:
{ 0, 2, 4, 6, 8 }.

To create 10 points instead of only 5 you should omit one of those incrementations.
Anyway I would suggest to use a List<Point> instead, which is more dynamic as you can easily add and remove elements to it:
List<Point> points = new List<Point>();
points.Add(new Point(...));

A: for(int i = 0 ; i <10 ;i ++)
{
points1 = new Point[] { new Point { X = i, Y = i++}};
}

doesn't set the value of each item in the array. It reassigns points1 to be a new array each iteration. Notice that points1 is being assigned, not an element of points1. To do this, you need to assign new Point values to points1[i] instead.

A: You can set the points for that array directly:
Point[] points1 = new Point[10];
for (int i = 0; i < 10; i++)
{
    points1[i] =  new Point { X = i, Y = i };
}

If you dont have a fixed number of point you have to use List instead of array.
Here is an example:
List<Point> points1 = new List<Point>();
for (int i = 0; i < 10; i++) // can be any limit
{
    points1.Add(new Point { X = i, Y = i++ });
}
// you can convert to array at any time
var points = points1.ToArray();
Console.WriteLine(points1);

A:         List<Point> points1 = new List<Point>();

        for (int i = 0; i < 10; i++)
        {
            points1.Add(new Point { X = i, Y = i++ });
        }


text:
Q: Passing an SSIS variable value as a parameter of SP via OLE DB Command I would like to ask how can I pass an SSIS variable as a parameter of the used Stored Procedure by OLE DB Command in Data Flow?
I am trying to write the following as SQL Command, but not working:
EXEC [dbo].[CalculateProcess] ?,?,?
Received error:

No value given for one or more required parameters.

The first and second values (? values) are coming from Flat File Source as ID, and NAME. The third one should be the value of SSIS variable @howMany. How can I do it? Thanks for help.
EDIT:
Lets assume my dataset is:
ID NAME
1  X
2  Y
3  Z
4
5  A

In this case, @howMany should be 4 at the end. The value should be updated dynamically after each OLE DB Command works if current NAME is not null.
ID NAME
1  X
@howMany = 1

2  Y
@howMany = 2

3  Z
@howMany = 3

4
@howMany = 3

5  A
@howMany = 4

EDIT 2:
When I do add @howMany as derived column, it is happening like:
ID NAME @howMany
1  X    0
2  Y    0
3  Z    0
4       0
5  A    0

And the 0 values are staying, not getting updated after each row. writing OUTPUT after ? in the SQL command did not solve it? Where is my mistake?
EDIT 3: Stored Procedure is --
CREATE PROCEDURE [dbo].[CalculateProcess]
    @ID int,
    @name varchar(30),
    @howMany int output
AS
BEGIN
    SET NOCOUNT ON;
    if (@name is not null)
    BEGIN
        set @howMany = @howMany + 1;
    END
END

EDIT 4: I added a Script Component right after getting Flat File Source. Name is the INPUT parameter, NameCounter is my output column. My script is:
private int nameCounter;
public override void PreExecute()
{
    nameCounter= 0;
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    if (Row.Name != null)
    {
        nameCounter++;

    }
    Row.NameCounter= nameCounter;
}

The Script Component is connected to my OLE DB Command. This is generating a column called NameCounter and adding it to all data in the OLE DB Command. Now I just dont know how to get the value of NameCounter here and assign it to an SSIS variable?

A: Use a Derived Column transformation before the OLE DB Command, and add the variable to your dataflow as a new column.   Then use the new column as the third parameter in your OLE DB Command.
EDIT based on updated question:
Ok, to do what you want you can use a script component.   Here is an example.  Increase the value of the howMany variable in the script if the NAME column is not null, and then add the value of the variable as a third column.
2nd Edit:
To update the value of an SSIS variable in a script, be sure to set the variable as a Read/Write variable in the script properties, unlike in the article I linked above.   Then:
Dts.Variables["howMany"].Value = nameCounter;

A: Right since you have mentioned that the @howMany variable is an output variable you would need to use the OUTPUT clause in your OLE DB Command tranformation.
EXEC [dbo].[CalculateProcess] ?,?,? OUTPUT

And as Tab Alleman has suggested add a derived column before the OLE DB Command tranformation and in the Column Mapping tab of the OLE DB Command transformation , map it to the derived column.
Now you have mentioned that you would also want a total sum of the rows updated.
You can add an Aggregate transformation after the OLE DB Command and Sum on the Derived column with no Grouping and this will give you the total number of rows updated.
Update
Here you go here is the problem, your stored procedure doesnt have the right logic, your @Howmany variable is always null unless you pass a value to it at run-time, since the only values you have is the ID and Name your Howmany variable will always be null in this case.
Your Stored procedure logic is wrong and it should be something like....
CREATE PROCEDURE [dbo].[CalculateProcess]
    @ID int,
    @name varchar(30),
    @howMany int output
AS
BEGIN
    SET NOCOUNT ON;

   Update TableName --<-- whatever your table name is
    SET Name = @name
   WHERE ID = @ID
    AND  Name IS NOT NULL

set @howMany = @@ROWCOUNT;

END


text:
Q: How can I have this specific line in one line and not two! I would like to have the element surrounded by a red rectangle in one line and not to:
Maybe there is something to force him to be shown in one line or maybe I can reduce the the margin left for this specific element but I don't know how to do it

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%
% License:
% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
% This template requires the moderncv.cls and .sty files to be in the same
% directory as this .tex file. These files provide the resume style and themes
% used for structuring the document.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%----------------------------------------------------------------------------------------
%   PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------

\documentclass[11pt,a4paper,sans]{moderncv} % Font sizes: 10, 11, or 12; paper sizes: a4paper, letterpaper, a5paper, legalpaper, executivepaper or landscape; font families: sans or roman

\moderncvstyle{casual} % CV theme - options include: 'casual' (default), 'classic', 'oldstyle' and 'banking'
\moderncvcolor{blue} % CV color - options include: 'blue' (default), 'orange', 'green', 'red', 'purple', 'grey' and 'black'

\usepackage{lipsum} % Used for inserting dummy 'Lorem ipsum' text into the template
\usepackage[top=1.1cm, bottom=1.5cm, left=2cm, right=2cm]{geometry}
%\usepackage[scale=0.75]{geometry} % Reduce document margins
%\setlength{\hintscolumnwidth}{3cm} % Uncomment to change the width of the dates column
%\setlength{\makecvtitlenamewidth}{10cm} % For the 'classic' style, uncomment to adjust the width of the space allocated to your name

%----------------------------------------------------------------------------------------
%   NAME AND CONTACT INFORMATION SECTION
%----------------------------------------------------------------------------------------

\firstname{Mehmet} % Your first name
\familyname{DEMIR} % Your last name

% All information in this block is optional, comment out any lines you don't need
%\title{Étudiant en réseaux et télécommunications}
\address{50, rue de la Paix}{77270 Villeparisis}
\phone{06 52 42 28 65}
\email{demir.mehmet90@gmail.com}
\extrainfo{23 ans}
%\homepage{staff.org.edu/~jsmith}{staff.org.edu/$\sim$jsmith} % The first argument is the url for the clickable link, the second argument is the url displayed in the template - this allows special characters to be displayed such as the tilde in this example
\extrainfo{Permis B / Véhiculé}
\photo[100pt][0.4pt]{pictures/picture} % The first bracket is the picture height, the second is the thickness of the frame around the picture (0pt for no frame)
\quote{Obtenir un contrat d'apprentissage d'une durée de trois ans en cycle ingénieur}

%----------------------------------------------------------------------------------------

\begin{document}

\makecvtitle % Print the CV title
\vspace*{-1.5cm}

\section{Formations}
\cventry{2013 -- 2014}{Formation d'Ingénieurs}{Institut Galilée}{}{}{Spécialité Télécommunications et Réseaux}
\cventry{2010 -- 2013}{Diplôme Universitaire de Technologie}{I.U.T de Villetaneuse (Paris XIII)}{}{}{Spécialité Télécommunications et Réseaux}
\cventry{2010}{Baccalauréat Scientifique}{Lycée Gérard de Nerval (Noisiel, 77186)}{}{}{Spécialité Physique-Chimie}

\section{Compétences}
\cvitem{Langages}{Java, HTML5/CSS3, Javascript, C/C++, PHP, SQL, Script Shell, XML}
\cvitem{Environnements}{Windows, Linux, Android}
\cvitem{Réseaux}{Mise en places des architectures LAN / WLAN}
\cvitem{}{Principe d'interconnexion de réseaux TCP/ IP}
\cvitem{}{Paramétrage de routeurs CISCO}
\cvitem{}{Mise en place d'outils réseaux sur un serveur Linux : DHCP, VPN, firewall et proxy}
\cvitem{}{Réseaux locaux, Ethernet}
\cvitem{Télécoms}{Configuration PABX, VoIP}
\cvitem{}{Fibre optique}
\cvitemwithcomment{Langues}{Anglais}{Bon niveau (\textbf{950} au dernier \textbf{TOEIC})}
\cvitemwithcomment{}{Espagnol}{Débutant}
\cvitemwithcomment{}{Turc}{Bilingue}
\cvitem{Logiciels}{Microsoft Office, Open Office}

\section{Expériences professionnelles}

\cventry{Mars 2012\\\`a  Aujourd'hui}{Auto-entrepreneur}{}{}{}{Gestion de Oues Peinture, entreprise spécialisée dans la peinture et travaux de rénovation.\newline{}}

\cventry{Avril 2013\\\`a Juin 2013}{Stage de fin d'études}{University of Bergen}{Norv\`ege}{}{Développement d'une application mobile Android pour contr\^oler une prise de courant GSM.\newline{}}

\cventry{2006 - 2012}{Travailleur saisonnier}{SBR Décoration}{entreprise de B.T.P}{}{
\begin{itemize}%
\item Préparation de commandes, factures et devis,
\item Elaboration de l'emploi du temps des salariés,
\item Gestion des courriers de l'Assurance Retraite et de l'URSSAF.\newline{}
\end{itemize}}

\section{Centres d'intérêt}
\cvitem{Intérêts}{Association << Entraide Scolaire Amicale >>}
\cvitem{Sport}{Football en salle, musculation}
\cvitem{Cinéma}{Films et séries anglophones en version originale}

\end{document}


text:
Q: Rotate and return the ArrayList in java here in below program i am defining ArrayList of size 7 [1,2,3,4,5,6,7] and and rotating right by 3 places but when i print the numbers1 list it gives me my expected answer numbers: [5, 6, 7, 1, 2, 3, 4] but when i return this ArrayList and then print it, it gives me this answer numbers: [2, 3, 4, 5, 6, 7, 1] why is that please explain.
package QAIntvSprint;

import java.util.ArrayList;
import java.util.Scanner;

public class RotateArray {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int k = sc.nextInt();

    ArrayList<Integer> numbers = new ArrayList<>();

    for (int i = 0; i < n; i++) {
      numbers.add(sc.nextInt());
    }
    rotateArray(numbers, k);
    ArrayList<Integer> ans = rotateArray(numbers, k);
    for (Integer x : ans) {
      System.out.print(x + " ");
    }
  }

  static ArrayList<Integer> rotateArray(ArrayList<Integer> numbers, int k) {
    for (int i = 0; i < k; i++) {
      numbers.add(0, numbers.get(numbers.size() - 1));
      numbers.remove(numbers.size() - 1);
    }
    ArrayList<Integer> numbers1 = numbers;
    System.out.println("numbers: " + numbers1.toString());
    return numbers1;
  }
}

output

A: That's because your function rotateArray changes your numbers ArrayList you give it as parameter. So basically it changes the List (numbers) in your main method. And because you call the method two times, the array gets rotated in sum 6 times (like you see in your final output)
If you don't want to change the ArrayList you give in as a parameter, you should do something like
ArrayList<Integer> newList = new ArrayList(numbers);

as first in you rotateArray method and then  rotate this list.

A: You are running your function twice:
rotateArray(numbers, k); // first
ArrayList<Integer> ans = rotateArray(numbers, k); // second

So the numbers are shifted by 6 instead of 3 positions
Besides, your function does not create a new copy of the array
You return a reference to the same array
ArrayList<Integer> numbers1 = numbers; // copies a reference to an object, not the object itself
return numbers1; // returns the original link

So i suggest refactoring your code like this:
public class RotateArray {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        ArrayList<Integer> numbers = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            numbers.add(sc.nextInt());
        }

        // the function will modify the ArrayList by reference, it will change
        rotateArray(numbers, k);
        for (Integer x : numbers) {
            System.out.print(x + " ");
        }
    }

    static void rotateArray(ArrayList<Integer> numbers, int k) {
        for (int i = 0; i < k; i++) {
            numbers.add(0, numbers.get(numbers.size() - 1));
            numbers.remove(numbers.size() - 1);
        }
    }
}

A: here
ArrayList<Integer> ans = rotateArray(numbers, k);
rotates
numbers, returned by the previous line
Delete
rotateArray(numbers, k);


text:
Q: How to assert multiple facts or rules in one assert/1 statement? If I'm at the repl I can do
?- assert(foo(a)),assert(foo(b)),assert(foo(c)).

and that works, but not
?- assert((bar(a),bar(b),bar(c))).

or similar. Is there a way to only need to type "assert" once and pass in multiple facts? Same question for rules.
thanks!
I tried several variations of what I mentioned above to accomplish this but can't figure out how to do it. Also looked at the doc for assert/1 but it doesn't show how.

A: Maybe you can instead consult from user?
?- [user].
:- dynamic(foo/1).
foo(a).
foo(b).
foo(c).

Press Ctrl-D to end consulting. If you just want to add clauses the database, you may not need to type the dynamic/1 directive.
P.S. assert/1 is a deprecated/legacy predicate. Use instead assrta/1 or assertz/1 if you must.


text:
Q: How to write generic regular expression for id's like ID_FILE_NEW? The file contain lines like,
MENUITEM "&New\tCtrl+N",                ID_FILE_NEW
MENUITEM "Recent File",                 ID_FILE_MRU_FILE1, GRAYED

So i want the output as below
ID_FILE_NEW
ID_FILE_MRU_FILE1

as well as there is possibility that file contains id's as below
ID_VIEW_STATUS_BAR
ID_VIEW_STATUS_BAR_......_N nth number of text after "_"

so how to write generic regular expression to get all of these id's from file?

A: /\w*_\w*_\w*/g
have a look on
Cheatsheet for the regularexpression


text:
Q: In ASP.NET is there an event fired on a Windows Authentication log in failure? (Logging the details of a Windows Authentication failure) I am building a .NET 4.0, ASP.NET MVC 3 intranet application that runs on IIS 7.5 in integrated mode. Windows Authentication is used to govern access to the website. The Windows Authentication module is enabled and all other auth modules are disabled.
Currently when a user provides improper credentials, the Windows Authentication module correctly rejects the credentials and re-displays a login prompt. It does so 3 times, after which a standard .NET 401 Unauthorized Access page is shown. This is expected and desirable.
My goal: I would like to be able to log the details of the failed authentication attempt to my own custom event log. Particularly, to capture the user name that was used in the log in attempt. (I'll accept that capturing the password is not likely to be possible for security reasons.)
Is my goal possible?
I have already built a working an IHttpModule module and added it as an event handler to the WindowsAuthenticationModule, like this:
myWindowsAuthenticationModule.Authenticate += WindowsAuthentication_Authenticate;

But my code does not get called in the case of a failed log in attempt, presumably because WindowsAuthenticationModule has already decided that the log in is failed and so there is no point calling my module. My module does get called after a successful log in attempt, and so I am certain that my event handler is properly set up.
To the best of my knowledge, the WindowsAuthenticationModule does not expose an event that is fired when authentication fails, so that option is out.
Any ideas? Or am I barking up a tree that has no solution?

A: I was looking at the same issue, and looks like there is no events for windows authentication, even that Authenticate event is common for forms and windows.
But I found a solution to this!
http://www.codeproject.com/Articles/11202/Redirecting-to-custom-401-page-when-quot-Access-de
UPDATE
From original article
protected void Application_EndRequest(Object sender, EventArgs e)
{
 HttpContext context = HttpContext.Current;
 if (context.Response.Status.Substring(0,3).Equals("401"))
 {
    if(User.Identity.IsAuthenticated)
    {
        // this means user is authenticated, but 401 still returned
        // which means no access to page or whatever you are trying to access?
    }
 }
}

UPDATE2
I also found out that this solution doesn't work in all cases. I was testing in different environments, so was working for me, but not for others.
By default IIS will not even run this piece of code and just return it's own error page, what you want to do is tell IIS to let app handle errors.
<httpErrors existingResponse="PassThrough">
</httpErrors>

Now, with that said, IIS won't return any more of custom errors and you will need to handle them in application, ie. not only 401, but 403, 405, etc


text:
Q: Average CPI of a processor I understand that CPI can be calculated by clock cycles over instructions. Although I am kind of at an impasse here and need some help. I am trying to find the average CPI of a processor where 25% of the instructions take 1 cycle to execute, 45% take 2 cycles, 15% take 3 cycles, 10% take 4 cycles, and 5% take 5 cycles. Thanks for any help or suggestions!

A: 0.25 * 1 + 0.45 * 2 + 0.15 * 3 + 0.1 * 4 + 0.05 * 5


text:
Q: A $X \subseteq \mathbb{A}^n$ such that $I(X) \neq I(V(I(X)))$? Let $\mathbb{A}^n$ be the affine $n$-space over a field $K$. Denote by $V(S)$ the zero locus of a $S \subseteq K[x_1, \dots, x_n]$ and let $I(X)$ be the ideal of a $X \subseteq \mathbb{A}^n$. Is there any $X \subseteq \mathbb{A}^n$ such that $I(X) \neq I(V(I(X)))$? If yes, give an example, please.

A: EDIT (with Georges Elencwajg's Suggestion):  We assume that $K$ is a commutative integral ring (not necessarily unital).  Let $S$ be an ideal of $K\left[x_1,x_2,\ldots,x_n\right]$ and $X\subseteq K\mathbb{A}^n$.  We claim that $\sqrt{I(X)}=I(X)=I\Big(V\big(I(X)\big)\Big)$ and that $V\big(\sqrt{S}\big)=V(S)=V\Big(I\big(V(S)\big)\Big)$.  We invoke five properties:
(1) $Y\subseteq V\big(I(Y)\big)$ for every $Y\subseteq K\mathbb{A}^n$,
(2) $T\subseteq I\big(V(T)\big)$ for every ideal $T$ of $K\left[x_1,x_2,\ldots,x_n\right]$,
(3) If $Y_1,Y_2\subseteq K\mathbb{A}^n$ are such that $Y_1\subseteq Y_2$, then $I\left(Y_1\right)\supseteq I\left(Y_2\right)$,
(4) If $T_1,T_2$ are ideals of $K\left[x_1,x_2,\ldots,x_n\right]$ such that $T_1\subseteq T_2$, then $V\left(T_1\right)\supseteq V\left(T_2\right)$, and
(5) For any ideal $T$ of $K\left[x_1,x_2,\ldots,x_n\right]$, $T\subseteq \sqrt{T}$.
From (2), as $I(X)$ is an ideal of $K\left[x_1,x_2,\ldots,x_n\right]$, we have $I(X)\subseteq I\Big(V\big(I(X)\big)\Big)$.  From (1), we have $X\subseteq V\big(I(X)\big)$, which means $I(X)\supseteq I\Big(V\big(I(X)\big)\Big)$, due to (3).
Similarly, by (1), as $V(S)\subseteq K\mathbb{A}^n$, we get $V(S)\subseteq V\Big(I\big(V(S)\big)\Big)$.  From (2), $S\subseteq I\big(V(S)\big)$, which leads to $V(S)\supseteq V\Big(I\big(V(S)\big)\Big)$, where (4) is applied.
Now, to show $I(X)=\sqrt{I(X)}$, we have $I(X)\subseteq \sqrt{I(X)}$ from (5).  Suppose $f\in\sqrt{I(X)}$.  Then, $f^k \in I(X)$ for some $k \in \mathbb{N}$.  That is, for all $p \in X$, $\big(f(p)\big)^k=0_K$, but, as $K$ is an integral ring, $f(p)=0_K$.  Therefore, $f\in I(X)$, or $\sqrt{I(X)}\subseteq I(X)$, as required.
To show that $V(S)=V\left(\sqrt{S}\right)$, we note from (5) that $S\subseteq \sqrt{S}$, which leads to $V\left(\sqrt{S}\right)\subseteq V(S)$, by (4).  Suppose that $p \in V\left(S\right)$.  Then, for $f\in \sqrt{S}$, we have $f^k\in S$ for some $k\in\mathbb{N}$.  Consequently, $\big(f(p)\big)^k=0_K$, or $f(p)=0_K$, since $K$ is an integral ring.  Ergo, $p \in V\left(\sqrt{S}\right)$.  Thus, $V(S)\subseteq V\left(\sqrt{S}\right)$, as desired.
If $K$ is a non-integral commutative ring, we only have $\sqrt{I(X)}\supseteq I(X)=I\Big(V\big(I(X)\big)\Big)$ and that $V\big(\sqrt{S}\big)\subseteq V(S)=V\Big(I\big(V(S)\big)\Big)$.  For example, if $K:=\mathbb{Z}/8\mathbb{Z}$, we can take $n:=1$, $X:=2\mathbb{Z}/8\mathbb{Z}$, and $S:=\left(4x_1\right)$.  In this case, $I(X)=\left(4x_1,2x_1+x_1^2,2x_1^2,x_1^3\right)$, whereas $\sqrt{I(X)}=\left(2,x_1\right) \supsetneq I(X)$.  Also, we have $\sqrt{S}=\left(2\right)$, so $V(S)=2\mathbb{Z}/8\mathbb{Z}$, but $V\left(\sqrt{S}\right)= 8\mathbb{Z}/8\mathbb{Z} \subsetneq V(S)$.


text:
Q: Sudden peaks in load and disk block wait Hello superior server gurus!
I'm running a Ubuntu server that hosts an apache tomcat service along with an MySQL database. The server load is always close to zero, even during the busiest hours of the week. Despite that I am experiencing random hangups 1-2 times per week, where the entire server stops responding.
An interesting effect of this lockdown is that all cronjobs seems to be executed later than scheduled, at least that is what the timestamps in various system logs indicate. Thus it appears to me that it is indeed the entire server that freezes, not only the custom software running as a part of the tomcat service.
The hangup normally lasts for about 3-5 minutes, and afterwards everything jumps back to normal.
Hardware:
Model: Dell PowerEdge R720, 16 cores, 16 GB ram
HDD-configuration: Raid-1 (mirror)

Main services:
apache tomcat, mysql, ssh/sftp

#uname -a
Linux es2 2.6.24-24-server #1 SMP Tue Jul 7 19:39:36 UTC 2009 x86_64 GNU/Linux

Running sysstat I can see huge peaks in both average load and disk block waits that corresponds in time exactly to when customers has reported problems with the backend system. Following is a plot of the disk usage from sar with a very obvious peak around 12.30pm.
My sincere apologies for putting this on a external server, but my rep is to low to include files here directly. Also had to put them together since i can only post one link :S

Sar plots: http://213.115.101.5/abba/tmpdata/sardata_es.jpg
Graph 1: Block wait, notice how the util% goes upp to 100% at approx 12.58
Graph 2: Block transfer, nothing unusual here.
Graph 3: Average load, peaks together with graph 1
Graph 4: CPU usage, still close to 0%.
Graph 5: Memory, nothing unusual here

Does anyone have any clue on what could cause this effect on a system? As I earlier explained the only software running on the server is a tomcat server with an SOAP interface, to allow users to connect to the database. Remote applications does also connect to the server via SSH to pull and upload files to it. At busy times im guessing that we have about 50 concurrent SSH/SFTP connections and not more than a 1-200 connections over http (soap/tomcat).
Googling around I found discussions about file handles and inode handles, but I think these are normal for 2.6.x kernals. Anyone that dissagrees?
cat /proc/sys/fs/file-nr
1152    0       1588671
cat /proc/sys/fs/inode-state
11392   236     0       0       0       0       0

At the same time "sar -v" shows these values for the time of the hangup above, but the inode-nr here is ALWAYS very high compared to above.
12:40:01    dentunusd   file-nr  inode-nr    pty-nr
12:40:01        40542      1024     15316         0
12:45:01        40568      1152     15349         0
12:50:01        40587       768     15365         0
12:55:01        40631      1024     15422         0
13:01:02        40648       896     15482         0
13:05:01        40595       768     15430         0
13:10:01        40637      1024     15465         0

I have seen this on two independent servers running the same setup of hardware, OS, software, raid-configuration etc. Thus I want to beleive that its more software/configuration dependent then hardware dependent.
Big thanks for your time
/Ebbe

A: The problems were related to a incompability issue between Ubuntu 8.04 LTS (Hardy) and the Dell PERC 6/i RAID controller, as reported in this bug: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/607167
Upgrading to Ubuntu 10.04 LTS Lucid (kernel 2.6.32) resolves the issue.
In case anyone else runs into the same issues.

A: May be you are running some heavy query which is doing a full table scan.
Have you checked your slow query log.
If thats case just add proper indexes.
PS: Sorry If you have done this already.


text:
Q: Grunt - no image library that works. All are silently failing I'm grunt beginner. But whenever I install any kind of grunt library to handle images it does not work.
grunt-webshot, webshot, getPixels, node-image, node, gm, node-pngjs, imagemagick, node-png, png, get-pixels
grunt.registerTask("getPixels", "your description", function() {
    var fs = require('fs') , gm = require('gm');
    gm('source/templates/t1/images/menu_item_bg.png').size(function (err, size) {

        grunt.log.writeln(size.width > size.height ? 'wider' : 'taller than you');
    });

});

Silently fails. No error, no nothing (I get: Done, without errors). Does not enter callback.
Same is with other libraries I used.
Only grunt modules can be used in grunt? Dont Think so, it seems i can use any library by using require() and it should work. It works ok with require('path')
Any way I can debug it? Make it return some kind of error or fix this problem?
Edit
I wrote a makescreenshot.js script which I call with node
var webshot = require('webshot');
// also tried commented varians:
//webshot('google.com', 'google.jpg', function(err) {
//webshot('http://google.com', 'google.jpg', function(err) {
webshot('http://google.com', 'google.jpg', {}, function(err) {
    console.log('console.log ERROR: ' + err);
});

It returns the following: console.log ERROR: Error: PhantomJS exited with return value 1

A: Seems I figured it somehow. The problem seemed to be not properly installed Microsoft Visual Studio I reinstalled MSVS 2013 Express and it started taking screens normally.


text:
Q: Yii2 - How to list the files inside a folder Hi, i'm making an Yii2 Basic application and have a file upload form in the admin area.
The file upload sends files to app/web/uploads. I followed the great tutorial on uploading files from samdark. It can be seen here: https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md
What i need to do is to create a view that renders hyperlinks to each one of the files inside uploads folder.
In Yii1.xx there was an extension for handling files called Cfile very handy. I used in several applications to do what i want now.
Using Cfile i was able to write code like this:
$cfileDir = Yii::app()->file->set('pdfs/'); // set pdfs as target folder
$files = $cfileDir->getContents();
The getContents() method was great because it let me later apply a foreach loop and list all the files in the folder.
In Yii2 how to do something similar in uploads folder, ie, list of files in that folder and create hyperlinks in a view.
To crate the hyperlinks inside the view i could use Html::a(), but to get all the files inside it i don't know how to do it.
Any Ideas ?? Thanks.
EDIT
SOLVED with the great tip from ALI.
HERE IS THE COMPLETE BLOCK OF CODE
<?php
    $files=\yii\helpers\FileHelper::findFiles('uploads/');
    if (isset($files[0])) {
        foreach ($files as $index => $file) {
            $nameFicheiro = substr($file, strrpos($file, '/') + 1);
            echo Html::a($nameFicheiro, Url::base().'/uploads/'.$nameFicheiro) . "
" . "
" ; // render do ficheiro no browser
        }
    } else {
        echo "There are no files available for download.";
    }
?>

A: In Yii2 you can achieve this by using FileHelper Class like below:
$files=\yii\helpers\FileHelper::findFiles('/path/to');

Now, you have all files list into $files variable as an array.
findFiles() method, returns the files found under the specified directory and sub-directories.
Another examples:
\yii\helpers\FileHelper::findFiles('.',['only'=>['*.php','*.txt']]);

Above example lists all files only with php and txt extensions.
\yii\helpers\FileHelper::findFiles('.',['except'=>['*.php','*.txt']]);

Above example lists all files with all extensions, except php and txt extensions.
\yii\helpers\FileHelper::findFiles('.',['recursive'=>FALSE]);

Above example does not list files under the sub-directories


text:
Q: How do you createRef in Suave Fable? I have a text input, and I've managed to debounce input. However, my keypress listener won't wait for text input events to flush before processing the enter key which would end edits without getting the latest value in the uncontrolled component.
Since I'm in webpack, React... is undefined so I can't just React.createRef() The current source code shows the function exists https://github.com/fable-compiler/fable-react/blob/e904add886bab45003c074cd2b06b8834fddf65b/src/Fable.React.Helpers.fs#L366
However it doesn't resolve/compile.
paket.lock shows Fable.React 4.1.3, Fable.Elmish.React 2.1.

A: createRef is available only since version 5.x something so you need to update to latest version. To be sure, I encourage you to upgrade to the latest version at the time of writing 5.2.3.
This means you will need to upgrade your application to Fable.Core v3, you can read more about it here.
When done you can use createRef like that:
open Fable.React
open Fable.React.Props

type MapComponent(initProps) =
    inherit Fable.React.Component<MapComponentProps, obj>(initProps)

    let mapRef : IRefHook<Browser.Types.HTMLDivElement option> = createRef None

    override this.render() =
        div [ RefValue mapRef ]
            [ str "..." ]

A: As it turned out, for what I needed, the ref wasn't necessary, however I did get one going.
type IReactRef =
  inherit Browser.Element

[<Emit("React.createRef")>]
let createRef(): IReactRef = jsNative

type TextInputProps =
  { Ident: string
    Delay: int
    AddedAttributes: IHTMLProp list
    DefaultValue: string option
    OnChange: (string -> unit)
    OnEscape: (unit -> unit) option
    OnEnter: (string -> unit) option
  }

type TextInputState = InputState
let textInputDelayDefault = 500
type TextInputComponent(props) =
  inherit React.Component<TextInputProps, TextInputState>(props)
  let mutable textInput: obj = null
  let debouncer = Eventing.Debouncer<string>.Create props.Ident props.Delay

  do
    textInput <- react.createRef()
    base.setInitState InputState

  member __.TextInput: IReactRef option =
    textInput
    |> Option.ofObj
    |> Option.map unbox

  // provide cancel edit extension point (Escape doesn't fire keypress)
  member this.OnKeyUp(e: React.KeyboardEvent) =
    if e.key = "Escape" then
      match this.props.OnEscape with
      | Some f ->
        e.preventDefault()
        f()
      | None -> ()

  // provide finish edit extension point
  member this.OnKeyPress(e: React.KeyboardEvent) =
    let value =
      e
      |> unbox
      |> Eventing.getTargetValue
    if e.key = "Enter" then
      this.props.OnEnter
      |> Option.iter (fun f ->
           e.preventDefault()
           debouncer.Clear()
           // send the current value in case the onChange did not send the current value due to debouncing
           f value)

  override this.render() =
    let r =
      input [ yield R.Props.Ref(unbox textInput)
              yield R.Props.OnKeyPress this.OnKeyPress
              yield R.Props.OnKeyUp this.OnKeyUp
              yield Eventing.onDebChange debouncer this.props.OnChange
              yield R.Props.DefaultValue(this.props.DefaultValue |> Option.defaultValue "")
              yield! this.props.AddedAttributes ]
    r

let inline textInputComponent props = Fable.Helpers.React.ofType<TextInputComponent, _, _> props []


text:
Q: Timer in Java which goes up I am doing developing a quiz program.
I want to have a timer that goes up by one second until the person doing the quiz hit the submit answer button.
I have everything other than the timer worked out and I just wanted to know how to add the timer and make it stop when the submit answer button was hit.

A: Try creating a new thread that increments a number and then Thread.sleep(1000); in a loop. I'd admit this isn't the best way but it can be used for most cases. Without knowing the code to implement such a thing into is like guessing.

A: A timer or a stopwatch? To just count the time it took the user to hit submit, you could do this:
// when they start the quiz question
long start = System.currentTimeMillis();

// when they hit submit
long finish = System.currentTimeMillis();

// difference is how long they took
long time = finish - start;
System.out.println("You took " + time + " milliseconds");

Keep in mind, the time they took will be in milliseconds. You can convert that to seconds if you want (there are 1000 milliseconds in 1 second).

A: Assuming you are using Swing since you mentioned button press, you can do this way-
private long startTime, endTime;
private Timer timer;

// When you need to start your timer, do-
startTime = System.currentTimeMillis();
if (timer == null) {
    timer = new Timer(100, this);
    timer.start();
} else {
    timer.restart()
}

// When the button is pressed
endTime = System.currentTimeMillis();
timer.stop();

double totalSeconds = (endTime - startTime) / 1000.0;

// To know how long it's been running-
long time = (System.currentTimeMillis() - startTime) / 1000;

Reference: Oracle's How to Use Swing Timers


text:
Q: Is the nature of the Vulcan/Romulan divide biological or political? As the title suggests what is the nature of the Vulcan Romulan divide?
Is it biological, are the Romulans biologically distinct enough to be considered a different species ?
For example would a medic treating injuries in war time need to check if the patient was from Romulus or Vulcan in order to provide adequate care ?
Or is it political with the only thing separating them is their differing philosophies ?

A: Initially a political issue which drove the two groups apart (whether to adopt the teachings of Surak, based in logic and reason) or to continue the more warlike nature of the Vulcan species. Those who rejected Surak would leave their world and become the Romulans.

*

*When Surak's reforms of embracing logical principles and rejecting emotions spread rapidly across Vulcan in the 4th century, a minority rejected Surak's ideals. Those who marched beneath the banner of the raptor, which became the symbol of the Romulan Star Empire, departed Vulcan in the 4th century.

*Later, some of their descendants established settlements on the planets Calder II, Dessica II, Draken IV, Yadalla Prime, and Barradas III. An ancient offshoot civilization, called the Debrune, at one time existed on Barradas III, but it had died out by the 24th century. (ENT: "Kir'Shara"; TNG: "Gambit, Part I")

*

*Being Romulan is as much a political identity as a physiological identity. The Romulans also lack the rigid mental disciplines common to their Vulcan cousins. These mental conditionings can affect the Vulcan physiology, particularly their brains in a number of ways.

*2,000+ years of differentiation between the two groups, as well as living on different planets and exposure to different ecosystems has lead to the two groups having similar overall biological capacities but distinctions due to their time apart.

*Both groups are still able to reproduce with each other without technological support.

*Yes, there are some differences between the two groups that would require a medic to take their species variation into consideration when treating them. A lack of knowledge about the Vulcan healing trance for example might be dangerous to a medic skilled in Romulan physiology but lacking in training for Vulcan physiology.

*

*Vulcans learned to gain conscious control of many of these functions, allowing them to regulate their bodies to a high degree by simple will power. When injured a Vulcan could go into a trance-like state, using this ability to concentrate all of his or her energy onto repairing the injury. (TOS: "A Private Little War")

*This trance could be self-induced and gave the physical appearance of near-death. It was similar, in principle, to Vulcan neuropressure techniques which could be used to relax the mind and body. (TOS: "By Any Other Name"; VOY: "Riddles"; ENT: "The Xindi")


text:
Q: Classifying space $\text{BU}(n)$ from the differential-geometric point of view? The classifying space of a topological group $G$ is the quotient of $EG$ (a topological space with vanishing homotopy groups) by a proper free action of $G$. The standard notation for the classifying space of $G$ is $BG$, with $B$ short for "classifying space".
The classifying space of the unitary group $\text{U}(n)$ is $\text{BU}(n) \simeq \text{Gr}_n(\mathbb{C}^{\infty})$, where $\text{Gr}_n(\mathbb{C}^{\infty})$ is the "inductive-limit" of the embeddings $$\text{Gr}_n(\mathbb{C}^k) \hookrightarrow \text{Gr}_n(\mathbb{C}^{k+1}) \hookrightarrow \cdots.$$
The infinite Grassmannian $\text{Gr}_n(\mathbb{C}^{\infty})$ is not finite-dimensional, and is therefore not a manifold in the usual sense.

Are there any results concerning the differential-geometric structure of $\text{Gr}_n(\mathbb{C}^{\infty})$?

Can we speak of the curvature of $\text{Gr}_n(\mathbb{C}^{\infty})$? Do we know anything about the curvature of "Riemannian metrics" which reside on $\text{Gr}_n(\mathbb{C}^{\infty})$?

A: In Example 1.2.22 of Nicolaescu - Lectures on the Geometry of Manifolds  you will find a description of the manifold structure  of $\DeclareMathOperator{\Gr}{Gr}\newcommand{\bC}{\mathbb{C}}$$\Gr_n(V)$,  where $V$ is a finite dimensional complex Hilbert space. The finite dimensionality is used only in computing the dimension.  It is described  as a submanifold in the real  Hilbert space of (bounded) self-adjoint operators  $V\to V$.  As such it has  an induced metric.
If  you  fix a  orthonormal basis $(e_n)_{n\geq 1}$ of $V$, then you can produce  a stratification of $\Gr_k(V)$ by Schubert cells   of finite codimension. One can show that these define cohomology classes spanning the cohomology  of $\Gr_k(V)$;   Appendix A of Localization formulae in odd K-theory by Daniel  Cibotaru    explains how one can  associate cohomology classes to strata under certain conditions that are satisfied in this case.
These strata also have a Morse theoretic description.

A: One prerequisite to any differential-geometric point of view of course is that $G$ is a Lie group rather than just a topological group.
Then, one option is to pass from manifolds to Lie groupoids:

*

*If $G$ is a Lie group, then there is a Lie groupoid with one object whose automorphism group is $G$; let's denote this Lie groupoid by $BG$.

*If $M$ is a smooth manifold, then there is a Lie groupoid with objects $M$ and only identity morphisms. Let's denote this Lie groupoid by $M$ again.
"The correct" kind of morphisms between Lie groupoids are "smooth anafunctors" a.k.a. "principal bibundles". All smooth anafunctors between two Lie groupoids from a category (Lie groupoids become a bicategory when equipped with such morphisms).
There is a canonical equivalence of categories:
$$
\operatorname{Hom}(M,BG) \cong \operatorname{Bun}_G(M).
$$
This is the Lie-groupoidal version for the classification of $G$-bundles by morphisms to a fixed object, $BG$. Note that everything takes places in finite-dimensional smooth manifolds, and it works for any Lie group $G$.
The relation to the classical picture is established by geometric realization (of topological groupoids). For example, $\lvert BG\rvert$ is a model for the classifying space, and smooth anafunctors induce homotopy classes of continuous maps.
This pov is explained in Section 2 of:
Nikolaus, Thomas; Waldorf, Konrad, Four equivalent versions of nonabelian gerbes, Pac. J. Math. 264, No. 2, 355-420 (2013). ZBL1286.55006.


text:
Q: drop logins from SQL Server 2000 I stacked here when I try to drop logins from sql server 2000
I used this script to get all the lists before dropping the logins, after I got all the lists I tried to execute the outputs, like "Drop login [xxxxx]" but got this error messages.
"Server: Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near 'LOGIN'."

The Script as follow
----------Script Begin--------
CREATE TABLE #sid (sid binary(85) NOT NULL)

INSERT #sid (sid)
 EXEC sp_MSforeachdb 'select sid from sysusers WHERE sid IS NOT NULL'

SELECT 'DROP LOGIN ' + quotename(name)
 FROM   master.dbo.syslogins l
 WHERE  NOT EXISTS (SELECT *
                    FROM   #sid s
                    WHERE  s.sid = l.sid)
 AND name NOT LIKE '##%'
 AND name NOT LIKE 'NT %'

go
 DROP TABLE #sid
----------Script ends--------

Please help me out
Am newbie for sql server
Any help would be much appreciated
Thanks

A: SQL 2000 code to drop a login:
EXEC master..sp_revokelogin @loginame='YOURDOMAIN\xxxxx'

A: This is what SSMS generated for SQL 2000. Funny thing is, there is different code for domain and SQL logins.
Domain login:
EXEC master.dbo.sp_revokelogin @loginame = N'your_domain\login'

SQL login:
EXEC master.dbo.sp_droplogin @loginame = N'sql_login'


text:
Q: Why is my c++ Winsock server unable to receive data from the client? I tried to run a simple client and server program. Therin, I tried to send the server a message from the client and have the server echo that message back. The problem is that every time I do I get a 10057 error. I have no idea why.
Here is the Server code
#include <stdio.h>
#include <winsock2.h>
#include <stdlib.h>

#define MYBUFSIZE   128

void shutdown_close(SOCKET s)
{

    // Tell the operating system the socket is
    // about to be closed
    shutdown(s, SD_BOTH);

    // close the socket….
    closesocket(s);
}

void shutdown_close_and_exit(SOCKET s)
{
    shutdown_close(s);
    exit(1);
}

void main(int argc, char *argv[])
{
    SOCKET srvr_socket;
    struct sockaddr_in srvr_addr;
    struct sockaddr_in clnt_addr; // Client address
    int addr_len = 0;
    WSADATA wsaData;
    char recv_buf[MYBUFSIZE];
    int recv_msg_len;
    short portnum;

    if (argc == 2)
    {
        portnum = atoi(argv[1]);
        printf("Setting port number to %d\n", portnum);

    } else
    {
        fprintf(stderr, "Usage: %s port_num_to_listen_at\n",
                argv[0]);
        exit(1);
    }

    // Init Winsock
    if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
    {
        fprintf(stderr, "Error: WSAStartup() failed");
        exit(1);
    }

    // Create UDP datagram socket for incoming connections
    if ((srvr_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == SOCKET_ERROR)
    {
        fprintf(stderr, "Error: socket() failed with error %d\n", WSAGetLastError());
        shutdown_close_and_exit(srvr_socket);
    }

    // Construct local address structure
    memset(&srvr_addr, 0, sizeof(srvr_addr));
    srvr_addr.sin_family = AF_INET;
    srvr_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  // Accept messages on any network interface.
    srvr_addr.sin_port = htons(portnum);     // Bind the port number specified on the command line.

    /* Bind to the local address */
    if (bind(srvr_socket, (struct sockaddr *) &srvr_addr, sizeof(srvr_addr)) == SOCKET_ERROR)
    {
        fprintf(stderr, "Error: socket() failed with error %d", WSAGetLastError());
        shutdown_close_and_exit(srvr_socket);
    }

    listen(srvr_socket, SOMAXCONN);

    // Loop forever
    for (;;)
    {
        // Set the size of the in-out parameter, where the client address
        // and port number will be stored by the OS
        addr_len = sizeof(clnt_addr);

        if(accept(srvr_socket,(SOCKADDR *) &srvr_addr, &addr_len) == SOCKET_ERROR)
        {
            fprintf(stderr, "Error: accept() failed with error %d\n", WSAGetLastError());
            shutdown_close_and_exit(srvr_socket);
        }

        // Receive message from client
        if ((recv_msg_len = recvfrom(srvr_socket, recv_buf, MYBUFSIZE, 0,
            (struct sockaddr *) &clnt_addr, &addr_len )) == SOCKET_ERROR) {

            fprintf(stderr, "Error: recvfrom() failed with error %d\n", WSAGetLastError());
            shutdown_close_and_exit(srvr_socket);
        } else {
            printf("Received message of size %d: %s\n from client %s:%d\n",
                    recv_msg_len, recv_buf, inet_ntoa(clnt_addr.sin_addr),
                    ntohs(clnt_addr.sin_port));
        }

        // 'echo' message back to client
        if ((recv_msg_len = sendto(srvr_socket, recv_buf, recv_msg_len, 0,
            (struct sockaddr *) &clnt_addr, addr_len )) == SOCKET_ERROR) {

            fprintf(stderr, "Error: sendto() failed with error %d\n", WSAGetLastError());
            shutdown_close_and_exit(srvr_socket);
        } else {
            printf("Echo'd message %s to client %s:%d\n",
                    recv_buf, inet_ntoa(clnt_addr.sin_addr),
                    ntohs(clnt_addr.sin_port));
        }
    }
}

and here is the client code:
#include <stdio.h>
#include <winsock2.h>
#include <stdlib.h>

#define BUFSIZE 128  /* Size of receive buffer */

void shutdown_close(SOCKET s)
{

    // Tell the operating system the socket is
    // about to be closed
    shutdown(s, SD_BOTH);

    // close the socket….
    closesocket(s);
}

void shutdown_close_and_exit(SOCKET s)
{
    shutdown_close(s);
    exit(1);
}

void main(int argc, char *argv[])
{
    SOCKET servSock;
    struct sockaddr_in srvr_addr;
    struct sockaddr_in recv_addr;
    int addr_len = 0;
    WSADATA wsaData;
    char mesg_buf[BUFSIZE];
    char *mesg_to_send;
    long server_IP;
    short portnum;

    if (argc == 4)
    {
        portnum = atoi(argv[1]);
        printf("Setting port number to %d\n", portnum);

        server_IP = inet_addr(argv[2]);
        printf("Target server IP address is %s\n", argv[2]);

        mesg_to_send = argv[3];

    } else
    {
        fprintf(stderr, "Usage: %s server_port_num server_IP_address message_to_send\n",
                argv[0]);
        exit(1);
    }

    // Init Winsock
    if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
    {
        fprintf(stderr, "Error: WSAStartup() failed with error %d\n", WSAGetLastError());
        exit(1);
    }

    // Create socket for incoming connections
    if ((servSock = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP)) == SOCKET_ERROR)
    {
        fprintf(stderr, "Error: socket() failed with error %d\n", WSAGetLastError());
        shutdown_close_and_exit(servSock);
    }

    // Construct local address structure
    // with server address.  This is like
    // addressing the envelope of a letter.
    memset(&srvr_addr, 0, sizeof(srvr_addr));
    srvr_addr.sin_family = AF_INET;
    srvr_addr.sin_addr.s_addr = server_IP;
    srvr_addr.sin_port = htons(portnum);

    if ( connect(servSock, (SOCKADDR*) &srvr_addr, sizeof(srvr_addr)) == SOCKET_ERROR)
    {
        fprintf(stderr, "Error: connect() failed with error %d\n", WSAGetLastError());
        shutdown_close_and_exit(servSock);
    }

    // Set the size of the in-out parameter
    addr_len = sizeof(recv_addr);

    if (sendto(servSock, mesg_to_send, strlen(mesg_to_send) + 1, 0,
                (sockaddr *) &srvr_addr, addr_len) == SOCKET_ERROR)
    {
        fprintf(stderr, "Error: sendto() failed with error %d\n", WSAGetLastError());
        shutdown_close_and_exit(servSock);
    }

    printf("Send message %s to server at %s:%d\n", argv[3], argv[2], portnum);

    // Sleep 1 full second to allow message  to get to server and be sent back...
    Sleep(1000);

    addr_len = sizeof(recv_addr);

    if (recvfrom(servSock, mesg_buf, BUFSIZE, 0,
                (sockaddr *) &recv_addr, &addr_len) == SOCKET_ERROR)
    {
        fprintf(stderr, "Error: recvfrom() failed with error %d\n", WSAGetLastError());
        shutdown_close_and_exit(servSock);
    }

    printf("Received message %s from %s:%d\n", mesg_buf,
            inet_ntoa(recv_addr.sin_addr), ntohs(recv_addr.sin_port));

    // close socket gracefully
    shutdown_close(servSock);

}

Can anyone see anything wrong with the code?

A: You should use recv for SOCK_STREAM sockets, not recvfrom.
(But that's a huge pile of code and no obvious indication of where the failure is, so there could be other problems besides.)

A: Use send() instead of sendto(), and recv() instead of recvfrom().  Also, you are passing the wrong sockaddr_in to accept() on the server side.

A: I figured out what was wrong. My server was never establishing a connection because I never established a connection with the accept function. In other words I was accepting a connection but not remembering it. I should have created a socket for accepting connections and set it equal to accept function like so :
Socket acceptSocket;

...

AcceptSocket = accept(srvr_socket,(SOCKADDR *) &clnt_addr, &addr_len) ;

        if(AcceptSocket == INVALID_SOCKET)
        {
            fprintf(stderr, "Error: accept() failed with error %d\n", WSAGetLastError());
            shutdown_close_and_exit(srvr_socket);
        }

Also I should have used recv() and send() instead of sendto() and recvfrom() like RichieHindle mentioned because they are designed for UDP connectionless sockets and not TCP connected sockets

A: My Initial code segment when I was receiving error 10057 from the   recvfrom() is as follows:
if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
printf("Error in Listening .. ErroR Code: %d \n", WSAGetLastError());
exit(EXIT_FAILURE);
}
else
printf("Listening\n");

//Accept and incoming connection
puts("Waiting for incoming connections...");

c = sizeof(struct sockaddr_in);
new_socket = accept(s, (struct sockaddr *)&client, &c);

if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d", WSAGetLastError());
return 1;
}
else
puts("Connection accepted");
recv_size = recvfrom(s , client_msg, sizeof(client_msg), 0,
(SOCKADDR *)&recv_from, &addrlen);

I was trying to receive data from the client on the same socket that I   was listening i.e. "s"  rather than the new socket I got the client connection accepted i.e."new_socket ".
    After making the following changes:
recv_size = recvfrom(new_socket , client_msg, sizeof(client_msg), 0, (SOCKADDR
*)&recv_from, &addrlen);

I could receive data from the client application perfectly.


text:
Q: Echo certain value from an array I am trying to echo a certain value of an array which  was outputted by an API call.
So when i call
$userid = 42
$api->listServersByOwner($userid)

will output
Array ( [success] => 1 [errors] => Array ( ) [data] => Array ( [Servers] => Array ( [259] => user42 Server ) ) )

What i specifically want is to put the "259" in a variable.
Please do note that this number changes allot depending on the userid so it wont always be 259.
Any help would be great

A: Replace $arr with the name of your variable.
echo key( $arr['Servers'] );

A: You mean
$array = $api->listServersByOwner($userid);
$var = key( $array['data']['Servers'] );


text:
Q: Can not Deploy ERC20 Token using Truffle I'd like to deploy follow "StandardERC20" token to kovan test net using Truffle.
I want to deploy same contract like
"https://etherscan.io/address/0x69d9905b2e5f6f5433212b7f3c954433f23c1572#code" to kovan.
But I got follow errors.
I added error log and some files needed to deploy this token.
And I found that error is in "ServiceReceiver(receiver).pay{value: msg.value}(serviceName);" of ServicePayer.sol.
last address parameter of deploy function in  2_deploy_token.js is my wallet address. is it correct?
And I tried to use remix. But I couldn't deploy it.
What Can I do for this error?
Help me,everyone!
-Error log-
D:\work\Project\alone\monkey-coin>npx truffle migrate --network kovan

Compiling your contracts...
===========================
> Compiling .\contracts\ServicePayer.sol
> Compiling .\contracts\ServiceReceiver.sol
> Compiling .\contracts\TokenRecover.sol
> Artifacts written to D:\work\ph\Project\alone\monkey-coin\build\contracts
> Compiled successfully using:
   - solc: 0.7.0+commit.9e61f92b.Emscripten.clang

Starting migrations...
======================
> Network name:    'kovan'
> Network id:      42
> Block gas limit: 12500000 (0xbebc20)

2_deploy_token.js
=================

   Deploying 'StandardERC20'
   -------------------------
   > transaction hash:    0x3628fb04e7566dd9619e790e3e0f0dc4aa31c4c59c31a4acdcddadeae11418ac

Error:  *** Deployment Failed ***

"StandardERC20" -- Cannot create instance of StandardERC20; no code at address 0x210f50C6ED1251606Cb8EfE2D191788d141bF935.

-migaration/2_deploy_token.js
const StandardERC20 = artifacts.require("StandardERC20");

module.exports = function(deployer) {
  deployer.deploy(StandardERC20, 'Happy Bear', 'HBT', 18, 1000000000, '0x4d1c919d233E5c35a9A5a12e82f7D5b12D071997');
};

-contracts/ServiceReceiver.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

//import "eth-token-recover/contracts/TokenRecover.sol";
import "./TokenRecover.sol";
/**
 * @title ServiceReceiver
 * @dev Implementation of the ServiceReceiver
 */
contract ServiceReceiver is TokenRecover {

    mapping (bytes32 => uint256) private _prices;

    event Created(string serviceName, address indexed serviceAddress);

    function pay(string memory serviceName) public payable {
        require(msg.value == _prices[_toBytes32(serviceName)], "ServiceReceiver: incorrect price");

        emit Created(serviceName, _msgSender());
    }

    function getPrice(string memory serviceName) public view returns (uint256) {
        return _prices[_toBytes32(serviceName)];
    }

    function setPrice(string memory serviceName, uint256 amount) public onlyOwner {
        _prices[_toBytes32(serviceName)] = amount;
    }

    function withdraw(uint256 amount) public onlyOwner {
        payable(owner()).transfer(amount);
    }

    function _toBytes32(string memory serviceName) private pure returns (bytes32) {
        return keccak256(abi.encode(serviceName));
    }
}

-contracts/ServicePayer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

import "./ServiceReceiver.sol";

/**
 * @title ServicePayer
 * @dev Implementation of the ServicePayer
 */
contract ServicePayer {

    constructor (address payable receiver, string memory serviceName) payable {
        ServiceReceiver(receiver).pay{value: msg.value}(serviceName);
    }
}

-contracts/TokenRecover.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title TokenRecover
 * @author Vittorio Minacori (https://github.com/vittominacori)
 * @dev Allow to recover any ERC20 sent into the contract for error
 */
contract TokenRecover is Ownable {

    /**
     * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts.
     * @param tokenAddress The token contract address
     * @param tokenAmount Number of tokens to be sent
     */
    function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner {
        IERC20(tokenAddress).transfer(owner(), tokenAmount);
    }
}

-contracts/StandardERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./ServicePayer.sol";
/**
 * @title StandardERC20
 * @dev Implementation of the StandardERC20
 */
contract StandardERC20 is ERC20, ServicePayer {

    constructor (
        string memory name,
        string memory symbol,
        uint8 decimals,
        uint256 initialBalance,
        address payable feeReceiver
    ) ERC20(name, symbol) ServicePayer(feeReceiver, "StandardERC20") payable {
        require(initialBalance > 0, "StandardERC20: supply cannot be zero");

        _setupDecimals(decimals);

        _mint(_msgSender(), initialBalance);
    }
}

-package.json
{
  "name": "monkey-coin",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@openzeppelin/contracts": "^3.3.0-solc-0.7",
    "truffle": "^5.1.60"
  },
  "devDependencies": {
    "@truffle/hdwallet-provider": "^1.2.1",
    "dotenv": "^8.2.0"
  }
}

I want to deploy this token surely.
Help Me!!!


text:
Q: Using a Connection String or Variable from an Included PHP File Description :
I have started using mysqli_* functions before that I was using mysql_* now the mysqli_* requires a variable lets say $con to be passed as aenter code heren argument to the mysqli_* function which contains this;
$con = mysqli_connect("localhost","my_user","my_password","my_db");

Now I have a different page at which I am connecting to the database which is just included at every php page to keep the work going like this;
--------- connect.php----------
<?php
if(!mysql_connect("localhost","root",""))
{
    echo "cannot connet to the server";
}
if(!mysql_select_db("katchup"))
{
    echo "Cannot connect to the database";
}
?>

and other pages like this
----------- get_products.php -----------
include 'connect.php';

$result = mysql_query("any query"); // this is what I have

$result = mysqli_query($con , "any query"); // this is what I want

My question is how do I get the $con in connect.php in other pages?

A: put this in your   connection file
<?php
//mysqli_connect("servername","mysql username","password",'database')
$con = mysqli_connect("localhost","root","",'business');

if(!$con)
{
    echo "cannot connet to the server";
}

?>

And in your get product.php etc file use mysqli like this.
<?php
 include('connection.php');
 $query=mysqli_query($con,"your query");
//for single record
 if($row=mysqli_fetch_array($query))
 {
   your data will be here
 }
//for multiple records
while($row=mysqli_fetch_array($query))
{
//your data will be fetched here
}
?>

A: Very simple.
In connect.php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if ($con->connect_errno) echo "Error - Failed to connect to database: " . $con->connect_error;

Then $con will be available in the php scripts you include connect.php in (after you include), and you can use this;
$result = mysqli_query($con , "any query");

or you can use OO instead if you want, like this;
$result = $con->query("any query");

To use the connection in functions, you can either pass as a variable, or make $con global inside the function using global $con;.


text:
Q: Download Github build artifact (release) using wget/curl The Goal: Download github release tar.gz in Docker Build Script, so that the release files can be used for the docker image. I do not want the full source downloaded, which I can get to download through the archive path using the tag, but rather a build artifact that is part of the release.
To Be Noted: This is a download from a private repository, which is why I'm attempting to send my github_token as part of the command currently.
The Problem: I'm having trouble downloading a github release tar.gz using wget.
wget --header="Authorization: token <GITHUB_TOKEN>" --output-document=<FILENAME>.tar.gz https://github.com/<USER>/<REPO>/releases/download/<TAG>/<FILENAME>.tar.gz

This is returning the following error:
--2014-12-02 16:19:25--  https://github.com/<USER>/<REPO>/releases/download/<TAG>/<FILENAME>.tar.gz
Resolving github.com (github.com)... 192.30.252.131, 192.30.252.131
Connecting to github.com (github.com)|192.30.252.131|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2014-12-02 16:19:25 ERROR 404: Not Found.

It's worth noting that I'm not opposed to using curl for the download either or some other solution if necessary.

A: You can use the GitHub API.
To download a release using wget, you can do:
wget --header "Authorization: token <GITHUB TOKEN>"  --output-document=<RELEASE>.tar.gz https://api.github.com/repos/<USER>/<REPO>/tarball/<RELEASE NAME>

Use can change tarball to zipball to get a zip file.

A: The release.tar.gz part is set by the owner, so it is not generic.

$ wget https://github.com/XhmikosR/notepad2-mod/releases/download/4.2.25.935/Notepad2-mod.4.2.25.935.exe
--2014-12-02 11:16:42--  https://github.com/XhmikosR/notepad2-mod/releases/download/4.2.25.935/Notepad2-mod.4.2.25.935.exe
Resolving github.com (github.com)... 192.30.252.130
Connecting to github.com (github.com)|192.30.252.130|:443... connected.
HTTP request sent, awaiting response... 302 Found


text:
Q: Min length of input (searchbox) I need to add a popup window event to my search system - when a customer hit only 2 characters it should popup a small table with alert e. g. "You must enter at least 3 characters when searching..." and the background should be greyed out.
Is this possible for me? Here is my javascript code for searching (in table):
/*** SEARCHBOX ***/

//define the table search object, which can implement both functions and properties
    window.tableSearch = {};
//initialize the search, setup the current object
tableSearch.init = function() {
    //define the properties I want on the tableSearch object
    this.Rows = document.getElementById('data').getElementsByTagName('TR');
    this.RowsLength = tableSearch.Rows.length;
    this.RowsText = [];

    //loop through the table and add the data to the table search object
    for (var i = 0; i < tableSearch.RowsLength; i++) {
        this.RowsText[i] = (tableSearch.Rows[i].innerText) ? tableSearch.Rows[i].innerText.toUpperCase() : tableSearch.Rows[i].textContent.toUpperCase();
    }
}

    //onlys shows the relevant rows as determined by the search string
tableSearch.runSearch = function() {
    //get the search term
    this.Term = document.getElementById('searchbox').value.toUpperCase();

    //loop through the rows and hide rows that do not match the search query
    for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
        row.style.display = ((rowText.indexOf(this.Term) != -1) || this.Term === '') ? '' : 'none';
    }
}

//handles the enter key being pressed
tableSearch.search = function(e) {
    //checks if the user pressed the enter key, and if they did then run the search
    var keycode;
    if (window.event) { keycode = window.event.keyCode; }
    else if (e) { keycode = e.which; }
    else { return false; }
    if (keycode == 13) {
        tableSearch.runSearch();
    }
    else { return false; }
}

And here is my html code (search box):

<input id="searchbox" size="25" maxlength="100" value="search..." style="color: gray;" name="Search" onkeyup="tableSearch.search(event)" onfocus="if(this.value == 'search...') {this.value=''}" onblur="if(this.value == ''){this.value ='search...'}" type="text" />
<input class="button_searchbox" value="Search" onclick="tableSearch.runSearch();" type="button" />

Any ideas? Thx

A: This is a little example using part of your code, and a simple div as a popup:
function doSearch(event)
{
    var keycode;
    if (window.event) { keycode = window.event.keyCode; }
    else if (e) { keycode = e.which; }
    else { return false; }

    if (keycode == 13)
    {
        if (this.searchbox.value.length > 2)
        {
            console.log("Searching...");
        }
        else
        {
            document.getElementById("divPopup").style.display = "block";
        }
    }
    else
    {
        document.getElementById("divPopup").style.display = "none";
        return false;
    }
}

Div:

You must enter at least 3 characters when searching...

CSS:
#divPopup
{
    color: grey;
    font-family: Verdana;
    font-size: 10px;
    border: 1px solid black;
    width: 200px;
    display: none;
}

JSFiddle: http://jsfiddle.net/hescano/9NFqL/

A: In your runSearch function, after the statement
this.Term = document.getElementById('searchbox').value.toUpperCase();
check the length of the search term
if (this.Term.length() < 3){
    alert('You must enter at least 3 characters when searching...');
    return;
}

Thats all.


text:
Q: How to display an animated icon during python function processing in django? I am trying to develop an application with Django. I have a form in my HTML file which will pass same data to the server. At server side, my python function(called submit) will receive the posted values and process them and then redirect the user to a new page.
Question: How can I show a loading gif to the user until my python function is processing posted data and finished? I searched on the stackoverflow about this question and there are some answers (this and this and this) but the answers are for finishing Ajax functions, or there is no explanation how can I identify when my python function has been finished or is for flask framework.
Any help would be greatly appreciated.

A: This is rather simple. First you will have to download font-awesome.css from here http://fontawesome.io/.
Then create one element like  this element will be hidden by default. Set it visible at the beginning of your ajax call and hide it once you have receive the response.
If you want to show your own image, the logic should be the same.


text:
Q: Check with code if an instance is a readable secondary How can I query if an instance is a readable secondary in an AG? E.g. to check if the instance is the primary for an AG then we can use: select sys.fn_hadr_is_primary_replica('AGDatabase'). Is there a similar check for a readable secondary?

A: I think the following query returns a row when the given database and current server is not primary and is readable.
SELECT ar.secondary_role_allow_connections_desc
FROM   sys.availability_replicas AS ar
       JOIN sys.availability_databases_cluster adc ON adc.group_id = ar.group_id
WHERE  ar.secondary_role_allow_connections > 0
       AND adc.database_name = '<<database>>'
       AND ar.replica_server_name = @@SERVERNAME
       AND sys.fn_hadr_is_primary_replica('<<database>>') = 0


text:
Q: NameError: при написании игры на Pygame Вопрос таков.
Пишу по учебнику Э.Метиз Изучаем Python учебный проект при помощи Pygame.
При определении одной из переменных screen вылезает ошибка NameError.
Хотя переменная инициализирована. Не вижу своей ошибки.
Буду рад помощи.
Основной файл game.py
import sys
import pygame
from settings import Settings
from ship import Ship

class AlienInvasion():
    """A class for managing resources and game behavior"""
    def __init__(self):
        """Inizialization game and create games resources"""
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")
        self.ship = Ship(screen)

    def run_game(self):
        """Launch main cycle game"""
        while True:
            # keyboard and mouse
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

            self.screen.fill(self.settings.bg_color)
            self.ship.blitme()

            # Display the last drawn screen
            pygame.display.flip()

if __name__ == '__main__':
    # Create exemple and launch game
    ai = AlienInvasion()
    ai.run_game()

файл с классом корабля Ship.py
import pygame

class Ship():
    """Class for control ship"""
    def __init__(self, ai_game):
        """initialization ship and sets its initial position"""
        self.screen = ai_game.screen
        self.screen_rect = ai_game.screen.get_rect()
        #Load image ship
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        #Each new ship appears at the bottom of the screen
        self.rect.midbottom = self.screen_rect.midbottom

    def blitme(self):
        """Draw ship in current position"""
        self.screen.blit(self.image, self.rect)

Текст сообщения об ошибке:

Traceback (most recent call last):
File "C:\Users\Gradysnik\Desktop\python_work\alien_invasion\game.py", line 33, in
ai = AlienInvasion()
File "C:\Users\Gradysnik\Desktop\python_work\alien_invasion\game.py", line 15, in init
self.ship = Ship(screen)
NameError: name 'screen' is not defined

Upd.
файл settings.py
class Settings():
    """A class for save all settings game Alien Invasion"""

    def __init__(self):
        """Inicialization settings game"""
        # Display settings
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (230, 230, 230)

A: я отметил строки, в которые внес изменения.
game.py
import  sys                                                                 # +++
import pygame
from settings import Settings
from ship import Ship

class AlienInvasion():
    """A class for managing resources and game behavior"""
    def __init__(self):
        """Inizialization game and create games resources"""
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")
        self.ship = Ship(self.screen)                                       # + self.

    def run_game(self):
        """Launch main cycle game"""
        while True:
            # keyboard and mouse
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

            self.screen.fill(self.settings.bg_color)
            self.ship.blitme()

            # Display the last drawn screen
            pygame.display.flip()

if __name__ == '__main__':
    # Create exemple and launch game
    ai = AlienInvasion()
    ai.run_game()

ship.py
import pygame                                                            # +++

class Ship():
    """Class for control ship"""
    def __init__(self, ai_game):
        """initialization ship and sets its initial position"""
        self.screen = ai_game                                             #.screen
        self.screen_rect = ai_game.get_rect()                             #ai_game.screen.get_rect()

        #Load image ship
#        self.image = pygame.image.load('images/ship.bmp')
        self.image = pygame.image.load('Ok.png')

        self.rect = self.image.get_rect()
        #Each new ship appears at the bottom of the screen
        self.rect.midbottom = self.screen_rect.midbottom

    def blitme(self):
        """Draw ship in current position"""
        self.screen.blit(self.image, self.rect)

settings.py
class Settings():
    """A class for save all settings game Alien Invasion"""

    def __init__(self):
        """Inicialization settings game"""
        # Display settings
        self.screen_width = 1200
        self.screen_height = 600
        self.bg_color = (230, 230, 230)


text:
Q: post_save play a video I have a django model called deposit and two views
/admin # django admin
/deposit # a ListView for the deposit model

I want to reload the /deposit view with the latest data and play a video whenever a new entry is added in /admin view.
It can be done using ajax where I keep hitting to check if db is updated after a fixed interval of time but is there any other way something that is more real time?


text:
Q: Get paths from Illustrator file for overlay on web page This is a pretty general question but just looking for someone to get me started in the right direction. I have been given a project where I need to create maps on a webpage and have certain parts of them highlighted/outlined on mouseover.
The maps I was given are illustrator files and when I open them up I see they are divided into the areas that I will need to highlight. Do I get those paths from AI and use them with something like Raphaël? Or do I create some overlays? Really not sure how to get started here.

A: Illustrator lets you export as svg. you can then use the svg as a background image, or include it inline in your page.
Note that you dont necessarily need to keep it in vector format in order to use it on a webpage. You could also simply use illustrator's "Save for web" feature to export the graphics as a png or gif.
Either way you can then start working with it like any normal web resource to build your page.


text:
Q: NameError in Python when opening - don't know why I have used this code but don't understand why it doesn't work (on Jupyterlabs 3.8)- error that comes us up is shown below.
import pandas as pd

pwd

'/Users/hassanmazhar/Desktop/Data Analytics course'

journal=pd.read('/Users/hassanmazhar/Desktop/Data Analytics course/Journals.csv')

journal.head()

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-a1ac9a5c147f> in <module>
----> 1 journal.head()

NameError: name 'journal' is not defined

A: You should try using pd.read_csv and also add an r before your file path.


text:
Q: communicating with nextjs from rust wasm I would like to trigger a code in my Nextjs component when something happened on my wasm application side. I am able to display an alert box using this:
#[wasm_bindgen]
extern "C" {
    pub fn alert(s: &str);
}

But I don't get how I could call a next function. Would it be possible to trigger a javascript event?


text:
Q: How to call a function from Angular service class in angular view component? I am creating a custom function in a service file where I am trying to limit the string length. But I don't know how to call that function from angular view component.
generalservice.ts
-----------------------

export class GeneralService {

  constructor() { }

  removeHTML(str:any){
      var tmp = document.createElement("DIV");
      tmp.innerHTML = str;
      return tmp.textContent || tmp.innerText || "";
  }
}

app.component.ts
--------------------
doSomething(){

    subscribe(data => {
        this.allBlogs = data.blogs.data;

        }
    );
  }

app.component.html
----------------------

{{ removeHTML(blogs.heading) }}
/div>

A: You can just create a public variable with the same name removeHTML and then assign the method of the service to this variable, then it will call the service method!
generalservice.ts
-----------------------

export class GeneralService {

  constructor() { }

  removeHTML(str:any){
      var tmp = document.createElement("DIV");
      tmp.innerHTML = str;
      return tmp.textContent || tmp.innerText || "";
  }
}

app.component.ts
--------------------
doSomething(){

    subscribe(data => {
        this.allBlogs = data.blogs.data;

        }
    );
  }

removeHTML = this.generalService.removeHTML; // <- change made here

app.component.html
----------------------

{{ removeHTML(blogs.heading) }}
/div>


text:
Q: Allow my app post on my facebook page I have a chatbot in facebook that receives images from users and make some adjustments.
Then, I want the chatbot to post the images on the facebook page automatically. Is there a way to achieve that?

A: Yes there is always a way.
Here's how I would do this.
First read this on how to use the page section of the graph-api.
You need to give your app these permissions https://developers.facebook.com/docs/facebook-login/permissions#reference-manage_pages. The manage_pages and publish_pages allow your app to post on the page.
STEP 1. Your bot sends the image to the server for processing.
STEP 2. Add the graph-api sdk to your project.(You might have this already)
STEP 3. Get the ID of the page you want to post to
STEP 4. Since you will be uploading images, you need to check this posting photos to facebook page via graph-api to post your images.
It's basically sending a POST request to https://graph.facebook.com/ /v2.8/{page-id}/photos with the image as a param called source.

1: Attach the photo as multipart/form-data. The name of the object doesn't matter, but historically people have used source as the parameter name for the photo. How this works depends on the SDK you happen to be using to do the post.
2: Use a photo that is already on the internet by publishing using the url parameter:

Now if everything is setup properly, you should be able to post from your server to the page with the ability to add captions etc.


text:
Q: Ninject, заменить реализацию на другой класс Знакомлюсь с IoC контейнерами и Ninject. По примерам в сети сделал реализацию для Ninject. Но как теперь мне выделить для объекта, скажем, не YandexTranslator, а TestTranslator? Создавать ещё один подобный конфиг-модуль, где будет уже TestTranslator вместо YandexTranslator, а после использовать этот конфиг для нового объекта IKernel?
Имеется ли более красивый способ подставлять другие классы с помощью Ninject?
class TranslatorConfigModule : NinjectModule
{
    public override void Load()
    {
        Bind<ITranslatorType>().To<YandexTranslator>();
        Bind<IFilterInputText>().To<FilterLowerCase>();
    }
}

Создание объекта с помощью Ninject
IKernel ninjectKernel = new StandardKernel(new TranslatorConfigModule());
Translator translator = ninjectKernel.Get<Translator>();

A: Если нужно подменить одну реализацию на другую, не затрагивая при этом существующий модуль, то есть два варианта.
Можно открепить абстракцию и прикрепить другую реализацию где-то сразу после инициализации ядра:
IKernel ninjectKernel = new StandardKernel(new TranslatorConfigModule());

ninjectKernel.Unbind<ITranslatorType>();
ninjectKernel.Bind<ITranslatorType>().To<TestTranslator>();

Translator translator = ninjectKernel.Get<Translator>();

Либо создать новый модуль, который наследует существующий и подменяет реализацию только для одной необходимой абстракции
class TestTranslatorConfigModule : TranslatorConfigModule
{
    public override void Load()
    {
        base.Load();
        Unbind<ITranslatorType>();
        Bind<ITranslatorType>().To<TestTranslator>();
    }
}

и, соответственно, использовать его вместо существующего при инициализации ядра
IKernel ninjectKernel = new StandardKernel(new TestTranslatorConfigModule());


text:
Q: Can I use the following Fail2ban jail with my wordpress on nginx server? [nginx-noscript]

enabled  = true
port     = http,https
filter   = nginx-noscript
logpath  = /var/log/nginx/access.log
maxretry = 6

It is advised to not enable [nginx-noscript] jail, if server is running scripts. What are the types of scripts in this case?

A: Take a look at the failregex definition for the nginx-noscript filter. You can typically find filters in /etc/fail2ban/filter.d/.
Example:
cat /etc/fail2ban/filter.d/nginx-noscript.conf

You may see something like this, which would restrict access to .php, .asp, .exe, .pl, .cgi, and .scgi files:
# Noscript filter /etc/fail2ban/filter.d/nginx-noscript.conf:
[Definition]
failregex = ^<HOST> -.*GET.*(\.php|\.asp|\.exe|\.pl|\.cgi|\.scgi)
ignoreregex =


text:
Q: What does Varchar(2000 char) mean in Oracle DB? I need to find a field length for a text field in application. i.e, How many words or characters I can store in that field. Should I need to check it in DB or in code?

A: Firstly , Oracle prefer Varchar2 data type instead of varchar.
secondly, before Oracle 12C, the max length of varchar2 is 4000 in SQL , but in PL/SQL, the max length varchar2 is 32K; since 12C, it is same for SQL and PL/SQL, the max length of varchar2 is 32K.