text:
Q: "Player2" is unable to do the same things as "player" import random

WIDTH = 800
HEIGHT = 500

background = Actor('background')
player = Actor('player')
enemy = Actor('enemy')
money = Actor('money', pos=(300, 300))
player2 = Actor('alien')
score = 0
score2 = 0
player.x = 200
player.y = 200

def draw():
    screen.clear()
    background.draw()
    player.draw()
    enemy.draw()
    money.draw()
    player2.draw()

def update():
    global score
    if keyboard.right:
        player.x = player.x + 4
    if keyboard.left:
        player.x = player.x - 4
    if keyboard.down:
        player.y = player.y + 4
    if keyboard.up:
        player.y = player.y - 4

    if player.x > WIDTH:
        player.x = WIDTH
    if player.x < 0:
        player.x = 0
    if player.y < 0:
        player.y = 0
    if player.y > HEIGHT:
        player.y = HEIGHT

    if enemy.x < player.x:
        enemy.x = enemy.x + 1
    if enemy.x > player.x:
        enemy.x = enemy.x - 1
    if enemy.y < player.y:
        enemy.y = enemy.y + 1
    if enemy.y > player.y:
        enemy.y = enemy.y - 1
    if player.colliderect(enemy):
        exit()

    if money.colliderect(player):
        money.x = random.randint(0, WIDTH)
        money.y = random.randint(0, HEIGHT)
        score = score + 1
        print ('Score:', score)

    if keyboard.d:
        player2.x = player2.x + 4
    if keyboard.a:
        player2.x = player2.x - 4
    if keyboard.s:
        player2.y = player2.y + 4
    if keyboard.w:
        player2.y = player2.y - 4
    if player.colliderect(player2):
        exit()

    if player2.x > WIDTH:
        player2.x = WIDTH
    if player2.x < 0:
        player2.x = 0
    if player2.y < 0:
        player2.y = 0
    if player2.y > HEIGHT:
        player2.y = HEIGHT

I just tried to introduce a player2 to into my python game that I am making in MU-editor, I can see player2 and move him, but there are some problems. enemy is not chasing player2 and player2 can not pick up money. I also want to add a score2 variable for player2 and store the score when he collides with the money.

A: To pickup the money, you have to add the collision test between playyer2 and money:
score2 = 0

def update():
    global score, score2

    # [...]

    if money.colliderect(player2):
        money.x = random.randint(0, WIDTH)
        money.y = random.randint(0, HEIGHT)
        score2 += 1

For chasing player or player2 you have to find the player which is nearer to the enemy. Compare the square of the Euclidean distance from the enemy to the players and chase the player which is nearer:
def update():

    dx1, dy1 = player.x - enemy.x, player.y - enemy.y
    dx2, dy2 = player2.x - enemy.x, player2.y - enemy.y
    dist1sq = dx1*dx1 + dy1*dy1
    dist2sq = dx2*dx2 + dy2*dy2

    player_near = player if dist1sq < dist2sq else player2

    if enemy.x < player_near.x:
        enemy.x += 1
    if enemy.x > player_near.x:
        enemy.x -= 1
    if enemy.y < player_near.y:
        enemy.y += 1
    if enemy.y > player_near.y:
        enemy.y -= 1
    if player.colliderect(enemy):
        exit()
    if player2.colliderect(enemy):
        exit()

    # [...]

function update:
def update():
    global score, score2

    if keyboard.right:
        player.x += 4
    if keyboard.left:
        player.x -= 4
    if keyboard.down:
        player.y += 4
    if keyboard.up:
        player.y -= 4

    if player.x > WIDTH:
        player.x = WIDTH
    if player.x < 0:
        player.x = 0
    if player.y < 0:
        player.y = 0
    if player.y > HEIGHT:
        player.y = HEIGHT

    if keyboard.d:
        player2.x += 4
    if keyboard.a:
        player2.x -= 4
    if keyboard.s:
        player2.y += 4
    if keyboard.w:
        player2.y -= 4

    if player2.x > WIDTH:
        player2.x = WIDTH
    if player2.x < 0:
        player2.x = 0
    if player2.y < 0:
        player2.y = 0
    if player2.y > HEIGHT:
        player2.y = HEIGHT

    dx1, dy1 = player.x - enemy.x, player.y - enemy.y
    dx2, dy2 = player2.x - enemy.x, player2.y - enemy.y
    dist1sq = dx1*dx1 + dy1*dy1
    dist2sq = dx2*dx2 + dy2*dy2

    player_near = player if dist1sq < dist2sq else player2

    if enemy.x < player_near.x:
        enemy.x += 1
    if enemy.x > player_near.x:
        enemy.x -= 1
    if enemy.y < player_near.y:
        enemy.y += 1
    if enemy.y > player_near.y:
        enemy.y -= 1
    if player.colliderect(enemy):
        exit()
    if player2.colliderect(enemy):
        exit()

    if money.colliderect(player):
        money.x = random.randint(0, WIDTH)
        money.y = random.randint(0, HEIGHT)
        score = score + 1

    if money.colliderect(player2):
        money.x = random.randint(0, WIDTH)
        money.y = random.randint(0, HEIGHT)
        score2 += 1


text:
Q: XMLhttprequest.send() doesn't send variables to PHP I have this code.
JAVASCRIPT
function removeAndReplace(id, sezione){
   var xhttp = new XMLHttpRequest();

   xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
         alert(xhttp.responseText);
      }
   }

   xhttp.open("POST", "removeAndReplace.php", true);
   xhttp.send("id=" + id + "&sezione=" + sezione);
}

PHP
 print_r($_POST);

 $id = $_POST['id'];
 $sezione = $_POST['sezione'];
 .
 .
 .

HTML
<input type="button" value="Elimina" class="btn_elimina" onClick="removeAndReplace(1, 'Shopping')">

I want to call a PHP function after the button click so I read that the better way is to use AJAX.
Firefox and Chrome return this error message:

Array
  (
  )

Notice:  Undefined index: id in C:\pweb\tools\xampp\htdocs\Bazaar\php\removeAndReplace.php on line 6

Notice:  Undefined index: sezione in C:\pweb\tools\xampp\htdocs\Bazaar\php\removeAndReplace.php on line 7

Line 6 is: $id = $_POST['id'];
Line 7 is:  $sezione = $_POST['sezione'];
Where am I going wrong?

A: You are dumping your data into the request body without telling the server how it is formatted.
Since PHP doesn't know you have sent it data in an encoding it understands, it ignores the request body.
You need to add:
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

… before you send the request.

Aside
While your hard coded data is free of special characters, it is best practice to encode your data. This will save you headaches in the future:
xhttp.send("id=" + encodeURIComponent(id) + "&sezione=" + encodeURIComponent(sezione));

You can save yourself the trouble of manually encoding the data and having to set your own content-type by using the FormData API:
var data = new FormData();
data.append("id", id);
data.append("sezione", sezione);

xhttp.open("POST", "removeAndReplace.php", true);
xhttp.send(data);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Play Games apk detailed list button bar css? The detailed list section at the bottom of the google play games apk application caught my attention. When I wanted to do the same, I searched on the internet but couldn't find it. Can I learn css codes from application? or is there a codepen example on the internet that has the same functionality?
Below are screenshots

Can I learn css codes from application? or is there a codepen example on the internet that has the same functionality?


text:
Q: Example for a proper Seminorm on $\mathbb{R}^n$ I should give an example for an proper seminorm, so a norm for which every norm-axiom holds but $||x||=0 \Rightarrow x=0$. We assume that we use the Vectorspace $\mathbb{R}^n$ for our x. My guess would be
$$
||x||=|\sum_i^n x_i|
$$
(N1) $||x+y||=|\sum_i^n (x_i+y_i)|=|\sum_i^n x_i+ \sum_i^n y_i|\leq |\sum_i^n x_i|+|\sum_i^n y_i|=||x||+||y||$
(N2)$||ax||=|\sum_i^n ax_i|=|a \sum_i^n x_i|=|a||\sum_i^n x_i|=|a| ||x||$
(N3/1)$||x||=|\sum_i^n x_i|\geq 0$
but for $x:=(1,-1,0,0,...0)^T\neq 0$ we have $||x||=|\sum_i^n x_i|=0$
Is that ok or did I do a mistake? I am unsure because in the answers of the book were a few examples but this one was not there. Thanks in advance :)

A: yes, your example is correct.
You can also choose a more trivial example, like setting the norm of every vector to zero.


text:
Q: Extract string if match the value in another list I want to get the value of the lookup list instead of a boolean. I have tried the following codes:
val = pd.DataFrame(['An apple','a Banana','a cat','a dog'])
lookup = ['banana','dog']
# I tried the follow code:
val.iloc[:,0].str.lower().str.contains('|'.join(lookup))
# it returns:
0    False
1     True
2    False
3     True
Name: 0, dtype: bool

What I want:
0    False
1    banana
2    False
3    dog

Any help is appreciated.

A: You can use extract instead of contains, and fillna with False:
import re
p = rf'\b({"|".join(lookup)})\b'
val[0].str.extract(p, expand=False, flags=re.I).fillna(False)

        0
0   False
1  banana
2   False
3     dog


text:
Q: How to concatenate Int variable in the SQL Select Query I have to write a select query with concatenating the stored procedure Exec in the select results.
This is the actual stored procedure execution result
exec wf_Move_bills ''' + billid+ ''',361,14098,14100, ''+ binid +'' ,''' + @comment + '''

BinId is an Integer. I am having trouble on concatenating with my query.
Result is returned as:
exec wf_Move_bills 'XZ242344',361,14098,14100, '+ binid +' ,'Moved by Dev :'

Expected result is:
exec wf_Move_bills 'XZ242344',361,14098,14100, 300 ,'Moved by Dev :'

Because in the stored procedure, parameter for binid is int with length = 4
declare @comment nvarchar(4000)
set @comment= 'Moved by Dev:'

select
    *,
    'exec wf_Move_bills ''' + billid+ ''',361,14098,14144, ''+ binid +'' ,''' + @comment + ''' '
from
    billingtable

A: + is overloaded.  That is, it means both string concatenation and addition.  If any value is numeric, then it is addition, and you get an error.
So, do an explicit cast:
select *,
       'exec wf_Move_bills ''' + billid+ ''',361,14098,14100, ''' + cast(binid as varchar(255)) +''' ,''' + @comment + '''

Alternatively, I often use replace for this type of logic:
declare @str nvarchar(max);
set @str = 'exec wf_Move_bills @billid, 361, 14098, 14100, @binid, ''@comment''';

set @str = replace(@str, '@billid', @billid);
set @str = replace(@str, '@binid', @binid);
set @str = replace(@str, '@comment', replace(@comment, '''', '''''');

Note:  this also gives an opportunity to handle any single quotes in the comment.
You may also be able to do variable substitution using sp_executedql.

A: change ''+ binid +'' to ''+ convert(varchar(10), binid) +''


text:
Q: How to Transpose 2D Matrix Stored as C 1D Array I have a 2D matrix
1 2 3
4 5 6
7 8 9

stored in C like this
int array[9] = {1,2,3,4,5,6,7,8,9};

and I would like to get the transpose of that matrix like this
int array_t[9] = {1,4,7,2,5,8,3,6,9};

without converting the original array into a 2D one. How can this be done?

A: This can be done by switching around the loops you would normally use to index it. If you wanted the original matrix you could loop through it with something like this
for (i = 0; i < 3; ++i) {
    for (j = 0; j < 3; ++j) {
        printf("%d ", array[j + i * 3]);
    }
    printf("\n");
}

If we switch the i and j loops we can get the desired output as in the following sample program
#include <stdio.h>

int main() {
    int array[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    int i, j;

    for (j = 0; j < 3; ++j) {
        for (i = 0; i < 3; ++i) {
            printf("%d ", array[j + i * 3]);
        }
        printf("\n");
    }
}

This is related to the mathematical definition of the transpose of a 2D matrix. The transpose operation on a 2D matrix swaps the rows with the columns, in the C program when we are indexing it we swap our row and column loops.


text:
Q: How to generate access token for youtube api? I am trying to integrate Youtube API into my project but to start working with it, I need to generate the access token. I searched the internet and found multiple articles that confused me a lot. I have seen various methods to generate it, but none of them works for me.
I also tried this npm library, but this gives me the following error:
code: 403,
  errors: [
    {
      message: 'The request is not properly authorized.',
      domain: 'youtube.activity',
      reason: 'forbidden'
    }
  ]

I am tired of searching more on this, so if anyone has any idea to get it, Please tell me. It will be a great help.

A: Did you try to follow the official documentation? There are clear steps on how to get access.
https://developers.google.com/youtube/v3/getting-started#before-you-start


text:
Q: Configuring Spring Web Sockets I followed the following example to get up and running a Spring project that uses Web sockets.
https://spring.io/guides/gs/messaging-stomp-websocket/
Now I'm trying to customize the project to my specific needs and facing a few issues.
For one I tried to rename the static folder inside resources to some other name, say webapp.
I added the following configuration file to support the change.
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/resources/**")
                .addResourceLocations("/resources/")
                .setCachePeriod(3600)
                .resourceChain(true)
                .addResolver(new PathResourceResolver());
    }
}

However now when I run the application, on http://localhost:8080
I go into a whitelabel error page,
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Oct 23 14:54:08 PDT 2016
There was an unexpected error (type=Not Found, status=404).
No message available

Any help with the configuration, will be highly appreciated. Thanks.


text:
Q: FInd the largest square in a histogram I have been given an array of integers like,
a = [1, 2, 3, 5, 4, 8, 4, 5, 6]
a[i] -> Height of each bar in the histogram
0 < len(a) < 100
0 <= a[i] < 100

My task is to find the edge length of the largest square I can find in this histogram.
Output for the above input is,
4

Explanation

I wrote the below code for the solution, but it is giving me wrong answer. I am unable to find any related article on the problem.
def findMaxSquare(arr):
    cur = 0
    for i in range(n-1):
        min_height = arr[i]
        length = 1
        if min_height > 0:
            cur = max(cur, 1)
        for j in range(i+1, n):
            min_height = min(min_height, arr[j])
            length += 1
            if min_height < length:
                break
            cur = max(cur, min(min_height, length))
    return cur

A: The idea is exactly similar to the Maximum rectangular area of a Histogram. Here, the idea for brute force is:
For current bar height, try to maximum expand on the Left side as well as Right side along with keeping track of the largest height of the left or right of the current bar. While we are doing that, we need to take the minimum of calculated expanded width and height of the current bar to mark the edge length of the maximum area square for the current bar.
The algorithm runs in O(n^2) and O(n) space.
Following is the optimized version (similar to the maximum rectangular area of Histogram) with Time complexity of O(n) and Space of O(n) in the worst case:
    public int maxSquareAreaHistogram(int[] heights) {
        Deque<Integer> stack = new LinkedList<>();
        int i=0, maxArea = 0;

        while (i < heights.length) {
            // Stack keeps track of last largest height. As soon as we
            // encounter a height which is less than the previous height,
            // we need to find the maximum area for the bar at the top of stack as
            // the area cannot be extended to the right.
            while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) {
                int idx = stack.pop();
                int width = stack.isEmpty() ? i : i - stack.peek() - 1;
                int edge = Math.min(width, heights[idx]);
                maxArea = Math.max(maxArea, edge * edge);
            }

            stack.push(i++);
        }

        while (!stack.isEmpty()) {
            int idx = stack.pop();
            int width = stack.isEmpty() ? i : i - stack.peek() - 1;
            int edge = Math.min(width, heights[idx]);
            maxArea = Math.max(maxArea, edge * edge);
        }

        return maxArea;
    }

PS: The code is written in Java.

A: I'd suggest a solution where you

*

*first identify all possible rectangles (for each bar, search to the left and to the right for other bars that have at least same height)

*then, for each rectangle, check what's smaller.. width or height. and with the smaller size, build up the square

*finally check which is the biggest square

In the sample given by you, both bar-5 and bar-7 would return a rectangle with height 4 and a width of 6... so you should have 2 rectangles and both resolve to a 4x4 square.


text:
Q: Is this the only solution to the problem? Find all mutually non-equivalent $A(p,q)$ so that $(Aq\rightarrow \overline{p}) = (p+A)$ is true regardless of $p$ and $q$, where $\overline{x}$ is negation, $xy$ is conjunction, $x+y$ disjunction, $x\rightarrow y$ implication and $x=y$ equivalence.
\begin{matrix}p&q&A&(Aq\rightarrow \overline{p}) = (p+A)\\
0&0&0&0\\
0&0&1&1\\
0&1&0&0\\
0&1&1&1\\
1&0&0&1\\
1&0&1&1\\
1&1&0&1\\
1&1&1&0
\end{matrix}
From the truth table we see that: $((Aq\rightarrow \overline{p}) = (p+A)) = \overline{p}\overline{q}A + \overline{p}qA + p\overline{q}\overline{A} + p\overline{q}A + pq\overline{A}$
$$\overline{p}\overline{q}A + \overline{p}qA + p\overline{q} + pq\overline{A} = 1$$
\begin{align}
A&=\overline{p}\overline{q}+\overline{p}q+\overline{(pq)}=\\
 &=\overline{p}+\overline{p}+\overline{q}=\\
 &=\overline{p}+\overline{q}
\end{align}
Cheking result
$$((\overline{p}+\overline{q})q\rightarrow \overline{p})=p+(\overline{p}+\overline{q})$$
For $p=0$ and $q=0$
$$
((1+1)0\rightarrow 1)=0+(1+1)\\
(0\rightarrow 1) = 1 \\
1=1 \\
$$
For $p=0$, $q=1$
$$
((1+0)1\rightarrow 1)=0+(1+0)\\
(1\rightarrow 1)=1 \\
1=1 \\
$$
For $p=1$, $q=0$
$$
((0+1)0\rightarrow 0)=1+(0+1)\\
(0\rightarrow 0)=1 \\
1=1 \\
$$
For $p=1$, $q=1$
$$
((0+0)1\rightarrow 0)=1+(0+0)\\
(0\rightarrow 0)=1 \\
1=1 \\
$$
This is a correct solution, but is it the only one?
I ask because the question uses the word all, and though that may not mean anything, I'd just like to check in case I missed something.

A: It seems to me you are correct up to here:
$$\overline{p}\overline{q}A + \overline{p}qA + p\overline{q} + pq\overline{A}
 = 1.$$
It does not follow that
$A=\overline{p}\overline{q}+\overline{p}q+\overline{(pq)}
= \overline p + \overline q,$ however.
Yes, it is true that
$$
(A = \overline p + \overline q)\rightarrow
(\overline{p}\overline{q}A + \overline{p}qA + p\overline{q} + pq\overline{A}
 = 1)
$$
for all possible truth assignments,
but the converse is not true.
The truth table shows that $A$ is one of two possible non-equivalent expressions, because for just one assignment to $p$ and $q,$
namely, $p=1, q=0,$ you have two choices for the value of $A.$

In particular, try the substitution $A = \overline p.$
With that substitution,
$Aq\rightarrow \overline p$ becomes
$\overline pq\rightarrow \overline p$, a tautology,
and $p+A$ becomes
$p+\overline p$, also a tautology,
so $(Aq\rightarrow \overline p)=(p+A).$
You can find this solution (rather than having to guess it) by selecting rows $2$, $4$, $5$, and $7$ from the truth table.

A: Line 5 of the table shows that while  $Aq\rightarrow \overline{p} = p+A$ is satisfied, you do not have that $A = \overline{p}+\overline{q}$, and so it is not even a solution to the equation.
Moreover, lines 5 and 6 demonstrate that you cannot express $A$ as a function of $p$ and $q$ to get all solutions, since in both lines $Aq\rightarrow \overline{p} = p+A$ is satisfied, and while the values of $p$ and $q$ are the same, the value of $A$ is not the same.

A: Just a tip for you, never write im terrbily sorry bc my english is so bad,because that tells me and others either that you are looking for compliments or you actually made grammar mistakes which makes the situation even worse because now we focus on the language rather than the mathematics. I know its polite to acknowledge weaknesses in some cultures but in stack exchange culture it is just a waste of alpah-betas


text:
Q: Como criar .BAT para renomear vários arquivos em várias pastas inserindo data e hora de criação? Alguém sabe como criar .bat para renomear vários arquivos em várias pastas inserindo data e hora de criação, e não a data atual?
Exemplo:
Nome                        Data e hora de Criação

SCP Dados.mdb               03/06/2016 10:26

Depois de renomear é para ficar assim:
Nome                        Data e hora de Criação

SCP Dados030616-1026.mdb    03/06/2016 10:26

Apagando qualquer caractere antes e depois do nome criado deixando a extensão .mdb "<-SCP Dados030616-1026->.mdb"
Já fiz isso:
@echo   Renomeando arquivo SCP Dados.mdb da BAHIA (BKP Manha)

dir \\S1WKSPCRCI\B$\CIBackups\Backup_BA\"SCP Dados.mdb" [AQUI ME MOSTRA A DATA]

set /p dt_arq_ba= Digite a DATA de Criacao do Arquivo da BAHIA: [AQUI INSIRO A DATA]

ren \\S1WKSPCRCI\B$\CIBackups\Backup_BA\SCP?Dados.mdb "SCP Dados%dt_arq_ba%.mdb" [AQUI ME DA O ARQUIVO RENOMEADO]

Está funcionando, mais só renomeia manualmente de um por um, queria automatizar com a data de criação do arquivo.

A: :: 1) Liste os arquivos e redirecione a saída para
 "%temp%\_file_origem.txt"
:: 2) Use um loop for para obter os caminhos e portar para o comando WMIC "\"="\\"
:: 3) Use outro loop for para obter a data de criação e salvar numa variável para renomear.
:: 4) Ajuste o layout de saída da data da criação para o formato pretendido:
:: 5) Setar o novo nome de arquivo e renomear retirando os caracteres indesejáveis:

*

*Obs.: Sobre a linha:
 echo/ ren "!_file_!" "SCP Dados!_date_create!.mdb"  && timeout /t 3 2>nul >nul

Adicionada apenas para debug, remover após verificar funcionamento.

@echo off && cd /d "%~dp0" & setlocal enableextensions enabledelayedexpansion
echo/  Renomeando arquivo SCP Dados.mdb da BAHIA ^(BKP Manha^)

rem  :: 1 ::
for %%i in (target origem) do echo/>"%temp%\_file_%%i.txt"
dir /s /b /a-d "\\S1WKSPCRCI\B$\CIBackups\Backup_BA\*.mdb" >>"%temp%\_file_origen.txt">>"%temp%\_file_origem.txt"

rem :: 2 ::
for /f "tokens=* delims= " %%i in ('type "%temp%\_file_origem.txt"') do (
     for /f "tokens=* delims= " %%I in ('dir /w /b "%%~i"') do set "_file_=%%~fI"&& call :_rename
     )
goto :eof

rem :: 3 ::
:_rename
for /f "tokens=1 delims=." %%r in ('wmic datafile where name^='!_file_:\^=\\!' get "creationdate" ^| findstr /v "CreationDate"') do (

rem :: 4 ::
     set "_date_=%%r"
     set _date_create=!_date_:~6,2!!_date_:~4,2!!_date_:~2,2!-!_date_:~8,2!!_date_:~10,2!

rem :: 5 ::
     echo/ ren "!_file_!" "SCP Dados!_date_create!.mdb"  && timeout /t 3 2>nul >nul
     for %%d in (file date_create) do set _%%d=<nul
     exit /b
    )


text:
Q: Click on Expand and Collapse button using selenium I have a group where i have to select the Expand icon and then expand further. Example: Click on User Directory and then "Native directory"

I used class method to click on "User Directory", which worked fine. But not able to move further. I used Class method, as xpath, css selector did not work and there is no element ID.
a=[]
a=driver.find_elements_by_class_name("bi-tree-view-expand-icon")
a[0].click()

The only difference is saw was in image title - Expand and Collapse
USER DIRECTORY html code

Native Directory html code

HTML code

<nobr>User Directories</nobr>

<nobr>Native Directory</nobr>

<nobr>Honeywell</nobr>

<nobr>Application Groups</nobr>

<nobr>File System</nobr>

Using CSS selector:
- User directory - .selected > td:nth-child(1) > img:nth-child(1)
- Native directory - .focused > tr:nth-child(2) > td:nth-child(1) > img:nth-child(1)


text:
Q: Support for OGC API - Records in MetaSearch I've been trying to access OGC API - Records through the MetaSearch Catalog of the latest release of QGIS (QGIS 3.24 'Tisler') but I ended up with the following issue:
Search error: {
    "code": "InvalidParameterValue",
    "description": "unknown query parameter: startindex"
}

While I can get consistent responses from the service description and the API, I can't load the associated information.
Has anyone experienced a similar problem?
The endpoint I am trying to access is: https://demo.pygeoapi.io/master/collections/dutch-metadata
I'm on Windows 10 using a version 3.24 of QGIS with OWSLib 0.25.0.

A: Changelog for OWSLib, which is used under the hood by QGIS MetaSearch, shows recent removal of support for startindex in place of  offset.
ref: https://github.com/geopython/OWSLib/commit/16ba31af36d155d1a89007ead2792218dcbb4fa7
I'm not sure whether startindex should ever have been expected to be supported, it was removed from OGC API Features (core) ~ https://github.com/opengeospatial/ogcapi-features/issues/75.
So the issue is I assume that the API instances, either never supported startindex, or have been updated to not support it, and  the metasearch plugin (or your version of it) is not yet using the latest OWSLib libraries.
As it says on the plugin page:

The OGC API - Records standard is currently in development and the current timeline for a public RFC by OGC is Q1 2022. This we ask you to take note of the draft status of the specification so you are aware that the specification may change a bit more over the next few months

Things are still evolving...

A: The issue should be solved with this PR:
https://github.com/qgis/QGIS/pull/47724


text:
Q: The use of string argument in an "IF" statement So, I was trying to make 2 javascript methods. The first method is to do the graphMaking AND the other to send the correct parameters to the first method to make the graph according to the sent parameters.The problem is, i need to loop the parameters sent with "arguments[i]" in order to form a string of:
data[i].Names == "A" || data[i].Names == "B"
and here's what i came up with:
  var numIndex = [];
  var cityString = "";
                for (var j = 1; j < arguments.length; j++)
                {
                    cityString = cityString + "||" + " data[i].Names==\"" + arguments[j] + "\"";
                    alert(arguments[j]);
                }
                cityString = "data[i].Names==\"" + arguments[0] + "\"";
    for (var i = 0; i < data.length; i++) {
      if (cityString)
      {
        numIndex.push(i);
      }
    }

what should my  if (cityString) be replaced with in rder for this to work?
Thanks in advance :)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
[EDIT] Okay heres the real deal why its C# is because i was doing the code in asp.net which was dumb of me and heres the real code:
function makeGraph() {
        var chrt = document.getElementById("myCanvas");
        $.ajax({
            url: '../api/values',
            type: 'GET',
            datatype: 'json',
            success: function (data) {
                var totalLabel = [];
                var totalValue = [];
                var totalLabel2 = [];
                var totalValue2 = [];
                var cityValue = [];
                var cityName = [];
                var numIndex = [];
                var cityString = "";
                for (var j = 1; j < arguments.length; j++)
                {
                    cityString = cityString + "||" + " data[i].Names==\"" + arguments[j] + "\"";
                    alert(arguments[j]);
                }
                cityString = "data[i].Names==\"" + arguments[0] + "\"";
                for (var i = 0; i < data.length; i++) {
                    totalLabel.push(data[i].Names);
                    totalValue.push(data[i].ValuesDouble);
                    totalLabel2.push(data[i].Names2);
                    totalValue2.push(data[i].ValuesDouble2);
                    if (cityString) {
                        numIndex.push(i);
                    }

                }
                for (var k = 0; k < numIndex.length; k++) {
                    cityValue.push(data[numIndex[k]].ValuesDouble);
                    cityName.push(data[numIndex[k]].Names);
                }

                $(function () {
                    Highcharts.chart('container', {
                        chart: {
                            type: 'column',
                            backgroundColor: 'black'
                        },
                        title: {
                            text: ''
                        },
                        xAxis: {
                            categories: cityName,

                        },
                        yAxis: {
                            min: 0,
                            tickInterval: 100000,
                            title: {
                                text: ''
                            }
                        },
                        legend: {
                            verticalAlign: 'top',
                            reversed: false,
                            backgroundColor: 'lightgrey'
                        },
                        plotOptions: {
                            series: {
                                stacking: 'normal'
                            }
                        },
                        series: [

                        {
                            name: 'Joe',
                            data: cityValue,
                            color: 'green'

                        },
                         {
                             name: 'Joe',
                             data: cityValue,
                             color: 'yellow'
                         },
                        {
                            name: 'Jane',
                            data: cityValue,
                            color: 'blue'
                        }]
                    });
                });

            }
        })

    }

A: I have finally found my own answer which was to use eval("if-statement") where if-statement is the if condition in the form of string


text:
Q: Can Jssor slider skip bad/inaccessible image URLs. Is it even possible? I would like to know if it is possible to setup Jssor slider to skip bad inaccessible URLs. I have a software that dynamically adds URLs, 1-12 pictures. The slider code I have is for 12 pictures total. Naturally, if only 11 pictures are used by this software, I have a blank thumbnail and image loading gif in the slider container. I would appreciate if you could point me in the right direction.
This is the code I am using:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Image Gallery Vertical Thumbnail Navigation Bar Theme - Jssor Slider, Slideshow with Javascript Source Code</title>

<thumbnailtemplate style=" width: 100%; height: 100%; border: none;position:absolute; top: 0; left: 0;"></thumbnailtemplate>

    javascript

A: You can remove slides with invalid picture url before initialization of Jssor Slider.
//remove invalid slides
var jssor_slider1 = new $JssorSlider$(...

Or rou can keep slides html code empty, and fill slides html code dynamically before initialization of Jssor Slider.
//fill slides html code
var jssor_slider1 = new $JssorSlider$(...


text:
Q: COLLATION 'utf8mb4_general_ci' is not valid for CHARACTER SET 'binary' I want to find a user in my Laravel app with name "Yılmaz" by searching for "Yilmaz"
by default in Laravel (with utf8mb4_unicode_ci as collation for my connection) this
\App\User::whereRaw('name LIKE ?', '%Yilmaz%')->get();

returns nothing.
As I found out at MySQL does not treat ı as i?, it works with collation utf8mb4_general_ci. However, it is not recommended to use utf8mb4_general_ci as default collation because it is not accuratly sorting.
My first try was
\App\User::whereRaw('name LIKE ? collate utf8mb4_general_ci', '%Yilmaz%')->get();

but this throws

SQLSTATE[42000]: Syntax error or access violation: 1253 COLLATION 'utf8mb4_general_ci' is not valid for CHARACTER SET 'binary' (SQL: select * from users where name LIKE %Yilmaz% collate utf8mb4_general_ci)

Next, I tried https://stackoverflow.com/a/58493518/2311074
\App\User::whereRaw('name LIKE convert(? using utf8mb4)', '%Yilmaz%')->get();

but this returns

SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and (utf8mb4_general_ci,IMPLICIT) for operation 'like' (SQL: select * from users where name LIKE convert(%Yilmaz% using utf8mb4))

How can I change collation to utf8mb4_general_ci in Laravel only for one query?

A: A combination of both works for me:
\App\User::whereRaw(
    'name LIKE convert(? using utf8mb4) collate utf8mb4_general_ci',
    '%Yilmaz%'
)->get();

But I am not sure if this is the best approach.


text:
Q: Enable and Disable Rows in a DataGrid I was playing around with enabling and disabling rows in a datagrid:

public IEnumerable GetDataGridRows(DataGrid grid)
{
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (null != row) yield return row;
    }
}

private void DisableGridRows()
{
    bool enableRow = false;
    var rows = GetDataGridRows(myGrid);
    foreach (DataGridRow dataRow in rows)
    {
        if (!enableRow)
        {
            dataRow.IsEnabled = false;
            enableRow = true;
        }
        else
        {
            enableRow = false;
        }
    }
}

The issue I am running into is that sometimes rows don't get disabled. When running in debug I can't duplicate the problem so it is making think something is going on with the grid not updating.
Any thoughts?


text:
Q: Display size problems with two monitors I just added a second monitor and my display is mis-sized. My macbook air monitor extends partly onto my external monitor. There are parts of the display that are off-screen - if I move my mouse to each side, the display will shift slightly with it, like the display is too big to fit the monitors. I've tweaked with the display resolution to no avail. Any ideas?

There's a black box in the bottom right corner where the mouse won't go, so the actual image is a bit taller than this. Also note how the left side of the window gets cut off.

I am running Snow Leopard; pretty sure zoom is not the issue.

A: That's what it looks like and that's the behavior when you zoom in on the laptop screen.  You can zoom in (even under Snow Leopard) via the trackpad or scroll wheel or keyboard.  In Snow Leopard there settings for screen zoom in System Preferences under "Universal Access" (both "Zoom" and "Zoom Options..."), "Mouse", and "Trackpad".  See what you have configured and use that to unzoom the screen.
I think the default zoom is ⌘+scroll wheel.
You have been able to zoom in on the screen as part of Universal Access for as long as I can remember.  You still can in Lion.


text:
Q: Problema con Flask API REST y Marshmallow Chicos, estoy realizando una API con el micro-framework 'Flask'. Básicamente lo que necesito realizar para este caso es poder insertar datos de un servicio con sus respectivas imágenes (galería). Servicio y galería son modelos por separados, por lo están relacionadas, es decir, una servicio puede tener muchas imágenes.
Tengo un Models/service.py:
class Service(db.Model):
    id          = db.Column(db.Integer, primary_key=True)
    service     = db.Column(db.String(80))
    gallery = db.relationship("Gallery")

    def __init__(self, service, gallery):

        self.service        = service
        self.gallery        = gallery

class Gallery(db.Model):
    id          = db.Column(db.Integer, primary_key=True)
    id_service  = db.Column(db.Integer, db.ForeignKey('service.id'))
    image_path  = db.Column(db.String(80))

    def __init__(self, id_service, image_path):

        self.id_service     = id_service
        self.image_path     = image_path

##### SCHEMAS #####

class GallerySchema(ma.Schema):
    class Meta:
        model: Gallery
        fields = ("image_path")
        ordered = True

class ServiceSchema(ma.Schema):

    class Meta:
        model: Service
    id = fields.Integer()
    service = fields.String(required=True)
    gallery = fields.Nested(GallerySchema, many=True)

Y también tengo Resources/service.py:

    def get(self):
        services = Service.query.all()
        services = services_schema.dump(services)
        return {'status': 'success', 'data': services}, 200

    def post(self):
        json_data = request.get_json()
        if not json_data:
               return {'status': 'error', 'message': 'No input data provided'}, 400

        # Validate and deserialize input
        try:
            data = service_schema.load(json_data)
        except ValidationError as err:
            return {'status': 'error', 'errors': err.messages}, 422

        service = Service(
            service     = data['service'],
            gallery  = data['gallery']
            )

        db.session.add(service)
        db.session.commit()

        result = service_schema.dump(service)

        return { 'status': 'success', 'data': result }, 201

La solicitud POST es básicamente:
{

    "service": "Servicio 1",
    "gallery": [
        {
                   "image_path": "test.png"
        },
         {
                   "image_path": "test.png"
        }
      ]
}

La respuesta cuando se trata del método POST muestra el siguiente error:
TypeError: unhashable type: 'dict'

Sin embargo, la respuesta cuando se trata del método GET es perfecta:
     "service": "Servicio de grifo",
     "gallery": [
             {"image_path": "test.png"},
       ]
   }

He recurrido a muchos ejemplos y búsquedas en Internet y se me ha dificultado conseguir la solución a mi caso. Si más que añadir, les doy las gracias de antemano.


text:
Q: Deploying a multi-container docker application to Azure Container Service I have a multi-container docker application on Github which can be accessed here. I want to deploy this docker application on Azure using the DC/OS orchestration with the help of the ACS cluster (I am able to run the application locally).
I followed this https://learn.microsoft.com/en-us/azure/container-service/container-service-setup-ci-cd guide on the azure docs and managed to deploy a sample application. I am not able to send a request to the server at that port. I tried to change the port of the docker-compose.yml file so that I can map port 5000 on the outside, to 8080 on the inside but it does not seem to work.
Code can be accessed on Github
The docker-compose.yml currently looks like this
services:
app:
  build: ./application
  image: ethercis-app

ports:
  - "5000:8080"
depends_on:
  - postgres

postgres:
  build: ./postgres
  image: ethercis-db

A: UPDATE: based on the additional information you provide in the comment below:
In your LB Rule you are using a probe on port 80 but your container is exposing port 5000.
See https://learn.microsoft.com/en-us/azure/container-service/container-service-enable-public-access
Original response:
ACS uses port 8080 for Marathon on the masters, not the agents. Your workloads run on the agents so there should be no problem in the port mapping. What are the symptoms that make you say there is a port clash?


text:
Q: Как добавить информацию к существующему компоненту в node_modules Angular 6? В общем установил компонент Share Buttons Component (кнопки шаринга в социальные сети) через NPM в проект и успешно его запустил, однако понадобилось добавить шаринг в OK.ru . Просмотрел исходный код, нашел как добавить, но проблема в том что если я изменю существующий компонент в node_modules, то при старте проекта папка node_modules заново обновляет все пакеты и мой код естественно стирается. Вопрос в том, существует ли способ как то ссылаться на файлы компонента и добавлять в него нужные строки кода?
По сути мне нужно добавить следующую информацию:
В файл @ngx-share\core\lib\share.models.d.ts в интерфейс IShareButtons добавить переменную ok?: IShareButton;
И в файл @ngx-share\core\fesm2015\ngx-share-core.js в const shareButtonsProp добавить следующий код:
ok: {
      type: 'ok',
        text: 'Ok',
        icon: ['fab', 'odnoklassniki'],
        color: '#FF9800',
        share: {
        desktop: 'https://connect.ok.ru/offer?url=',
          android: 'https://connect.ok.ru/offer?url=',
          ios: 'https://connect.ok.ru/offer?url=',
          operators: metaTagsOperators,
          metaTags: {
          url: 'u'
        }
      },
      count: {
        request: 'http',
          url: 'https://connect.ok.ru/offer?url=',
          operators: FacebookCountOperators
      }
    },

Если это как то можно сделать, расскажите пожалуйста как, буду очень благодарен.

A: Данный компонент поддерживает добавление кастомных кнопок, делается это следующим образом:
import { ShareButtons, metaTagsOperators } from "@ngx-share/core";

  constructor(shareButtons : ShareButtons) {
    shareButtons.addButton('ok', {
      type: 'ok',
      text: 'ok',
      icon: ['fab', 'odnoklassniki'],
      color: '#FF9800',
      share: {
        desktop: 'https://connect.ok.ru/offer?',
        android: 'https://connect.ok.ru/offer?',
        ios: 'https://connect.ok.ru/offer?',
        operators: metaTagsOperators,
        metaTags: {
          url :  'url' ,
          title :  'title' ,
          image :  'imageUrl'
        }
      }
    })
  }


text:
Q: Set CreatedBy and Owner when creating custom objects Is it possible to set CreatedBy and Owner when creating custom objects?
I am using Java API remotely to create custom object (using OAuth2 protocol).
When the objects are created they have the admin owner & createdBy.
This is damaging my data sharing policies and I would prefer to set the owenerId and createdBy fields on these objects - to match the user that created them.
Is it possible?


text:
Q: Cannot list step function tags from lambda I have wasted hours trying to find out why stepfunctions.listTagsForResource(...) is not defined when calling it from the AWS Lambda integrated editors like this:
const { tags } = await stepfunctions.listTagsForResource({
  resourceArn: process.env.STATE_MACHINE_ARN
}).promise()

lambda.listTags(...), however, seems to be available. I feel really stupid asking a question that (seemingly) simple:
How do I access AWS Step Functions resource tags using the AWS SDK? The docs certainly didn't help.
EDIT: It's worth noting that all the other list functions work as expected, listTagsForResource is the only one that is not defined.

A: Short Answer:
The version of aws-sdk available for use in the inline AWS Lambda editor is commonly antiquated; the current version there does not define the listTagsForResource function.
Long Answer:
Right now, running the following in the inline editor shows the aws-sdk version is 2.290.0:
var AWS = require("aws-sdk")
exports.handler = async (event) => {
    console.log(AWS.VERSION)
}

The latest version at this time (as in your docs link) is 2.409.0, which does, indeed, define the listTagsForResource function. You can confirm this in the v2.409.0 source code.
listTagsForResource was not, unfortunately, available in v2.290.0, so you won't be able to call it in the Lambda inline editor. (It appears that function was added in this commit for v2.382.0.)
It's still possible to use this function in Lambda, just not through the snazzy inline editor--you would have to build a package of your Node app and deploy it to Lambda as a Zip file.
So, your question isn't stupid at all; you've encountered a frustrating problem that all too often bites people wanting to try out something quickly in the inline editor.


text:
Q: What does ksize and k mean in cornerHarris? I was playing around with cornerHarris function in OpenCV. I could not understand what does ksize and k mean in the function. The documentation mentions ksize to be Aperture parameter of Sobel derivative used and k to be Harris detector free parameter in the equation but I am not sure what does it really mean?
Could someone help me understand?
I tried to detect corners in a cube and it came it as :

with the simple code I used from the documentation:
    import cv2
    import numpy as np

    filename = "cube.jpg"

    img = cv2.imread("./images/{}".format(filename))

    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    gray = np.float32(gray)
    dst = cv2.cornerHarris(gray,12,3,0.04)

    dst = cv2.dilate(dst,None)

    # Threshold for an optimal value, it may vary depending on the image.
    img[dst>0.01*dst.max()]=[0,0,255]

    cv2.imshow('dst',img)
    if cv2.waitKey(0) & 0xff == 27:
        cv2.destroyAllWindows()

I tried tweaking K but could not understand the role of it although I realized increasing it beyond a limit resulted in zero corner being detected.

A: Harris Corner detector is used to extract corners from grayscale images.
The Harris detector works by first calculating the image gradient, then calculating the covariance of the gradient, which is an approximation of the local Hessian.
It has 4 main steps:

*

*Edge detection (spatial derivative calculation) - The first step is to convert the grayscale image into an image of edges. There are many techniques to do this, but the cv2 uses a filter called Sobel's kernel, which gets cross-correlated with the original image. The ksize parameter determines the size of the Sobel kernel (3x3, 5x5, etc..). As the size increases, more pixels are part of each convolution process and the edges will get more blurry.

*Structure tensor setup - Basically we construct a matrix M which represents the direction of the gradients (edges) at every point of the image. This matrix can then be used to determine which of the edge pixels are corners:

*Harris response calculation - In this step, we calculate the "corner score" R of each edge pixel. The idea is that a pixel is defined as a corner only if it has big gradients in 2 perpendicular directions, which means the M matrix has 2 big eigenvalues (1 big eigenvalue will simply be an edge).
Here we can see Harris detector's free parameter - k. It is an empirically determined constant in the range [0.04,0.06]:

The k parameter lets you influence in this step, trading off precision and recall. So with a bigger k, you will get less false corners but you will also miss more real corners (high precision), with a smaller k you will get a lot more corners, so you will miss less true corners, but get a lot of false ones (high recall).

*Non-maximum suppression - The maxima of corner pixels in every local area is found and the rest are suppressed.


text:
Q: Image Changer in iOS I'm trying to get my app to do a basic background change from 3 screens.  Here is my .h file.
#import <UIKit/UIKit.h>

@class BIDYellowViewController;
@class BIDBlueViewController;
@class BIDGreenViewController;

@interface BIDSwitchViewController : UIViewController

@property (strong, nonatomic) BIDYellowViewController *yellowViewController;
@property (strong, nonatomic) BIDBlueViewController *blueViewController;
@property (strong, nonatomic) BIDGreenViewController *greenViewController;

- (IBAction)switchViews:(id)sender;

@end

and here is my method in the .m file that when the IBAction button is pressed, the superview will go from one screen to the next and continue in the loop of rotating them.
- (IBAction)switchViews:(id)sender {
//animations
    [UIView beginAnimations:@"View Flip" context:nil];
    [UIView setAnimationDuration:1.25];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//loads yellow
    if (self.yellowViewController.view.superview == nil) {
        if (self.yellowViewController == nil) {
            self.yellowViewController = [[BIDYellowViewController alloc]initWithNibName:@"YellowView" bundle:nil];
        }
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
//removes blue
        [self.blueViewController.view removeFromSuperview];
        [self.view insertSubview:self.yellowViewController.view atIndex:0];
//loads green
    } else if(self.greenViewController.view.superview == nil){
        if (self.greenViewController == nil) {
            self.greenViewController = [[BIDGreenViewController alloc] initWithNibName:@"GreenView" bundle:nil];
        }
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
//removes yellow
        [self.yellowViewController.view removeFromSuperview];
        [self.view insertSubview:self.greenViewController.view atIndex:0];

//loads blue
    } else if(self.blueViewController.view.superview == nil){
        if (self.blueViewController == nil) {
            self.blueViewController = [[BIDBlueViewController alloc] initWithNibName:@"BlueView" bundle:nil];
        }
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
//removes green
        [self.greenViewController.view removeFromSuperview];
        [self.view insertSubview:self.blueViewController.view atIndex:0];
    }
    [UIView commitAnimations];
}

the problem I'm having is that on the first loop, it repeats green screen twice and then continues on and works properly.  Am I missing something or should I be using a switch: case statement( and if so how would I do that)?

A: If want to repeat it continuously then use a global count variable as
static int count=0;

and use code as:
- (IBAction)switchViews:(id)sender
{
    [UIView beginAnimations:@"View Flip" context:nil];
    [UIView setAnimationDuration:1.25];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];

    switch (count) {
        case 0:

            [greenView removeFromSuperview];
            [blueView removeFromSuperview];

            [self.view addSubview:yellowView];
            break;
        case 1:

            [yellowView removeFromSuperview];
            [greenView removeFromSuperview];

            [self.view addSubview:blueView];

            break;
        case 2:

            [blueView removeFromSuperview];
            [yellowView removeFromSuperview];

            [self.view addSubview:greenView];

            break;

    }

    count++;

    if (count==3) {
        count=0;
    }

    [UIView commitAnimations];
}

you can also use three xib's with single ViewController, just need to change the class of your xib to ViewController's class you want to use like this---
BIDViewController *yellowViewController;
BIDViewController *blueViewController;
BIDViewController *greenViewController;

self.yellowViewController = [[BIDViewController alloc]initWithNibName:@"YellowView" bundle:nil];
self.greenViewController = [[BIDViewController alloc] initWithNibName:@"GreenView" bundle:nil];
self.blueViewController = [[BIDViewController alloc] initWithNibName:@"BlueView" bundle:nil];


text:
Q: USB barcode scanner and Arduino I have a USB barcode scanner and I have difficulty getting the data out of it. What I did was to get one of these adapters, and followed this tutorial with no luck. When I connect the ports as shown, it does not even power up the scanner to make a BEEP. With computer it works as a PS2 keyboard I guess without problem.
Any recommendation on how I can go forward?

A: That seems to be a USB scanner. It mentions in the instructable that it won't work for USB:

While I started this project with the intent of "let's use that old CueCat" I couldn't ac-tually find mine, so I bought a "new" one off of ebay.  When purchasing one, it is extremely important that you get one of the original PS2 models.  Some of the ones for sale at places like library thing are USB and those WILL NOT WORK with this project

If your intention is to talk to the Arduino, you would either need to use one with USB host capabilities (don't know if they exist as I have not used one) or RS232 (mentioned as supported by the scanner - the serial connection here) which would be a lot easier, just use the Arduino UART connection.
So, I think if you get an RJ45 to 9-pin serial cable, plug the RJ45 into scanner and the 9-pin female into a 9-pin male (may need MAX232 depending on signal levels, may be able to pug straight into Arduino if it uses same logic levels) it should work. There should be plenty of Arduino tutorials on using UART/RS232 and (if needed) MAX232.


text:
Q: highchart - irregular time series I am trying to plot irregular time series data onto high chart such as this example http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/spline-irregular-time/.
var dataArray = [
{ErrorDate: "2017-09-07", Brand: "Toyota", Count: 3},
{ErrorDate: "2017-09-02", Brand: "Ford", Count: 258},
{ErrorDate: "2017-09-03", Brand: "Ford", Count: 239},
{ErrorDate: "2017-09-04", Brand: "Ford", Count: 197},
{ErrorDate: "2017-09-05", Brand: "Ford", Count: 187},
{ErrorDate: "2017-09-06", Brand: "Ford", Count: 418},
{ErrorDate: "2017-09-07", Brand: "Ford", Count: 344},
{ErrorDate: "2017-09-03", Brand: "Mercedes", Count: 43},
{ErrorDate: "2017-09-04", Brand: "Mercedes", Count: 220},
{ErrorDate: "2017-09-03", Brand: "Chrysler", Count: 3},
{ErrorDate: "2017-09-04", Brand: "Chrysler", Count: 3},
{ErrorDate: "2017-09-06", Brand: "Chrysler", Count: 6},
{ErrorDate: "2017-09-07", Brand: "Chrysler", Count: 1}
];

I have my data in variable dataArray, and I've attempted to build out a series data based on each brand from the data coming in, however the challenge I am having is that I need to dynamically pass in the 'ErrorDate' along with each data point in the series so that it is plotted appropriately.
What would be the best way to accomplish this?
fiddle: https://jsfiddle.net/ntt5oc21/

A: You should prepare your data before passing it to Highcharts. This doc page should be helpful: https://www.highcharts.com/docs/chart-concepts/series
Here is your processed data:
var seriesArr = [];
dataArray.forEach(function(point) {

  var newPoint = [point.ErrorDate, point.Count],
    seriesIndex = seriesArr.findIndex((series) => series.name === point.Brand);

  if (seriesIndex === -1) {
    seriesArr.push({
      name: point.Brand,
      data: [newPoint]
    });
   } else {
    seriesArr[seriesIndex].data.push(newPoint);
  }
});

Then you can use one of the methods from METHODS AND PROPERTIES
For dynamically modifying the chart API section: http://api.highcharts.com/highcharts
For example:
seriesArr.forEach(function(series) {
    chart.addSeries(series);
});

Full demo: https://jsfiddle.net/kkulig/knhx3yvz/


text:
Q: How to realise the symbol check in JTextField? How to realise the symbol check in JTextField? I want to see in my JTextField only digits. What I should do?

A: NumberOnlyFilter.java:
import javax.swing.*;
import javax.swing.text.*;
import java.util.regex.*;
public class NumberOnlyFilter extends DocumentFilter
{

    public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
    {
        StringBuilder sb = new StringBuilder();
        sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.insert(offset, text);
        if(!containsOnlyNumbers(sb.toString())) return;
        fb.insertString(offset, text, attr);
    }
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
    {
        StringBuilder sb = new StringBuilder();
        sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.replace(offset, offset + length, text);
        if(!containsOnlyNumbers(sb.toString())) return;
        fb.replace(offset, length, text, attr);
    }

    /**
     * This method checks if a String contains only numbers
     */
    public boolean containsOnlyNumbers(String text)
    {
        Pattern pattern = Pattern.compile("[\\d]");
        Matcher matcher = pattern.matcher(text);
        boolean isMatch = matcher.matches();
        return isMatch;
    }

}

and then you can use it like:
((AbstractDocument)yourTxtField.getDocument()).setDocumentFilter(new NumberOnlyFilter());

A: Use a JFormattedTextField or a DocumentFilter.


text:
Q: Overriding core blocks with backend logic for specific theme Im having trouble of understading not the override itself but how to override from theme with backend logic. so here is my question do i have to override Blocks in app/code or can do it from app/design . I am asking this because i would like to have this overrides only for one theme.
For example i would like to show Working hours in footer (only for one theme) do i have to make a module and enable it or can i do it in theme itself so when the user picks that theme it gets overriden and shown in Footer Block? Or did i understood this wrong.
EDIT I have done it from the module as i need some backend logic. As i didnt know if that could be done from theme itself

A: You can overwrite files in app/design.
You have two options, to extend the existing XML which I would advise if you just need to add your own template. Or you can ignore existing XML and create you're own which is the overriding the XML.

I am presuming you just need to add a template and there is no backend logic required so a module is unnecessary. If this is not correct then ignore the rest as you will be better off keeping the template inside the module (app/code) so it remains with the rest of the module.
In your example I think it would be best to extend the existing XML and add a template. So if you wanted your template to display in the footer on every page you would do the following:

*

*Create layout:
app/design/frontend/PartyShowroom/default/Magento_Theme/layout/default.xml

*Add your block, example:
<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="footer">
            <block class="Magento\Framework\View\Element\Template" name="working.hours" after="footer.payments" template="Magento_Theme::html/footer/working-hours.phtml" />
        </referenceContainer>
    </body>
</page>

*Add your template:
app/design/frontend/**VENDOR**/**THEME**/Magento_Theme/templates/html/footer/working-hours.phtml

*Add your working hours to that template.
You could also do this with a static block, to do this use the below XML instead:
<block class="Magento\Cms\Block\Block" name="block_name">
    <arguments>
        <argument name="block_id" xsi:type="string">static_block_name_here</argument>
    </arguments>
</block>


text:
Q: Display of Calculated Items in Excel Pivot Table I created a PivotTable to present the budget for the year using 2 Categories (A, B) and also create a Calculated Item (= Spending / Budget) showing the percentage of the budget used.
In the first Pivot Table of the image the percentage calculation does all right, but when another subcategory is added makes the sum of all percentages instead of just showing the calculation of single row "A" that would have to be 79% (second PivotTable of the image)
Is there any way that, when the pivot table is collapsed, not show the Summarize Values of all Percentages Values within his Category, and when the PivotTable is expanded, only do the Calculated Item but row level appear as in the 3rd PivotTable of the image?

A: Pivot Tables are notorious for not having "that one obvious feature".
In this case, the "aggregate of the calculation" (e.g. sum of %Used) should really be the "calculation of the aggregate" (e.g. %Used of the sums). Unfortunately, there doesn't seem to be a way to coerce this out of the pivot table.
As a fallback position, you can use VBA.

*

*In the VBEditor, double click the worksheet containing the Pivot Table

*In the first drop down, select Worksheet.

*In the second drop down, select PivotTableUpdate

Insert the following code for the PivotTableUpdate event. It should work cleanly for many kinds of changes - I am sure there will be cases that I haven't dreamed up ...
Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
Dim rCell As Range, rCol As Range, rRow As Range
Dim lNewCol As Long, lBudgetCol As Long, lSpendCol As Long, lRow As Long
Dim sFormula As String

' Initial
Application.ScreenUpdating = False

' Clean up remnants of old calculation
For Each rRow In ActiveSheet.UsedRange.Rows
    For Each rCell In rRow.Cells
        If InStr(rCell.Formula, "=") Then
            rCell.Delete shift:=xlShiftToLeft
            GoTo NextCell
        End If
        If rCell.Value = "%Used" Then
            rCell.Columns(1).EntireColumn.Delete shift:=xlShiftToLeft
            GoTo NextCell
        End If
        If rCell.Value = "Budget" Then lBudgetCol = rCell.Column
        If rCell.Value = "Spending" Then lSpendCol = rCell.Column
NextCell:
    Next rCell
Next rRow

lNewCol = ActiveSheet.UsedRange.End(xlDown).End(xlToRight).Column + 1

' Implement new calculation and format
For Each rRow In ActiveSheet.UsedRange.Rows
    lRow = rRow.Rows(1).EntireRow.Row
    ActiveSheet.Cells(lRow, lNewCol - 1).Copy
    ActiveSheet.Cells(lRow, lNewCol).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
    If lRow = 4 Then ActiveSheet.Cells(lRow, lNewCol).Value = "%Used"
    If lRow > 4 And IsNumeric(ActiveSheet.Cells(lRow, lNewCol - 1).Value) Then
        sFormula = "=R" & lRow & "C" & lSpendCol & "/R" & lRow & "C" & lBudgetCol
        ActiveSheet.Cells(lRow, lNewCol).FormulaR1C1 = sFormula
        ActiveSheet.Cells(lRow, lNewCol).Style = "Percent"
    End If
Next rRow

' clean up
ActiveSheet.UsedRange.End(xlToLeft).Select
Application.ScreenUpdating = True

End Sub

The formula used to calculate %Used is (for example) =C5/B5 as opposed to =GETPIVOTDATA(...)/GETPIVOTDATA(...) for simplicity.
The following screenshots show results as filters and layout are modified ...


text:
Q: Symfony3 repository method doesn't work I'm trying to call a method in the repository ArticleRepository from my controller ArticleController. However it says :
Undefined method 'afficheArticle'. The method name must start with either findBy or findOneBy!

my Entity Article : (Entity\Article.php)
/**
 * Article
 *
 * @ORM\Table(name="Article", indexes={@ORM\Index(name="I_FK_Article_TypeArticle", columns={"idTypeArticle"})})
 * @ORM\Entity(repositoryClass="erp-gkeep\new_erp\gkeepBundle\Repository\ArticleRepository")
 */
class Article
{

my ArticleController (Controller\ArticleController)
 /**
     * @Route("viewArticle2", name="viewArticle2")
     */
    public function listAction2()
    {

        $data = $this->getDoctrine()->getRepository('gkeepBundle:Article')->afficheArticle();

my ArticleRepository
    <?php
/**
 * Created by PhpStorm.
 */

namespace gkeepBundle\Repository;

use Doctrine\ORM\EntityRepository;

class ArticleRepository extends EntityRepository
{

    public function afficheArticle(){
        $em=$this->getEntityManager();

        $query = $em->createQuery(
            'SELECT a.reference, a.designationfr, a.designationen, a.plan, a.url, a.datecreation, a.idtypearticle
     FROM gkeepBundle:Article a
     '
        );

        $articles = $query->getArrayResult();

        return $articles;
    }
}

if someone can help me please ! I'm pretty sure it's a stupid error :/

A: The value of repositoryClass in your mapping annotation needs to be the namespace + class name of your repository, it looks like you've maybe added some of the directory structure as well. - actually isn't a valid character in a PHP namespace, so the value you've got now definitely isn't right.
Try
@ORM\Entity(repositoryClass="gkeepBundle\Repository\ArticleRepository")

For reference: when this classname is not valid, Doctrine falls back to the default repository - this is what's throwing the error you're seeing.


text:
Q: Intercept each http request globally in flutter http package I have many API calls to the server, in many of them if I get a 401 response then I should forward the user to the login screen to refresh the token that I used for authorization.
http.post(
       URL,
       body: jsonEncode(loginHttpBody),)
    .then((response) {
      if (response.statusCode == 401) {
        Navigator.pushNamed(context, LoginScreen.id);
      }
    });

I need a way to make a global interceptor to check if any of the HTTP requests have 401 status to forward the user to log in screen, not writing this code in all of my HTTP requests.
The package that I use for my HTTP request is http


text:
Q: Ordenando resultados de relacionamento "ManyToManyField" com a mesma tabela em Django Estou com o relacionamento Many to Many com a mesma tabela, e preciso ordenar o resultado com a mesma sequencia da criação.
ex: adiciono Django básico, Django intermediário, Django avançado;
Tem q aparece nessa sequencia na visualização.
Já tentei {% for req in course.requirements.all|dictsort:"id" %} na view, mas sem resultado. Alguém poderia me dar uma ajuda. Desde já agradeço. Obrigado...
model.py:
class Course(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField()
    requirements = models.ManyToManyField("self", blank=True, symmetrical=False)
    created_at = models.DateTimeField(auto_now_add=True)

admin.py
class CourseContentInline(admin.TabularInline):
    model = CourseContent

class CourseAdmin(AjaxSelectAdmin):
    list_display = ('name')
    search_fields = ['id', 'name']
    list_filter = ['created_at']
    prepopulated_fields = {"slug": ("name",)}
    inlines = (CourseContentInline,)
    form = make_ajax_form(Course, {
        'requirements': 'courses',
    })

admin.site.register(Content, ContentAdmin)

view.py
def details(request, slug):
course = get_object_or_404(Course, slug=slug)
course_content = CourseContent.objects.filter(course=course)

context = {
    'course': course,
    'course_content': course_content,
}

return render(request, 'portal/courses/details.html', context)

details.html

{% if course.requirements.count >= 1 %}

Pré-Requisitos

            {% for req in course.requirements.all %}
                - {{ req.name }}

            {% endfor %}

{% endif %}

área admin

visualização

A: Problema resolvido!!!
O problema foi resolvido com o uso do pacote "django-sortedm2m". Dessa forma consegui ordenar o resultado de uma maneira simples e eficaz.
instalação
pip install django-sortedm2m

settings.py
INSTALLED_APPS = [
    'sortedm2m',
]

model.py
from sortedm2m.fields import SortedManyToManyField

class Course(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField()
    requirements = SortedManyToManyField("self", blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

criar e rodar as migrations
./manage.py makemigrations
./manage.py migrate

Problema resolvido!!!


text:
Q: ESP32 SerialBT wrong password from bluetooth terminal I connected to my ESP32 via bluetooth and put the password test to move the servo into a certain position. However, it keeps telling me its the wrong password via the terminal
I've tried classifying all variables as a string and also tried to add a " test" to see if that would change the results.
    #include <SoftwareSerial.h>
#include <ESP32Servo.h>
#include <BluetoothSerial.h>

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;
Servo myservo;
String password = "test";
String getinput = "";
const int lockPosition = 90;
const int unlockPosition = 180;

void setup() {
  myservo.attach(13);
  myservo.write(lockPosition);
  Serial.begin(115200);
  SerialBT.begin("ESP32 Lock"); // Name of the device
  Serial.println("The device is ready to pair");
}

void loop() {

  if (SerialBT.available()) {

    getinput = SerialBT.readStringUntil('\n');
    Serial.print("Received: ");
    Serial.println(getinput);

    if (getinput ==password) {

      SerialBT.println("Correct password, unlocking");
      myservo.write(unlockPosition);

    } else {

      myservo.write(lockPosition);
      SerialBT.println("Wrong Password");

    }
  }
}

A: The problem seems to occur via the userinput adding white spaces when being sent to the esp32. Solved it by using the trim() which removes any leading or trailing white spaces
yourvariable.trim();


text:
Q: How to format cell color based on another cell color I have a worksheet where the cells in column A change fill color based on weekend by a CF. I would like the entire connected row to change to that color based on color of cell in column A.

A: The only way I found was creating, manually, a rule for each colunm. It worked. If you want to do this only for this sheet, it will be easy to do. To create the condition to the colunm B, select a cell on the column B, go to CF, new rule, and paste the formula. So, aply to $B$1:$B$26. Do the same with columns C, D...
See the example
I edited the uploaded file too.


text:
Q: Problem while using caption for rows of multiple figures in 2 columns and many rows I have a collection of 10*2 figures which are subfigures of a main figure. I have been able to place them in my Latex document. The result is like as follows:
a    b
c    d
.
.
.
Figure: 1 (Caption of Figure: 1).

But I want to put caption to each row as well and want my figure to look like:
a    b
{Caption of first row}
.
.
.
Figure: 1 {....}

How can I achieve the requested layout?

A: You can set the entire sub-figure construction inside a tabular and then set by-pair captions as a regular \multicolumn{2}{c}:

\documentclass{article}

\usepackage{graphicx,subcaption}

\begin{document}

\begin{figure}[ht]
  \begin{tabular}{c@{\quad}c}
    \subcaptionbox{first}{\includegraphics[width=.3\linewidth]{example-image-a}} &
    \subcaptionbox{second}{\includegraphics[width=.4\linewidth]{example-image-b}} \\[1.5\normalbaselineskip]
    \multicolumn{2}{c}{This is a mid-figure caption} \\[.5\normalbaselineskip]
    \subcaptionbox{third}{\includegraphics[width=.5\linewidth]{example-image-a}} &
    \subcaptionbox{fourth}{\includegraphics[width=.3\linewidth]{example-image-b}} \\[1.5\normalbaselineskip]
    \multicolumn{2}{c}{This is another mid-figure caption} \\[.5\normalbaselineskip]
    \subcaptionbox{fifth}{\includegraphics[width=.2\linewidth]{example-image-a}} &
    \subcaptionbox{sixth}{\includegraphics[width=.2\linewidth]{example-image-b}} \\[1.5\normalbaselineskip]
    \multicolumn{2}{c}{This is a final mid-figure caption} \\[.5\normalbaselineskip]
  \end{tabular}
  \caption{A figure caption}
\end{figure}

\end{document}

The spacing between the by-pair captions and their respective sub-figures can be adjusted.


text:
Q: Equation with three variables I am confused as how to solve an equation with three squared variables to get its integer solutions? As:
$$x^2+y^2+z^2=200$$
Thanks!

A: All of $x^2$, $y^2$, and $z^2$ must be non-negative, so there are only finitely many cases to check.

A: If you are doing it to find solution to your previous question about the area of that triangle then you should use heron's formula and simplify it in terms of $x, y, z$ like,
$\sqrt{s(s-a)(s-b)(s-c)}=\dfrac{1}{4}\sqrt{(x+y+z)(x+y-z)(x-y+z)(-x+y+z)}$, which will simplify into,
$\dfrac{1}{4}\sqrt{-(x^4+y^4+z^4)+2(x^2y^2+y^2z^2+z^2x^2)}$
Now you can substitute the values to get the required area.

A: I would do it this way: (it takes just few minutes)
Let's assume $x<=y<=z$, without loss of generality.
$z$ must be larger than $8$, since $3*8^2 = 192 < 200$.
$z$ must be smaller than $15$, since $15^2 = 225 > 200$.
Now, there are six possibilities:
$$x^2+y^2=200-9^2=119$$
$$x^2+y^2=200-10^2=100$$
$$x^2+y^2=200-11^2=79$$
$$x^2+y^2=200-12^2=56$$
$$x^2+y^2=200-13^2=31$$
$$x^2+y^2=200-14^2=4$$
Then, according to the list of Pythagorean triples, only this solution can exist:

$$x=6, y=8, z=10$$

The list above assumes x<>0, and for x=0, we easily get two more solutions:

$$x=0, y=2, z=14$$

and

$$x=0, y=10, z=10$$

Of course, if variables can be negative, there is also a number of solutions directly derived from last three ones.


text:
Q: Installation failed. Failed to receive heartbeat from agent I got this error

Installation failed. Failed to receive heartbeat from agent.

when I was installing cloudera on single node.
This is what is in my /etc/hosts file:
127.0.0.1   localhost
192.168.2.131   ubuntu

This is what is in my /etc/hostname file:
ubuntu

And this is the error in my /var/log/cloudera-scm-agent file:
[13/Jun/2014 12:31:58 +0000] 15366 MainThread agent        INFO     To override these variables, use /etc/cloudera-scm-agent/config.ini. Environment variables for CDH locations are not used when CDH is installed from parcels.
[13/Jun/2014 12:31:58 +0000] 15366 MainThread agent        INFO     Re-using pre-existing directory: /run/cloudera-scm-agent/process
[13/Jun/2014 12:31:58 +0000] 15366 MainThread agent        INFO     Re-using pre-existing directory: /run/cloudera-scm-agent/supervisor
[13/Jun/2014 12:31:58 +0000] 15366 MainThread agent        INFO     Re-using pre-existing directory: /run/cloudera-scm-agent/supervisor/include
[13/Jun/2014 12:31:58 +0000] 15366 MainThread agent        ERROR    Failed to connect to previous supervisor.
Traceback (most recent call last):
  File "/usr/lib/cmf/agent/src/cmf/agent.py", line 1236, in find_or_start_supervisor
    self.get_supervisor_process_info()
  File "/usr/lib/cmf/agent/src/cmf/agent.py", line 1423, in get_supervisor_process_info
    self.identifier = self.supervisor_client.supervisor.getIdentification()
  File "/usr/lib/python2.7/xmlrpclib.py", line 1224, in __call__
    return self.__send(self.__name, args)
  File "/usr/lib/python2.7/xmlrpclib.py", line 1578, in __request
    verbose=self.__verbose
  File "/usr/lib/cmf/agent/build/env/lib/python2.7/site-packages/supervisor-3.0-py2.7.egg/supervisor/xmlrpc.py", line 460, in request
    self.connection.request('POST', handler, request_body, self.headers)
  File "/usr/lib/python2.7/httplib.py", line 958, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python2.7/httplib.py", line 992, in _send_request
    self.endheaders(body)
  File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
    self.send(msg)
  File "/usr/lib/python2.7/httplib.py", line 776, in send
    self.connect()
  File "/usr/lib/python2.7/httplib.py", line 757, in connect
    self.timeout, self.source_address)
  File "/usr/lib/python2.7/socket.py", line 571, in create_connection
    raise err
error: [Errno 111] Connection refused
[13/Jun/2014 12:31:58 +0000] 15366 MainThread tmpfs        INFO     Reusing mounted tmpfs at /run/cloudera-scm-agent/process
[13/Jun/2014 12:31:59 +0000] 15366 MainThread agent        INFO     Trying to connect to newly launched supervisor (Attempt 1)
[13/Jun/2014 12:31:59 +0000] 15366 MainThread agent        INFO     Successfully connected to supervisor
[13/Jun/2014 12:31:59 +0000] 15366 MainThread _cplogging   INFO     [13/Jun/2014:12:31:59] ENGINE Bus STARTING
[13/Jun/2014 12:31:59 +0000] 15366 MainThread _cplogging   INFO     [13/Jun/2014:12:31:59] ENGINE Started monitor thread '_TimeoutMonitor'.
[13/Jun/2014 12:31:59 +0000] 15366 MainThread _cplogging   INFO     [13/Jun/2014:12:31:59] ENGINE Serving on ubuntu:9000
[13/Jun/2014 12:31:59 +0000] 15366 MainThread _cplogging   INFO     [13/Jun/2014:12:31:59] ENGINE Bus STARTED
[13/Jun/2014 12:31:59 +0000] 15366 MainThread __init__     INFO     New monitor: (<cmf.monitor.host.HostMonitor object at 0x305b990>,)
[13/Jun/2014 12:31:59 +0000] 15366 MainThread agent        WARNING  Setting default socket timeout to 30!
[13/Jun/2014 12:31:59 +0000] 15366 MonitorDaemon-Scheduler __init__     INFO     Monitor ready to report: ('HostMonitor',)
[13/Jun/2014 12:31:59 +0000] 15366 MainThread agent        INFO     Using parcels directory from server provided value: /opt/cloudera/parcels
[13/Jun/2014 12:31:59 +0000] 15366 MainThread parcel       INFO     Agent does create users/groups and apply file permissions
[13/Jun/2014 12:31:59 +0000] 15366 MainThread downloader   INFO     Downloader path: /opt/cloudera/parcel-cache
[13/Jun/2014 12:31:59 +0000] 15366 MainThread parcel_cache INFO     Using /opt/cloudera/parcel-cache for parcel cache
[13/Jun/2014 12:31:59 +0000] 15366 MainThread agent        INFO     Active parcel list updated; recalculating component info.
[13/Jun/2014 12:32:04 +0000] 15366 Monitor-HostMonitor throttling_logger INFO     Using java location: '/usr/lib/jvm/java-7-oracle-cloudera/bin/java'.
[13/Jun/2014 12:32:04 +0000] 15366 Monitor-HostMonitor throttling_logger ERROR    Failed to collect NTP metrics
Traceback (most recent call last):
  File "/usr/lib/cmf/agent/src/cmf/monitor/host/ntp_monitor.py", line 39, in collect
    result, stdout, stderr = self._subprocess_with_timeout(args, self._timeout)
  File "/usr/lib/cmf/agent/src/cmf/monitor/host/ntp_monitor.py", line 32, in _subprocess_with_timeout
    return subprocess_with_timeout(args, timeout)
  File "/usr/lib/cmf/agent/src/cmf/monitor/host/subprocess_timeout.py", line 40, in subprocess_with_timeout
    close_fds=True)
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
[13/Jun/2014 12:32:12 +0000] 15366 Monitor-HostMonitor throttling_logger ERROR    Timeout with args ['/usr/lib/jvm/java-7-oracle-cloudera/bin/java', '-classpath', '/usr/share/cmf/lib/agent-5.0.2.jar', 'com.cloudera.cmon.agent.DnsTest']
None
[13/Jun/2014 12:32:12 +0000] 15366 Monitor-HostMonitor throttling_logger ERROR    Failed to collect java-based DNS names
Traceback (most recent call last):
  File "/usr/lib/cmf/agent/src/cmf/monitor/host/dns_names.py", line 67, in collect
    result, stdout, stderr = self._subprocess_with_timeout(args, self._poll_timeout)
  File "/usr/lib/cmf/agent/src/cmf/monitor/host/dns_names.py", line 49, in _subprocess_with_timeout
    return subprocess_with_timeout(args, timeout)
  File "/usr/lib/cmf/agent/src/cmf/monitor/host/subprocess_timeout.py", line 81, in subprocess_with_timeout
    raise Exception("timeout with args %s" % args)
Exception: timeout with args ['/usr/lib/jvm/java-7-oracle-cloudera/bin/java', '-classpath', '/usr/share/cmf/lib/agent-5.0.2.jar', 'com.cloudera.cmon.agent.DnsTest']

A: I am facing similar problems. I've found how to solve the problem:
ERROR    Failed to collect NTP metrics

It's because NTP service is not installed/started.
Try:
sudo apt-get update && sudo apt-get install ntp
sudo service ntp start

A: Got the same error, please assure that your hostname could be translated to your ip.
Run ifconfig -a lookup your ip address for eth0, then run dig or host command using your FQDN and review the ip address is the same that ifconfig shows.
Follow this tutorial from cloudera: http://www.cloudera.com/content/cloudera-content/cloudera-docs/CDH4/latest/CDH4-Installation-Guide/cdh4ig_topic_11_1.html

A: When installing Cloudera 5.2 on AWS, this error occurs. It's a known issue and Cloudera put the workaround on their website (copied here):
Installing on AWS, you must use private EC2 hostnames.
When installing on an AWS instance, and adding hosts using their public names, the installation will fail when the hosts fail to heartbeat.
Workaround:
Use the Back button in the wizard to return to the original screen, where it prompts for a license.
Rerun the wizard, but choose "Use existing hosts" instead of searching for hosts. Now those hosts show up with their internal EC2 names.
Continue through the wizard and the installation should succeed.

A: Ensure that the host's hostname is configured properly.
Ensure that port 7182 is accessible on the Cloudera Manager server (check firewall rules).
Ensure that ports 9000 and 9001 are free on the host being added.
Check agent logs in /var/log/cloudera-scm-agent/ on the host being added (some of the logs can be found in the installation details).


text:
Q: MsTest ClassInitialize and Inheritance I have a base class for my tests which is composed in the following way:
[TestClass]
public abstract class MyBaseTest
{
   protected static string myField = "";

   [ClassInitialize]
   public static void ClassInitialize(TestContext context)
   {
       // static field initialization
       myField = "new value";
   }
}

Now I am trying to create a new test that inherits from the base, with the following signature:
[TestClass]
public class MyTest : MyBaseTest
{
   [TestMethod]
   public void BaseMethod_ShouldHave_FieldInitialized()
   {
       Assert.IsTrue(myField == "new value");
   }
}

The ClassInitialize is never called by the child tests ... What is the real and correct way of using test initialization with inheritance on MsTest?

A: Unfortunately you cannot achieve this that way because the ClassInitializeAttribute Class cannot be inherited.
An inherited attribute can be used by the sub-classes of the classes that use it. Since the ClassInitializeAttribute cannot not be inherited, when the MyTest class is initialized the ClassInitialize method from the MyBaseTest class cannot be called.
Try to solve it with another way. A less efficient way is to define again the ClassInitialize method in MyTest and just call the base method instead of duplicating the code.

A: A potential workaround is to define a new class with AssemblyInitializeAttribute instead. It has a different scope, obviously, but for me it meets my needs (cross-cutting concerns, which just so happen to require exactly the same settings for every test class and test method.)
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyTests
{
  [TestClass]
  public sealed class TestAssemblyInitialize
  {
    [AssemblyInitialize]
    public static void Initialize(TestContext context)
    {
      ...
    }
  }
}

A: Use a static constructor on a base class? It's executed only once, by design, and it doesn't have the weird limitation on inheritance, like the ClassInitializeAttribute.

A: There is a parameter for the ClassInitialize and ClassCleanup attributes:
[ClassInitialize(InheritanceBehavior.BeforeEachDerivedClass)]
public static void ClassInitialize(TestContext context)
{
   // gets called once for each class derived from this class
   // on initialization
}

[ClassCleanup(InheritanceBehavior.BeforeEachDerivedClass)]
public static void Cleanup()
{
   // gets called once for each class derived from this class
   // on cleanup
}

which will actually do what you want.

A: UPDATE: Added lock to avoid multi-threading issues...
We know that a new instance of the class is constructed for every [TestMethod] in the class as it gets run. The parameter-less constructor of the base class will be called each time this happens. Couldn't you simply create a static variable in the base class and test it when constructor runs?
This helps you to not forget to put the initialization code in the sub-class.
Not sure if there's any drawback to this approach...
Like so:
public class TestBase
{
    private static bool _isInitialized = false;
    private object _locker = new object();

    public TestBase()
    {
        lock (_locker)
        {
          if (!_isInitialized)
          {
            TestClassInitialize();
            _isInitialized = true;
          }
        }
    }

    public void TestClassInitialize()
    {
        // Do one-time init stuff
    }
}
public class SalesOrderTotals_Test : TestBase
{
    [TestMethod]
    public void TotalsCalulateWhenThereIsNoSalesTax()
    {
    }
    [TestMethod]
    public void TotalsCalulateWhenThereIsSalesTax()
    {
    }
}


text:
Q: Php5 - Unicode string length I need to get correct length of unicode text getting via HTTP Post/get.
"हेल्लो स्टैक ओवरफ्लो"
When I set a browser's character encoding as Unicode, then
mb_strlen($text) gives me correct length of unicode string which is 20.
But when I submit form with browsers encoding as 'ISO-8859-1', it behaves oddly.
mb_strlen($text) gives me byte length of unicode string which is 128, which is wrong and also
mb_detect_encoding($text, "auto") returns me ascii.
while
mb_detect_encoding($text, "UTF-8") returns UTF-8.
I need correct length of unicode text, irrespective of Browser charset.
anyone can help me sovling this problem?
Regards,
Sandip

A: ISO-8859-1, aka the Western European character set, refers to the extended Roman alphabet, which does not include the characters you specified above (is that Hindi? I'm not so well-versed in such languages). The mb_detect_encoding call will not detect your encoding, because you mangled the characters into ISO-8869-1, which doesn't support the characters you gave it.
You should specify an encoding that supports the character types that you need to display. UTF-8 would probably be your best bet. You can explicitly set the encoding in your HTTP headers using the Content-Encoding header. You can also repeat this in a meta tag in your HTML for maximum support.

A:
I need correct length of unicode text, irrespective of Browser charset.

You can't know the length if you don't know the encoding. A string of bytes may represent a different valid string in different encodings at once. mb_detect_charset gives you nothing more than an unreliable guess.
There is a sneaky way many modern browsers support for them to tell you what encoding they have used, which is to include this hack (originating in IE) in the form:
<input type="hidden" name="_charset_"/>

You'll then get an encoding name submitted in that field, which you can theoretically use to mb_convert_encoding a string you have received to UTF-8 for further handling. You definitely want to keep all your strings in a single encoding in your scripts, only converting to other encodings at the input/output ends where necessary; it's very unpleasant trying to keep track of byte strings in arbitrary encodings.
However you can't convert a ISO-8859-1 string containing हेल्लो... to UTF-8 because ISO-8859-1 can't contain those characters. Your data have already been corrupted as described by deceze: when you submit form data in an encoding that can't contain the characters, the browser escapes them using HTML &#...; character references. This is a lossy conversion that you can't accurately recover, because you can't tell the difference between these escapes and actual ampersand-hash sequences the user originally typed. Never rely on this long-standing but quirky and undesirable behaviour.
In general it's really much better just to ensure that the form submission always comes in using a known encoding that covers all the characters you are likely to want. That way you don't have to worry about conversion, or whether there has been any character-reference-mangling. The only sensible encoding to pick for this purpose is UTF-8. (UTF-16 has some browser problems apart from being generally less efficient.)
Browsers submit forms using the same encoding that they used to display the page, so use the Content-Type: text/html;charset=utf-8 header and/or <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> equivalent to specify the page encoding, rather than letting the browser guess. It will then use that encoding for the form submission too.
The only remaining wrinkle is that if the user deliberately overrides the encoding of the page with the form in, you'll get the wrong data submitted. This is very unlikely to happen unless your page is already broken, so usually it's not worth bothering with.
If you want to cover that possibility you can set the attribute accept-charset on the form. However! This doesn't work right in IE, which only treats accept-charset as a fallback suggestion for when it has form data that doesn't fit within the page's natural encoding. If you want to ensure you get UTF-8 even in the face of the user changing the encoding to something else, you'd have to include some data in the form that can't be encoded in any of the other encodings the user is able to pick. The traditional way of doing that is:
<form accept-charset="utf-8">
    <input type="hidden" name="unicodesnowman" value="☃"/>
    ...


text:
Q: Ruby On Rails - Show pre-download page with a timer, initiate download in background once timer expires,then redirect to another view I have already looked at answers to this question send_data - open file in new browser window? but that do not solve my problem.
I have a website where user will click on a download button. Upon clicking the the button, he is to be taken to a page where I will show some information, along with a banner saying that download will begin in N seconds. Once the timer expires the file will be downloaded (not displayed). Then the current page has to be automatically redirected to another 'post download' page in my controller. I am encountering problem implementing this.
What I have already done:
I am using send_data from my controller to send the file as binary data to browser and ask the broswer to download it instead of displaying it.
send_data buffer, :filename => @organisation.id.to_s + '.key', :disposition => "attachment"

I am using "target"="_blank" to initiate download on a new page.
I open in a new window.

Can you suggest how I can achieve the intended flow?

A: Here is how I achieved this.
You can not achieve this by using two controller actions alone. You need at least three controller actions and some client side Javascript.
Here is what you need to do.

*

*Render a pre-download page where you show any ads or details or yet another 'Download Now' button.

*With-in the pre-download page, create a timer in javascript. When the timer expires , using java script open the direct download link with target set as "_blank"
window.open("https://example.com/direct_download_url" , "_blank");

*Using java script, redirect the current page to a 'post-download' page.
window.location.href = "https://www.example.com/after_download_page";

*Use send_data with depostion as "attachment" in your controller action for direct download
send_data buffer, :filename => "file_name", :disposition => "attachment"

Here is how the controller file would looks like.
class DownloadsController < ApplicationController

  def pre_download_page

  end

  def direct_download
     #Your logic here
     #.......
     send_data buffer, :filename => "file_name", :disposition => "attachment"
  end

  def after_download_page

  end
end

Here is how View for pre_download_page would look like

A: Thanks for taking the time!
In the mean time I resolved the issue in a simpler manner. Take a look:
*In my controller: *
def generate_key
   ... LOGIC ...

send_data buffer, :filename => 'whatever.key', :disposition => "attachment", :type => 'text/plain'

end
In my view:
link_to 'Label', generate_key_organisation_path, target: "_blank"


text:
Q: How to do Wake On LAN by Qt 5? I found this tutorial for wake on LAN,but I can not understand it completely. It is implemented in Qt3. I want the wake on LAN functionality which could be compiled with Qt5. How can I use the mentioned code to wake a computer through LAN using Qt5?

A: Here is an implementation for wake on lan which compiles with Qt 5. The function takes the MAC address of the destination computer as an argument and broadcasts the relevant UDP packet :
void MyClass::wakeOnLan(QString MAC)
{
    char MACAddr [6];
    char MagicPacket [102]; // Magic package for remote boot

    int j = sscanf (MAC.toLatin1().data(), "%2x-%2x-%2x-%2x-%2x-%2x",
                    & MACAddr [0], & MACAddr [1], & MACAddr [2], & MACAddr [3], & MACAddr [4], & MACAddr [5]);

    // Set to hexadecimal before the magicpacket array 6 characters ff
    memset (MagicPacket, 0xff, 6);

    int packetsize = 6; // the beginning of the initial value is 6, do not wrong. I is because the effect of the initial value of the written as 0, it is too effortless.
    // Build MagicPacket.
    for (int i = 0; i <16; i++)
    {
        memcpy (MagicPacket + packetsize, MACAddr, 6);
        packetsize += 6;
    }

    QHostAddress FakeAddress;
    FakeAddress.setAddress ("192.168.0.255");

    QUdpSocket udpSocket;
    udpSocket.writeDatagram(MagicPacket, 102, FakeAddress, 9);
}


text: Q: .htaccess on local to redirect all CDN to local files when i use localhost i'm developing a web site using bootstrap, jquery and google-fonts By CDN, sometimes i'm on moving and without internet connexion, is it possible to create a .htaccess on my wamp server that can redirect all my CDN links to local images when i'm testing my code by localhost ?


text:
Q: Excel formula is giving me an answer in date format instead of a number My data looks like this

Essentially I need to get the earliest buy date and subtract from all the sell dates for the same account number. To get the earliest buy date, I used the following formula:
=MINIFS(G:G,C:C,C53,E:E,"Buy")

G is the column where all the dates are, C is is where the account numbers are and column E is where the BUY and SELLs are located.
However when I do this formula
==SUMIFS(H:H,C:C,C48,E:E,"Buy")-H48

It is giving me a date number instead of the difference between two dates. Any ideas why?


text:
Q: how to implement regexp_substr in hive? So i have an oracle query :
SELECT REGEXP_SUBSTR('BOND~CRR~CD~DAKAR_2299913320','[^~]+',1,3) FROM DUAL

from that query the result should be like : CD
now, my question is how to implement that query in hive, because from what i know, hive does not have REGEXP_SUBSTR syntax, so far what i have already try was :
select regexp_extract('BOND~CRR~CD~DAKAR_2299913320','[^~]+',0)

but the result was : BOND
when i change my query to :
select regexp_extract('BOND~CRR~CD~DAKAR_2299913320','[^~]+',2)

it was give a semanticExecption : wrong arguments '2'
so is there any way to implement that oracle query in hive ?

A: You can use SPLIT Function instead of REGEXP
select split('BOND~CRR~CD~DAKAR_2299913320','[\~]')[2]

For more details refer below link
https://dwgeek.com/hive-string-functions-examples.html/

A: As described here: https://cwiki.apache.org/confluence/display/hive/languagemanual+udf the last argument is the index of capturing group.
You've got the wrong arguments '2' exception because in your example you didn't have any capture group (except the general 0)
REGEXP_SUBSTR works as expected, only one thing you have to fix is the regexp.
By example:
select regexp_extract('BOND~CRR~CD~DAKAR_2299913320','^[^~]*~[^~]*~([^~]*)~.*',1);

will give you the desired result.
Hive uses java implementation of regexp so the best source of knowledge will be: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html


text:
Q: Swift - Why is Class Instance Appended to Array Deinitialized? I'm having memory problems with the Swift code below.
In GameScene's sceneDidLoad(), I add a GKEntity to the array "entities," but in GameScene's update(), the array "entities" is empty. Shouldn't the reference to "entity" be preserved in "entities"? Why is "entity" being deinitialized at the end of sceneDidLoad()?
import GameplayKit

class GraphicsComponent: GKComponent {
  override func update(deltaTime: TimeInterval) {
    // ...
  }
}

class GameScene: SKScene {

  var entities = [GKEntity]()

  override func sceneDidLoad() {
    let entity = GKEntity()
    entity.addComponent(GraphicsComponent())
    entities.append(entity)
  }

  override func update(_ currentTime: TimeInterval) {

    // ...

    for entity in entities {
      entity.update(deltaTime: dt)
    }
  }
}

I was expecting the "entity" instance to be preserved because a reference to it was added to the "entities" array. If that reference remained, then why was the instance destroyed?
EDIT:
I found that if I move the code in sceneDidLoad() to didMove(), everything works as expected. I still didn't know why, so I looked around in the boilerplate that Xcode puts in GameViewController and found where sceneDidLoad() and didMove() are each called. I found that if I add an entity to the scene.entities array in sceneDidLoad(), the scene.entities array will be empty when the code steps into the if statement that begins with if let scene = GKScene(fileNamed: "GameScene"). Is the if let creating a temporary GKScene?
class GameViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    // This "if let" will call sceneDidLoad(), which appends a new entity to scene.entities.
    if let scene = GKScene(fileNamed: "GameScene") {
      // scene.entities.count = 0

      if let sceneNode = scene.rootNode as! GameScene? {

        sceneNode.entities = scene.entities
        sceneNode.graphs = scene.graphs

        sceneNode.scaleMode = .aspectFill

        if let view = self.view as! SKView? {
          view.presentScene(sceneNode) // This calls didMove()
          view.ignoresSiblingOrder = true
          view.showsFPS = true
          view.showsNodeCount = true
        }
      }
    }
  }
}