text:
Q: Jacoco: unable to read execution data file, ant task Info:
java version: 1.8.0_66
ant version: 1.9.6
What I want to do:
Provide a code coverage report for the server's code that is running on AWS windows 2k12 server.
What I did:

*

*Stop the server completely.

*Put jacocoagent.jar into server's bin folder. Note: this is inside Program Files folder

*Append -javaagent settings to JAVA_OPTS that is used during server start up.

*Start the server.

*Run my sample test from my local laptop.

*Stop the server completely. This produced a 184kb jacoco.exec.

*Copied my build.xml to the same directory where the jacoco.exec is located. C:/path/to/exec/jacoco.exec

*Copied jacocoant.jar to C:/path/to/jacocoant.jar

*cd into C:/path/to/exec/ and run command "ant"

Result:
Got error unable to read execution data file C:/path/to/exec/jacoco.exec
Build.xml:
<project name="Example" default="rebuild" xmlns:jacoco="antlib:org.jacoco.ant">

<description>
  Example Ant build file that demonstrates how a JaCoCo coverage report
  can be itegrated into an existing build in three simple steps.
</description>

<property name="result.dir" location="." />
<property name="result.classes.dir" location="${result.dir}/path/to/classes" />
<property name="result.report.dir" location="${result.dir}/report" />
<property name="result.exec.file" location="${result.dir}/jacoco.exec" />

<!-- Step 1: Import JaCoCo Ant tasks -->
<taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml">
    <classpath path="../jacocoant.jar" />
</taskdef>

<target name="clean">
    <delete dir="${result.report.dir}" />
</target>

<target name="report">
    <!-- Step 3: Create coverage report -->
    <jacoco:report>

        <!-- This task needs the collected execution data and ... -->
        <executiondata>
            <file file="${result.exec.file}" />
        </executiondata>

        <!-- the class files and optional source files ... -->
        <structure name="JaCoCo Code Coverage Report">
            <classfiles>
                <fileset dir="${result.classes.dir}" >
                    </fileset>
            </classfiles>
            <sourcefiles encoding="UTF-8">
                <fileset dir="${src.dir}" />
            </sourcefiles>
        </structure>

        <!-- to produce reports in different formats. -->
        <html destdir="${result.report.dir}" />
        <csv destfile="${result.report.dir}/report.csv" />
        <xml destfile="${result.report.dir}/report.xml" />
    </jacoco:report>
</target>

I am not sure if the problem is with exec file (it is corrupted maybe) or is with my entire setup.
Any help to identify and help solving the problem is appreciated!!!
Thanks!

A: I got this when using gradle and jaCoCo.
I deleted the build/ directory and reran ./gradlew jacocoTestReport, this time passing.

A: I have the same problem recently, it took me long time to figure this out. I hope how I fix this will help you or someone else.

*

*Use ant -verbose report to see the detailed information. I used "ant -verbose report" and got this message: "java.io.IOException: Incompatible version 1007".

*As I am using maven, I added the following lines to my pom.xml. Note: version is the same as your javaagent's version.

 <dependency> <groupId>org.jacoco</groupId> <artifactId>org.jacoco.ant</artifactId> <version>0.7.4.201502262128</version> </dependency>
In the end, the report is successfully generated.

A: Similar to @sofia's solution but for gradle:
I removed the version after tool version. Instead of
allprojects {
    jacoco {
        toolVersion = '0.7.1.201405082137'
    }
}

I used the following
allprojects {
    jacoco {
        toolVersion = '0.7.1'
    }
}


text:
Q: Passing function with the innerHTML in ng-class I'm trying to create an ng-class clause in AngularJS that evaluates the length of the contents and assigns a class accordingly, the problem is that the text is retrieved using the angular-translate service, so when trying to pass the variable in the ng-class, it is still undefined.
Here's what I've tried so far

common.title

the JS
this.isTextTooLong = function(text) {
    if (typeof text === 'undefined' || !text) {
        return;
    }
    debugger;
    console.log(text);
    return true;
};

PS : this function is currently for testing purposes only, it is still a work in progress

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex that captures the text only if there is 3 lines I have this regex1 :
(\w+)\n#(\w+)_(\w+)\n(\w+)

That captures the following text1 :
randomtext
#randomteeexxt_randomqlsdfjml
randomagain

But sometimes I have a fourth line in the text2 :
randomtext
#randomteeexxt_randomqlsdfjml
randomagain
stillrandom

So this following regex2 works :
(\w+)\n#(\w+)_(\w+)\n(\w+)\n(\w+)

The regex2 does not match anything of the text1, this is what I want.
The regex1 matches the 3 first lines of the text2, but I don't want it.
I want that the regex1 does not match anything of the text2.

A: You could try placing anchors around your current pattern to ensure that it applies to the entire input:
^(\w+)\n#(\w+)_(\w+)\n(\w+)$

Here is an example of how to use this pattern in JavaScript:

var str_pass = 'AAA\n#BBB_CCC\nDDD';
var str_fail = 'AAA\n#BBB_CCC\nDDD\nEEE';
console.log(/^\w+\n#\w+_\w+\n\w+$/.test(str_pass));
console.log(/^\w+\n#\w+_\w+\n\w+$/.test(str_fail));


text:
Q: If I'm trying to run the same script in ten different directories in a row, will this way work and is there a more concise command sequence? Sorry if this is noobish, I had to pick up Ubuntu for a job and am not super well-versed in the intricacies of input and output yet. Basically, I've got a bunch of directories that each have a copy of the same script, and ordinarily I'd have to go into each directory, ./ each script separately, wait like two minutes and type "2" to select an option partway through the script, then back out and go to the next folder. One of the guys I'm working with said I could use the cat command and a pipe to type what I want to put into the script automatically rather than sitting and waiting for the prompt, but he didn't show me how. Since I have ten of them, I was thinking I should be doing basically the following:
for i in $(ls -d [each of the folders]);
    do
       cd $i;
       echo "2" > input.txt;
       cat input.txt | ./scriptname.sh;
       rm input.txt;
       cd ..;
    done

So my questions are 1. Will/should this even work and 2. Is there a less clunky way to accomplish this?

A: Some notes:

*

*Don't parse ls. Assuming you want to use all the directories in the current folder, so
for dir in */        # note the trailing slash

IMO "dir" is a better varname than "i".

*if not every directory is wanted, you can spell them out
for dir in dir1 dir2 dir4 ...; do ...

or use a glob pattern that will match the wanted dirs
for dir in dir[1-46-9] ...; do ...

or use an array to hold them, and iterate over the array
dirs=(dirA dirB dirE dirG)
for dir in "${dirs[@]}"; do ...      # those quotes are required.

*Quote your variables

*This pattern is fine: cd dir; do stuff ...; cd ...
You could also create a subshell so the effects of cd vanish when the subshell exits.

*It's conceivable that cd fails.

So, here's a slight alternate take
for dir in */; do
    ( cd "$dir" && echo 2 | ./scriptname.sh )
done


text:
Q: cmake flags for opengl using glew and glfw I have this simple code:
#include <stdio.h>
#include <stdlib.h>

#include <GL/glew.h>
#include <GL/glfw.h>

int main(int argc, char const* argv[] )
{
    if( !glfwInit() ){
        fprintf( stderr, "failed\n" );
    }

    return 0;
}

and in my CmakeLists.txt:
PROJECT(test C)
find_package(OpenGL)
ADD_DEFINITIONS(
    -std=c99
    -lGL
    -lGLU
    -lGLEW
    -lglfw
)
SET(SRC test)
ADD_EXECUTABLE(test ${SRC})

running "cmake ." doesn't produce any error, but running make will says:
test.c:(.text+0x10): undefined reference to `glfwInit'
collect2: ld returned 1 exit status
make[2]: *** [tut1] Error 1

while running:
gcc -o test test.c -std=c99 -lGL -lGLU -lGLEW -lglfw

successfully compiles the code without error. How do i make cmake run with my code?
also, if i add these lines to the main function:
glfwOpenWindowHint( GLFW_FSAA_SAMPLES, 4 );
glfwOpenWindowHint( GLFW_OPENGL_VERSION_MAJOR, 3 );
glfwOpenWindowHint( GLFW_OPENGL_VERSION_MINOR, 1 );
glfwOpenWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );

even running gcc with the same flags will produce error:
test.c: In function 'main':
test.c:14: error: 'GLFW_OPENGL_VERSION_MAJOR' undeclared (first use in this function)
test.c:14: error: (Each undeclared identifier is reported only once
test.c:14: error: for each function it appears in.)
test.c:15: error: 'GLFW_OPENGL_VERSION_MINOR' undeclared (first use in this function)
test.c:16: error: 'GLFW_OPENGL_PROFILE' undeclared (first use in this function)
test.c:16: error: 'GLFW_OPENGL_CORE_PROFILE' undeclared (first use in this function)

i'm running linux mint based on kubuntu 10.04, cmake v2.8, libglfw-dev, libglfw2, libglew1.5, libglew1.5-dev, glew-utils.
I'm new to cmake, glew and glfw. Thanks for your help guys!
cheers!
P

A: you can see here an example how I use cmake with glfw.
http://code.google.com/p/assembly3d/source/browse/tools/viewer/CMakeLists.txt
I use FindGLFW.cmake for finding glfw
http://code.google.com/p/assembly3d/source/browse/tools/viewer/cmake_modules/FindGLFW.cmake
Also, glfw version in ubuntu is 2.6.
GLFW_OPENGL_VERSION_MINOR and GLFW_OPENGL_VERSION_MAJOR just works in glfw 2.7 and I think OpenGL 3.x works only with glfw 2.7.
Best

A: To see the commands that the CMake generated makefile is executing, run make as:
make VERBOSE=1

Seeing the commands is very helpful when debugging CMake projects.  For the example provided, the following commands are executed:
/usr/bin/gcc -std=c99 -lGL -lGLU -lGLEW -lglfw -o CMakeFiles/test.dir/test.c.o -c test.c
/usr/bin/gcc CMakeFiles/test.dir/test.o -o test -rdynamic

The makefiles generated by CMake will compile each source file into an object file (this is what gcc -c does) individually, and then link all of the object files together with a separate command.  With the provided example, the OpenGL related libraries are being specified during the compilation stage, and not during the link stage.  Instead of specifying the libraries with add_definitions, the target_link_libraries command should be used.
A CMakeLists.txt file like this should work:
cmake_minimum_required(VERSION 2.8)
project(test C)
add_definitions(-std=c99)
set(SRC test.c)
add_executable(test ${SRC})
target_link_libraries(test GL GLU GLEW glfw)

The -l prefix does not need to be specified for the libraries because target_link_libraries will automatically add the -l prefix for UNIX/Linux environments and the .lib extension for Windows environments.  More information about target_link_libraries can be found at http://www.cmake.org/cmake/help/cmake-2-8-docs.html#command:target_link_libraries

A: Pixar has did it yet. The below is its source code, you can refer it:
https://github.com/PixarAnimationStudios/OpenSubdiv/blob/master/cmake/FindGLFW.cmake


text:
Q: Перевeсти HEX или RGB в feColorMatrix значения и суть каждого из них Изображение svg в формате base64
Необходимо черной фигуре svg,  задать цвет #26bf8c. Но как его записать в значениях feColorMatriх?
<svg width='20px' height='10px' preserveAspectRatio='none meet'>
  <image filter='url(#colorMatrixFilter1)' width='20px' height='10px' xlink:href='../img.svg'/>
  <defs>
    <filter id='colorMatrixFilter1'>
      <feColorMatrix type='matrix' values='1 0 0 0 0
                                           1 0 0 1 0
                                           1 0 0 0 0
                                           0 1 0 1 0'
      />
    </filter>
  </defs>
</svg>

Что значит каждое значение(элемент) этой матрицы?

A: Ниже на рисунке показано, за какими строчками и столбцами закреплены определенные каналы цветов и прозрачности цвета:

В крайнем, правом столбце, каждая строка,- это финальный результат выполненных матричных вычислений по определенным каналам.
 Первая строка отвечает за красный цвет (R). Если в этой строчке будет "1", а в двух последующих строках нули, то результирующий цвет всей матрицы будет красный, чистый цвет, HEX(#ff0000),rgba(255,0,0,1) или rgba в % (100,0,0,1)
Последняя строка,- это проценты прозрачности. "1" в этой строке соответствует 100% прозрачности.
Пример окраски в красный цвет:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewBox="0 0 200 130">
  <defs>
     <filter id="RedFilter" x="-20" y="-20" width="150" height="150">
        <feColorMatrix in="SourceGraphic" type="matrix"
                values="0 0 0 0 1
                        0 0 0 0 0
                        0 0 0 0 0
                        0 0 0 1 0
                "/>
    </filter>
      <image id="Building" width="150" height="150"  xlink:href="data:image/png;base64,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"/>
   </defs>
   <use xlink:href="#Building" x="0" filter="url(#RedFilter)" ></use>

</svg>

С одноканальным (R) красным цветом оказалось всё просто. Также просто будет получить зеленый цвет (G), для этого нужно поставить 1 во второй строчке последнего столбца матрицы.
Для подстановки значений в матрицу  необходимо будет перевести шестнадцатеричные значения цветов (HEX) #26bf8c в rgba в %

*

*С помощью инженерного калькулятора переводим: шестнадцатеричное
число26 это 38 в десятичной системе; bf - 191; 8c - 140
итого rgba(38,191,140)

*Переводим в проценты: (38/255)*100 = 15%

*Итого  будут значения rgba в % (15,75,55,100) или для
матрицы (0.15,0.75,0.55,1)

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewBox="0 0 200 130">
  <defs>
    <filter id="RedFilter" x="-20" y="-20" width="150" height="150">
        <feColorMatrix in="SourceGraphic" type="matrix"
                values="0 0 0 0 0.15
                        0 0 0 0 0.75
                        0 0 0 0 0.55
                        0 0 0 1 0
                "/>
    </filter>
       <image id="Building" width="150" height="150"  xlink:href="data:image/png;base64,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"/>
   </defs>
   <use xlink:href="#Building" x="0" filter="url(#RedFilter)" ></use>

</svg>

2# способ
перевода из HEX значений цвета в rgba в %
Этот способ намного проще, так как не надо ничего вычислять.

*

*Используется любая утилита, в которой есть возможность выбора и
конвертирования цвета из одной формы записи в другую.  Для этих целей
я использовал ColorMania

*

*Копируем значение HEX цвета

*Нажимаем установку цвета (Set)

*Выбираем кодировку RGB % Value

Забираем цифры в процентах и подставляем в виде - 1 соответствует 100% - 0.15,0.75,0.55,1 в последний, пятый столбец матрицы, как в первом способе выше.

A: Это коэффициенты смешения цветов.

*

*Каждая строка в матрице обозначает свой цветовой канал выходного изображения (красный, зелёный, синий и непрозрачность соответственно).

*Коэффициенты в строке означают степень влияния каждого из входных каналов на конкретный выходной. Однако коэффициентов пять, а каналов всего четыре. Это связано с тем, что вы, возможно, захотите не просто смешать цвета, но и сдвинуть результат вверх или вниз, сделав канал безусловно темнее или светлее. То есть последний коэффициент сдвигает чёрную точку цветового канала.
В вашем случае:

    1 0 0 0 0        rвых = (1 * rвх) + (0 * gвх) + (0 * bвх) + (0 * aвх) + 0
    1 0 0 1 0   =>   gвых = (1 * rвх) + (0 * gвх) + (0 * bвх) + (1 * aвх) + 0
    1 0 0 0 0        bвых = (1 * rвх) + (0 * gвх) + (0 * bвх) + (0 * aвх) + 0
    0 1 0 1 0        aвых = (0 * rвх) + (1 * gвх) + (0 * bвх) + (1 * aвх) + 0

это означает следующее:

*

*Красный канал остаётся как есть.

*Зелёный формируется путём усреднения красного и синего каналов. Причём итоговая яркость будет в два раза выше исходной (так как оба исходных канала складываются на своей полной яркости) — результат может быть ярче максимально допустимого, что приведёт к отсечению значения.

*Синий канал отбрасывается и замещается красным.

*Альфа-канал (задающий непрозрачность) также складывается из двух каналов, зелёного и исходной альфы. То есть мы сохраняем исходную альфу, но теперь на степень непрозрачности влияют и зелёные оттенки.

Как это можно сочетать и использовать — остаётся на ваше художественное и дизайнерское усмотрение.

A: Способ замещения RGB цвета CSS фильтрами.
В ручную подбирать комбинацию фильтров CSS и их параметров довольно утомительное занятие.

img {
filter: invert(61%) sepia(10%) saturate(2853%) hue-rotate(109deg) brightness(101%) contrast(85%);
}
<img src="https://cdn.jsdelivr.net/gh/oakmac/chessboardjs/website/img/chesspieces/wikipedia/wK.png"/>

Но есть замечательный генератор, который можно скачать с Codepen или выполнить подборку фильтров онлайн.
Всё просто — копируем нужный цвет и получаем подборку CSS фильтров, реализующих нужный цвет.


text:
Q: Java Returns Nothing Recursion So I found this code in a Java textbook and it is a piece of recursion code. I don't really understand what happens when nothing is returned ("return;") and it doesn't explain in the textbook either. I tried searching it on the internet, but couldn't find any answers either.
public static void numbers(int n) {
    if (n == 0) {
        throw new IllegalArgumentException();
    }
    if (n == 1) {
        System.out.print(n);
        return;
    }
    numbers(n - 1);
    System.out.print(", " + n);
}

A: When n is 1 it prints n (1) and then stops recursing (the return; unwinds the stack-frame and returns to the caller). In this case, that was when n was 2. Then the method body ends (equivalent to a return;) so it happens again (3)...

A: Although the code doesn't return anything, it does take action that changes things, in this case printing something to the output.
If n is 1, it just prints 1.
If n is 2, it calls numbers(1).  As noted above, that prints 1.  Then it returns back to the caller, which is numbers with n==2.  The caller starts with the statement after numbers(n-1), and therefore prints , 2.  Thus, the output is 1, 2.
If n is 3, it calls numbers(2).  As described in the previous paragraph, this outputs 1, 2 using another recursive call.  Then it returns to the caller, which is numbers with n==3.  The caller starts with the statement after numbers(n-1), and therefore prints , 3.  Thus, the output is 1, 2, 3.
So basically, the output of numbers(n) (for n > 1) is just the output of numbers(n-1), with a comma and n after it.

A: The purpose of that (example) method is to print a number.  It is not designed to return anything.

I don't really understand what happens when nothing is returned ("return;") and it doesn't explain in the textbook either.

Well ... what "happens" is that nothing is returned.
But that is OK, because the recursion method is declared as a void method.  And indeed, if you did attempt to either return a value, or assign the result of the call, you would get compilation errors.  (Try it and see!)
Note that is applies to all methods / method calls in Java, not just recursive ones.

(It most likely does explain this in your text book, but in an earlier section than the one you are looking at right now.  Text books are generally written on the assumption that you will read the text from the beginning ...)

A: "return;" in a void function has the same meaning as "return val;" in a non-void function.
So, "return;" in the example means "To here the function ended, and return to the invoke place where the function invoked."
You can also think that: in the end of every void function, there is a "return;", but they are always left out for conciseness.

A: The purpose of this method is to print a sequence of numbers from 1 to n separated by commas and not to return anything to its caller.
So here is how it works (try to simulate in your head - I numbered the lines to facilitate my references.):

 1: public static void numbers(int n) {
 2:    if (n == 0) {
 3:        throw new IllegalArgumentException();
 4:    }
 5:    if (n == 1) {
 6:        System.out.print(n);
 7:        return;
 8:    }
 9:    numbers(n - 1);
10:    System.out.print(", " + n);
11: }

If you call it with 1 as parameter (n = 1), the expression in line 5 is true, line 6 prints "1" to the output and the method returns in line 7, to its caller.
If you call it with 2 as parameter, the expression in line 5 fails, the if block is skipped, line 9 calls number method with n - 1 (=1) as parameter, causing "1" to be shown (as seen in the previous case). The CPU then returns to it's caller and resumes executing line 10, which prints ", 2" to the output. The final output is "1, 2".
If you call it with 3 as parameter, line 9 calls numbers method with 2 as parameter, resulting in the output "1, 2" (as seen in the previous case), then prints ", 3" (in line 10), resulting in "1, 2, 3" as output.
And so on...


text:
Q: About semipositive definite matrix Suppose $A$ and $B$ are positive semidefinite matrices
$A \ge B\ge 0$
Is the statement $A^2\geq B^2$ true or false? Why?
$\geq$ means nonnegative pointwise

A: Let $$ A = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}, \quad B = \begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix} $$
Then
$$ A^2 = \begin{pmatrix} 5 & 3\\ 3 & 2\end{pmatrix}, \quad B^2 = \begin{pmatrix} 2 & 2 \\ 2 & 2\end{pmatrix} $$
We have
$$ A - B = \begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}, \quad
 A^2- B^2 = \begin{pmatrix}  3 & 1 \\ 1 & 0\end{pmatrix} $$
We have $A-B \ge 0$, but $\det(A^2 - B^2) = -1 < 0$, that is $A^2-B^2 \not\ge 0$.

A: If $(A)_{ij}\geq (B)_{ij}\geq 0$ (for $i,j=1,\ldots,n$), then
$$
(A^2)_{ij}=\sum_{k=1}^n(A)_{ik}(A)_{kj}\geq \sum_{k=1}^n(B)_{ik}(B)_{kj}=(B^2)_{ij}.
$$

A: I suppose $A\ge B$ means $A-B$ is positive semidefinite. Then I'm pretty sure that $A^2\ge B^2$ is a wrong statement, whose counterexample can be easily found in the case $2\times 2$ matrix (see the other answer).
There is nevertheless an interesting true statement, which is $A^{-1}\leq B^{-1}$ (if they both exist)
Hope I'm not wrong :)


text:
Q: ImportMapServerCache_server not executed I have this script based on an export from Model Builder (ArcMap 10.4) that is supposed to take  .tif files from a directory and import them to an existing service.
The problem is that ImportMapServerCache_server is not executed after some editing of the code I reached the following:
import arcpy
import os

input:
# Local variables:
connectionFile = "C:\\Users\\carmel.han\\AppData\\Roaming\\ESRI\\Desktop10.4\\ArcCatalog"
server = "arcgis on geoerpdev_6080 (publisher)"
serviceName = "MondayFull3.MapServer"
Input_Service =  connectionFile + "\\" + server + "\\" + serviceName
print (Input_Service)

#Input_Service = "http://geoerpdev:6080/arcgis/rest/services/tests/MondayFull2/MapServer"
OutPut_Cache_Location_Path = "C:\\Users\\carmel.han\\Desktop\\Caching\\Output"
Manage_Mode = "RECREATE_ALL_TILES"
# Input_Data_Source = "Ov_i04_L02_R000005F1_C000004567892"
Input_Tiling_Scheme = "IMPORT_SCHEME"
Import_Tiling_Scheme = "C:\\Users\\carmel.han\\Desktop\\tests_monday\\Final.xml"
Scales__Pixel_Size___Estimated_Disk_Space_ = "64000;32000;16000"
#Area_of_Interest = "in_memory\\{3B818E7A-1914-4D00-9C2C-E97C6744D7BC}"
Area_of_Interest = "#"
Maximum_Source_Cell_Size = ""
Minimum_Cached_Scale = "64000"
Maximum_Cached_Scale = "16000"
#Cache_Name = "C:\\Users\\carmel.han\\Desktop\\Wensday\\wensday2"
Source_Tile_Package = ""
Upload_data_to_server = "UPLOAD_DATA"
Scales = "64000;32000;16000"
Number_of_caching_service_instances = "3"
#Area_Of_Interest__Polygon_ = "in_memory\\{8BBC3764-B579-4CCF-847B-E1D1E428CE1C}"
#Area_Of_Interest__Polygon_ = "#"
Area_Of_Interest__Polygon_ = ""
Overwrite_Tiles = "MERGE"
Output_Map_Service_URL = "http://geoerpdev:6080/arcgis/rest/services/System/CachingControllers/GPServer/ImportCache/jobs/j98c38213db434a8da6aec04aacb259c3"
Source_Cache_Dataset = "C:\\Users\\carmel.han\\Desktop\\Wensday\\Wensday1"
directory = "C:\\Users\\carmel.han\\Desktop\\Caching\\Input"

code:
for Input_Data_Source in os.listdir(directory):
        if Input_Data_Source.endswith(".tif") or Input_Data_Source.endswith(".ecw"):
                Input_Data_Raster = directory + "\\" + Input_Data_Source
                print ("Input: " + Input_Data_Raster)
                try:
                    os.stat(OutPut_Cache_Location_Path)
                except:
                    os.mkdir(OutPut_Cache_Location_Path)
                print ("Output: "+ OutPut_Cache_Location_Path)

                arcpy.ManageTileCache_management(OutPut_Cache_Location_Path, Manage_Mode, os.path.splitext(Input_Data_Source)[0], Input_Data_Raster, Input_Tiling_Scheme, Import_Tiling_Scheme, Scales__Pixel_Size___Estimated_Disk_Space_, Area_of_Interest, Maximum_Source_Cell_Size, Minimum_Cached_Scale, Maximum_Cached_Scale)
                Cache_Name = OutPut_Cache_Location_Path + "\\" +  os.path.splitext(Input_Data_Source)[0]
                print (Cache_Name)
                try:
                        arcpy.ImportMapServerCache_server(Input_Service, "CACHE_DATASET", Cache_Name, Source_Tile_Package, "UPLOAD_DATA", Scales, Number_of_caching_service_instances, Area_Of_Interest__Polygon_, "", Overwrite_Tiles)
                except ValueError:
                        print ("Bad!!")

output:
Executing: ManageTileCache C:\Users\carmel.han\Desktop\Caching\Output RECREATE_ALL_TILES Ov_i04_L02_R000005F1_C0000045678921 C:\Users\carmel.han\Desktop\Caching\Input\Ov_i04_L02_R000005F1_C0000045678921.tif IMPORT_SCHEME C:\Users\carmel.han\Desktop\tests_monday\Final.xml 64000;32000;16000 "Feature Set" # 64000 16000
Start Time: Mon May 28 08:48:52 2018
Generating tile cache using 4 parallel instances.
Succeeded at Mon May 28 08:49:02 2018 (Elapsed Time: 9.58 seconds)
Executing: ImportMapServerCache "C:\Users\carmel.han\AppData\Roaming\ESRI\Desktop10.4\ArcCatalog\arcgis on geoerpdev_6080 (publisher)\MondayFull3.MapServer" CACHE_DATASET C:\Users\carmel.han\Desktop\Caching\Output\Ov_i04_L02_R000005F1_C0000045678921 # DO_NOT_UPLOAD 64000;32000;16000 3 "Feature Set" "646401.583133334 8292340.10282222 662788.783133334 8308724.10282222" MERGE
Start Time: Mon May 28 08:49:04 2018
Reporting status from http://geoerpdev:6080/arcgis/rest/services/System/CachingControllers/GPServer/ImportCache/jobs/j2b56a4d7497b4eb8a3e914735072d50a
ERROR 001225: Server cannot access target_cache_path.
Failed to execute (ImportCache).
Failed.
The workspace is not connected.
Failed to execute (ImportMapServerCache).
Failed at Mon May 28 08:49:19 2018 (Elapsed Time: 14.41 seconds)

I noticed in the output under Executingit says DO_NOT_UPLOAD even though i entered UPLOAD_DATA so i replaced it with DO_NOT_UPLOAD thinking there might be some problem with the boolian variable, but it did not help.
What may cause such a problem?

A: You can only do upload to server with tile package file. You need to export tile cache to tpk file. ExportTileCache_management


text:
Q: Switch WPF Form Content I wanna make some game on WPF form,
And the problems I don't know how to switch between main menu form to the main game,
When I run my program, the main menu will show up, and when I click the play button
the content will be changed into the main program
but, I don't wanna make the user figure that the program change form,
so, just the form content will be changed, and the title bar stand still.
Sorry for my bad grammar

A: From Xaml, you can pub both of Menu UI and Main UI in the same Grid and hide Main UI. When user clicks "Play" button on Menu, you hide Menu UI and make Main UI visible. You can add some transform or animation to make the effect smoothly.
From Code, you can use MVVM and define both Menu UI and Main UI as DataTemplate. Then you use one ContentControl with its Content bound to your Menu ViewModel. When user clicks "Play" button, you change Menu ViewModel to Main ViewModel then UI will switch automatically.


text:
Q: How to compute the time at which a predetermined number of events is reached for a given survival function using lifelines in Python? Often clinical trial analyses are triggered based on reaching a predetermined number of events on an event-driven (time-to-event endpoint) study. This of course depends on the underlying survival function, the number of arms in the study, etc.
I reviewed the lifelines documentation but did not find a simple way of computing the time at which a specific number of events is reached. How would I go about using current functionality in lifelines, or is there another library to consult here? Thank you!

A: I don't know that there is a "simple" way to do this, in lifelines or any other survival software, if you want a detailed analysis. (Software-specific questions are off-topic here in any event.) But the approach is straightforward.
You presumably have a model that predicts survival as a function of time $t$, covariate values $X$, and treatment $A$, say $S(t|X,A)$. After a model is built, this model-specific prediction is provided in the software by a function with a name like predict(). To get a full analysis, construct a set of multiple hypothetical study participants $i$ with covariate values representing the covariate distributions among members of the population of interest. Predict the cumulative hazard (probability of an event up to time $t$) for each of those hypothetical participants, $F_i(t|X_i,A_i)= 1 - S(t|X_i,A_i)$, and average appropriately to represent the study population.
Multiplying that probability by the size of the study population gives you the number of events as a function of time.
In practice, particularly at early stages of evaluating study feasibility, a simple exponential survival curve might be assumed, with the rate parameter $\lambda$ determined by the known historical survival probability for the untreated population of interest at a particular point in time. That is, you assume a constant hazard, so the cumulative hazard over time has the simple form $F(t)=1-\exp(-\lambda t)$. Multiplying that probability by the initial untreated cohort size gives you the number of events in that cohort over time. Then take the treatment-associated change in $\lambda$ that you'd like to detect (hazard ratio) and repeat the calculation for the treated group. Together with appropriate handling of study entry and censoring over time, that's the basis of simple power estimates for survival studies, in which power is determined by the difference in the number of events between untreated and treated participants.


text:
Q: Ionic 3 get index of clicked item I need to get the index of the clicked item in an ion list, so I can access the position in an array.
The html code I used is this:
<ion-list>
 <ion-item *ngFor="let poi of poiList" (click)="openPage(poi, $index)">
 <h2> {{ poi.name }} </h2>
</ion-item>
</ion-list>

Inside the function openPage I've printed the index in the console, but it is showed as "undefined". I couldn't find any other way to get the index correctly.

A: $index will only work for AngularJS, in Angular2 and above the way to get the clicked item index is the following :
<ion-list>
 <ion-item *ngFor="let poi of poiList; let i= index" (click)="openPage(poi, i)">
 <h2> {{ poi.name }} </h2>
</ion-item>
</ion-list>


text:
Q: Where to get "/etc/ld.so.nohwcap" file from? When I run a command through strace utility I can see access errors such as
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
Now I've read somewhere that what's happening on the above line is that a linker is looking for optimized version of the command that I'm running but can't find it.
How do I solve this problem ? What package do I need to install so that I can have that ld.so.nohwcap file on the system ? Even if not for optimization purposes but just to get rid of these errors in strace ?

A: You probably don't want to "solve" this problem; according to the Debian glibc manpage for ld.so,

/etc/ld.so.nohwcap When this file is present the dynamic  linker  will  load  the  non-optimized  version  of  a library, even if the CPU supports the optimized version.

It's not installed by a package, it can be created by the system administrator to disable loading optimised libraries.
Note that this is Debian-specific: the feature is implemented by a patch in the Debian glibc package, and isn't available in upstream glibc. The feature's documentation disappeared from the ld.so manpage when the latter was moved from glibc to the man-pages project.


text:
Q: Why spyOn "stops all execution of a function" in Jasmine (asking for clarification on Jasmine 2.2 Documentation on Spies) In the Jasmine 2.2 documentation I cannot understand the last spec that demonstrates the basic use of Spies.
In the beforeEach() section we set bar = null, then we spy on foo.setBar and then we call foo.setBar twice. I can't understand why bar === null in the last spec. Shouldn't it be bar === 456 before the spy is torn down for the spec?
Here is the example:
describe("About a Spy", function(){
  var foo, bar = null;

  beforeEach(function() {
    foo = {
      setBar: function(value) {
        bar = value;
      }
    };

    spyOn(foo, "setBar"); // we spy

    foo.setBar(123); // shouldn't bar === 123 here?
    foo.setBar(456, 'another param'); // and bar === 456 here?
  });

  it("stops all execution on a function", function() {
    // What, why, how?
    expect(bar).toBeNull();

    //I expected this to be the case, but it's not.
    //expect(bar).toBe(456);
  });
});

I must be misunderstanding how the beforeEach builds up and tears down the variable scope or perhaps there is a step where the variables within the describe section get reset? Or were they never actually touched, because we used the spy function only and not the real function?
It would be very helpful if you could explain what exactly is going on with the variable bar in this spec suit so I could understand why its value remains null in the last spec.
Thanks!

A:
If you look closely, you might realize that spyOn is replacing the original function with a spy that intercepts the function calls and tracks a lot of potentially useful information about them. The problem we run into above is that once we've replaced the original function, we've lost its capabilities. We can remedy that with andCallThrough. If you chain andCallThrough() after calling spyOn, the spy will then pass any calls to it through to the original function

http://www.joezimjs.com/javascript/javascript-unit-testing-with-jasmine-part-2/


text:
Q: Group by first occurrence of each value in a pandas dataframe I have a pandas dataframe that looks like this:

id
user
action
timestamp

1
Jim
start
12/10/2022

2
Jim
start
12/10/2022

3
Jim
end
2/2/2022

4
Linette
start
8/18/2022

5
Linette
start
3/24/2022

6
Linette
end
8/27/2022

7
Rachel
start
2/7/2022

8
Rachel
end
1/4/2023

9
James
start
6/12/2022

10
James
end
5/14/2022

11
James
start
11/28/2022

12
James
start
8/9/2022

13
James
end
2/15/2022

For each user, there can be more than one start event, but only one end. Imagine that they sometimes need to start a book over again, but only finish it once.
What I want is to calculate the time difference between the first start and the end, so keep, for each user, the first occurrence of "start" and "end" in each group.
Any hint?

A: >>> (df.groupby(["user", "action"], sort=False)["timestamp"]
       .first()
       .droplevel("action")
       .diff().iloc[1::2])

user
James       29 days
Jim        311 days
Linette     -9 days
Rachel    -331 days
Name: timestamp, dtype: timedelta64[ns]

*

*for "timestamp" of each "user" & "action" pair, get the first occurences

*

*this will effectively take the first start, and the (only) end

*then drop the carried over "action" level of groupers

*take the difference from ends and starts

*take every other value to get per-user difference

(sort=False ensures during groupby that start's don't get mixed up.)


text:
Q: Yii GridView returns a blank screen? Yii GridView returns a blank screen, when a dataProvider return a many models;
IMAGES BROWSER

A: This is Apache Fatal error: Allowed memory size of... , i decided with the help of
ini_set('memory_limit', '-1');


text:
Q: Contractions which are conformal Can someone give an example for a contraction which is also a conformal?
I know that we call a contraction as conformal when it preserves angles.
Even a hint would be helpful.

A: Unless I am misunderstanding your request, $z\mapsto\frac12z$ is both a contraction and a conformal map from $\mathbb C$ into $\mathbb C$.


text:
Q: ¿Cómo puedo quitar la URI de la URL en PHP? ¿Como puedo remover la URI que obtengo con $_SERVER["REQUEST_URI"]?
En mi página, al cargar, muestra en la URL prueba.com, hasta ahí todo bien, ahora lo que necesito es que al cargar el módulo que necesito entonces me muestra lo siguiente: prueba.com/modulo
La cuestión es que con PHP tengo que remover la URI para obtener prueba.com y al hacer un echo a $_SERVER["REQUEST_URI"] me debe mostrar  // y no el nombre del HOST ésto como si el módulo(prueba.com/modulo) sea tratado como prueba.com
Espero me puedan ayudar.
NOTA: Si necesito obtener la URI, pero en el proceso que estoy haciendo necesito removerla en ciertos segmentos

A: Con $_SERVER['SERVER_NAME'] obtienes el nombre del host del servidor, ej.: www.domain.com

Nota: Bajo Apache 2, se debe establecer UseCanonicalName = On y ServerName. De lo contrario, este valor refleja el nombre del host proporcionado por el cliente, el cual se puede burlar. No es seguro depender de este valor en contextos que necesiten seguridad.

+ info


text:
Q: About Sum of Squared differences I found a paragraph in the book about $SSD$, can't get one thing:

Most commonly, the distance measure is the sum of squared differences.
  For two images $f(x, y)$ and $g (x, y)$ it is defined as  $$
SSD(d_1,d_2) = \sum_{i=-n_1}^{n_1} \sum_{j=-n_2}^{n_2}
\big(f(x+i,\,y+j)-g(x+i-d_1,\,y+j-d_2)\big)^2
$$
where the summation extends over the region of size $(2n_1 + 1) \times (2n_2 + 1)$.

I can not get, why does $i$ changes from $-n_1$ to $n_1$, but not from $0$ to $n_1$.  The similar about $j$.
And why does summation goes over the $(2n_1 + 1) \times (2n_2 + 1)$ but not over the  $(n_1) \times (n_2)$

A: Certainly one could iterate a sum from $i = 0$ to $n_1$ and from $j=0$ to $n_2.$ The question is, what is the purpose of the sum?
The indexing scheme in the formula is apparently intended to extract two rectangular regions out of two much larger images.
The rectangular regions are parallel to the coordinate axes,
but each rectangle has a width, a height, and a position that need to be specified.
For reasons that may be explained in the parts of the book that have been omitted from the question, the author wanted to specify the position of each rectangle by the coordinates of a pixel in the exact center of the rectangle.
Perhaps this is due to considerations of symmetry, or perhaps it is because we are really supposed to be interested in what is happening at a specific pixel in each image, and the other pixels are considered only as "neighbors" of the interesting pixel.
Whatever the motivation is, we get a rectangle by selecting a certain pixel to be in the center of the rectangle, and then extending the rectangle $n_1$ pixels to the left and to the right and $n_2$ pixels upward and downward.
The coordinates of the center of the rectangle inside the $f$ image are
$(x,y),$ so the rectangle runs left and right from $x - n_1$ to $x + n_1$
and vertically from $y - n_2$ to $y + n_2.$
The coordinates of the center of the rectangle in side the $g$ image are
not necessarily the same as those of the $f$ rectangle.
Instead of $(x,y),$ they are $(x-d_1,y-d_2),$
so the rectangle runs left and right from $(x - d_1) - n_1$ to
$(x - d_1) + n_1$ and vertically from $(y - d_2) - n_2$ to $(y - d_2) + n_2.$
If you take all the integers from $x - n_1$ to $x + n_1,$
there are $2n_1 + 1$ of them,
so the $f$ rectangle is $2n_1 + 1$ pixels wide.
For similar reasons, it is $2n_1 + 1$ pixels high,
and the $g$ rectangle is the same size.

A: The region, $n_1×n_2$, starts from $1$. That is, $n_1,n_2$ start from $0$.
The region according to the formula is always odd, with windows of size: $1x1, 3x3, 5x5,.. $ or even $1x3, 1x5, .., 3x1$ and so on.
For example, if you are comparing two pixels (i.e. one pixel in each image), you have a region of $1$ pixel. Let's say it is the fifth pixel in the first row:  x = $0$, y = $4$. The pixel values are $10,3$ for $f,g$ respectively. For the region of one$ 2n_1= 1 =>n_1 = 0$, and the same goes for $n_2$.
$SSD= (f(x+i,y+j) - g(x+i,y+j))^2$
$SSD= (f(0+0,4+0) - g(0+0,4+0))^2$
$SSD= (f(0,4) - g(0,4))^2$
$SSD= (10 - 3)^2 = 49$
Basically, you are comparing the value of the same pixel location  with no offset around it.
If the window size is bigger, you are squaring the summation of the differences between the according pixels in that window.


text:
Q: How to find out if lvm mirror write is asynchronous or synchronous? I am using redhat 5.8 with an lvm mirror, created with the following command:
 lvcreate -m1 --mirrorlog mirrored -n mirrorvol -L 10G myvg /dev/vdb /dev/vdc

I would like to know, when I write, do I need to wait the write is given to both devices, or just one?
From what i understood lvm mirror is synchronous:
[root@02srv004x9 ~]# dmsetup ls
mpath2  (253, 2)
foo (253, 3)
vgmirror-oracle_BD2_mirrorlogAvol   (253, 4)
VolGroup00-LogVol01 (253, 1)
VolGroup00-LogVol00 (253, 0)
vgmirror-oracle_BD2_mirrorlogAvol_mimage_1  (253, 6)
vgmirror-oracle_BD2_mirrorlogAvol_mimage_0  (253, 5)
dmsetup suspend /dev/mapper/vgmirror-oracle_BD2_mirrorlogAvol_mimage_1
Name:              vgmirror-oracle_BD2_mirrorlogAvol_mimage_1
State:             SUSPENDED
Read Ahead:        256
Tables present:    LIVE
Open count:        1
Event number:      0
Major, minor:      253, 6
Number of targets: 1
UUID: LVM-c8xfdstj4tTpfV3LSIYat0wbKXpfb7kDefFId05lIJR2QV1ws7CBfkbC0Oc813d9

Now I have a secondary image in suspend state, and I will try to mount the filesystem:
 mount /dev/mapper/vgmirror-oracle_BD2_mirrorlogAvol /mnt

Here the mount command locks, and remains in state D.

A: If you write, write will happen into the block cache in your ram. From there it will be synced out, when it is optimal.
If you do a sync command or an fsync() system call, it will write out the whole write cache. Next to that, the ext2-3-4 filesystems try to write the write cache nearly as often as it is possible, other filesystems have better heuristics.
Journaling filesystem also execute partial syncs regularly.
If a write happens to the mirrorvol, it will passed over two write operations to the logical sub-volumes on vdb and vdc. There is no guarantee they will be actually executed in the same time, except if somebody says them so (which can be periodic write cache sync, journaling or the ext2-3-4 filesystems wonderful sync feature).

Suspension is not for emulating errors in a LVM physical volume. Suspension is to do non-atomic changes which seems atomic for the actual users. During suspension, every command using the given logical volume, will be in D status, but it don't have to do anything with the write caching, it is an LVM feature.
If you want to emulate a hardware error in a mirrored LVM volume, you have to find alternative solutions. The first which I think working if you power off the physical hard disk with SMART.


text:
Q: PHP trigonometry TAN I try to figure out an angle of a triangle.
If one side of the triangle is 100 and the other side is 100.
How do I get that to be 45 degrees.
If I run tan-1(100/100) on my calculator i get 45. How do I do this in PHP?

A: Use the atan function.
tan-1(100/100) on the calculator is the equivalent to atan(100/100) in Php.
Edit: Sorry, here's the same output as the calculator:
$input = 100 / 100;
print atan($input) * (180 / pi());
//Ouputs 45

A: Since you have both rise and run what you really want to use is atan2(), which will handle the difference between e.g. 1/4*pi and -3/4*pi properly.

A: Here you go:
$base = 100;
$perpendicular = 100;
echo rad2deg(atan($perpendicular/$base)); // 45

A: $degrees = atan($tan);

Source

A: You should be able to use atan2 from the math functions. This returns a value in radians though (by multiplying by 180 degrees over pi), so you also have to convert that to degrees. So something like this should work (also using the pi() function from the math library):
$degrees = atan2( 100, 100 ) * ( 180 / pi() );


text:
Q: Windows Forms C# create control Category List I created own control using Windows Forms under C# project. I use Settings to change control properties like:
[Category("Settings")]
public Color BorderColor { get; set; }

and in my form I just change BorderColor by picking another from list.
But now I want to make NewList (of strings) in Form and then bind my ListString attribute to my NewList.
In my control it looks like:
[Category("Settings")]
public List<string> ListString { get; set; }

In my form it looks like
public List<string> NewList = new List<string>() { "1", "2" };


text:
Q: How to display "parent" companies with count of facilities for given location? I have following database structure (simplified):
id | company_name | parent | count_of_facilities | longitude | latitude
1  | Apple        |  0     | 3                   |  ...      | ...
2  | Apple        |  1     | 3                   |  ...      | ...
3  | Apple        |  1     | 3                   |  ...      | ...
4  | Bmw          |  0     | 2                   |  ...      | ...
5  | Bmw          |  4     | 2                   |  ...      | ...
6  | HP           |  0     | 5                   |  ...      | ...
7  | HP           |  6     | 5                   |  ...      | ...
8  | HP           |  6     | 5                   |  ...      | ...
9  | HP           |  6     | 5                   |  ...      | ...
10 | HP           |  6     | 5                   |  ...      | ...

What am I trying to do - I am trying to get all companies in a certain location; so far, I am doing it this way:
@companies = Company.select('COUNT(id) AS grouped_facilities,
                             GROUP_CONCAT(id) AS grouped_facilities_ids')
                          .includes(:services)
                          .within(distance, origin: [lat,lng])
                          .where('companies.corporate_hq   = "0""')
                          .group('companies.company_name')
                          .order("companies.count_of_facilities DESC")

This solution so far works, but grouping companies based on their name isn't perfect - so I added the column parent. The root/parent company has set 0 here and all other "children" ID of the parent company.
If I do a search for a specific location, I want to find how many facilities are in this location and display the parent company + count of the facilities for the given location.
I tried to group the companies by companies.parent, but this would probably doesn't work, because there's so many companies with companies.parent = 0, right?
How could I get the desired output instead of using group('companies.company_name)?
EDIT:
The desired output for a given location:
Apple - 1 facility in this area
BWM - 2 facilities in this area
HP - 2 facilities in this area

A: You want to think about how you can do things more in the Rails way and avoid raw SQL as much as possible.  Writing raw SQL queries should be avoided!  For example, to find all "parent" companies:
@companies = Company.where(:parent => 1).within(distance, origin: [lat,long]).where(:corporate_hq => 0)

Much cleaner and it allows the query optimizer to do its job and ActiveRecord to abstract things away for you.
This isn't to say that you never need to augment this with actual SQL, but avoid it as much as you can.  It keeps you more portable and allows you to swap out the database backend at some point with minimal fuss.  You've done this to some degree.. Just continue thinking of things set-wise (SQL-ish) and continue adding compound statements.


text:
Q: How can I select first letter of text wrote as a tag and change it css? I want to change the color first letter only (B O L D) of the code when I hover .tab

BASE

OTHER

LABEL

DIRECT

and I use this jQuery
var words = $('.tab > li > a').text().split('1');
  $('.tab').hover(function(){
   words.css("color","#3f9cd6");
});

but the color is not changed. How can I fix this jQuery?

A: You can also have a CSS only method using ::first-letter CSS pseudo-element
Example

.tab li:hover::first-letter {
  color: red;
  font-weight: bold;
}

BASE

OTHER

LABEL

DIRECT


text:
Q: No network access from within Docker container I can't access the Internet or even the local network (a network printer) from within a container.
For example, pinging google.com's IP:
docker run --rm busybox ping -c 2 142.250.186.142

outputs:
PING 142.250.186.142 (142.250.186.142): 56 data bytes

--- 142.250.186.142 ping statistics ---
2 packets transmitted, 0 packets received, 100% packet loss

With --network=host, it works:
docker run --rm --network=host busybox ping -c 2 142.250.186.142

Host is Ubuntu 22.10.
And it used to work until last week. My colleagues using Windows as an host can ping fine.
I tried:

*

*restart docker

*reboot the host

*uninstall and reinstall Docker from the repository.

More details:
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 22.10
Release:        22.10
Codename:       kinetic

$ docker info
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Docker Buildx (Docker Inc., v0.9.1-docker)
  compose: Docker Compose (Docker Inc., v2.12.2)
  scan: Docker Scan (Docker Inc., v0.21.0)

Server:
 Containers: 1
  Running: 0
  Paused: 0
  Stopped: 1
 Images: 1
 Server Version: 20.10.21
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: systemd
 Cgroup Version: 2
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: a05d175400b1145e5e6a735a6710579d181e7fb0
 runc version: v1.1.4-0-g5fd4c4d
 init version: de40ad0
 Security Options:
  apparmor
  seccomp
   Profile: default
  cgroupns
 Kernel Version: 5.19.0-26-generic
 Operating System: Ubuntu 22.10
 OSType: linux
 Architecture: x86_64
 CPUs: 8
 Total Memory: 15.4GiB
 Name: boris-ThinkPad-T480
 ID: ZN24:57QW:KT4M:J5H6:BIHZ:BF6I:KDV2:EAM6:CESL:UWNE:43AL:LUAJ
 Docker Root Dir: /var/lib/docker
 Debug Mode: true
  File Descriptors: 24
  Goroutines: 34
  System Time: 2022-12-12T20:08:42.528459605+01:00
  EventsListeners: 0
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

$ docker version
Client: Docker Engine - Community
 Version:           20.10.21
 API version:       1.41
 Go version:        go1.18.7
 Git commit:        baeda1f
 Built:             Tue Oct 25 18:01:58 2022
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.21
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.18.7
  Git commit:       3056208
  Built:            Tue Oct 25 17:59:49 2022
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.6.12
  GitCommit:        a05d175400b1145e5e6a735a6710579d181e7fb0
 runc:
  Version:          1.1.4
  GitCommit:        v1.1.4-0-g5fd4c4d
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

$ cat /proc/sys/net/ipv4/ip_forward
1

$ iptables -Z && iptables -nvL > before.txt && docker run --rm busybox ping -c 3 142.250.186.142 > ping.txt  &&  iptables -nvL > after.txt && cat before.txt && cat ping.txt && diff before.txt after.txt
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 LIBVIRT_INP  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DOCKER-USER  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 DOCKER-ISOLATION-STAGE-1  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
    0     0 DOCKER     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  docker0 docker0  0.0.0.0/0            0.0.0.0/0
    0     0 LIBVIRT_FWX  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 LIBVIRT_FWI  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 LIBVIRT_FWO  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 LIBVIRT_OUT  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain DOCKER (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain DOCKER-ISOLATION-STAGE-1 (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DOCKER-ISOLATION-STAGE-2  all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0
    0     0 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain DOCKER-ISOLATION-STAGE-2 (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DROP       all  --  *      docker0  0.0.0.0/0            0.0.0.0/0
    0     0 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain DOCKER-USER (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain LIBVIRT_FWI (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  *      virbr0  0.0.0.0/0            192.168.122.0/24     ctstate RELATED,ESTABLISHED
    0     0 REJECT     all  --  *      virbr0  0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable

Chain LIBVIRT_FWO (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  virbr0 *       192.168.122.0/24     0.0.0.0/0
    0     0 REJECT     all  --  virbr0 *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable

Chain LIBVIRT_FWX (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  virbr0 virbr0  0.0.0.0/0            0.0.0.0/0

Chain LIBVIRT_INP (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     udp  --  virbr0 *       0.0.0.0/0            0.0.0.0/0            udp dpt:53
    0     0 ACCEPT     tcp  --  virbr0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:53
    0     0 ACCEPT     udp  --  virbr0 *       0.0.0.0/0            0.0.0.0/0            udp dpt:67
    0     0 ACCEPT     tcp  --  virbr0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:67

Chain LIBVIRT_OUT (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     udp  --  *      virbr0  0.0.0.0/0            0.0.0.0/0            udp dpt:53
    0     0 ACCEPT     tcp  --  *      virbr0  0.0.0.0/0            0.0.0.0/0            tcp dpt:53
    0     0 ACCEPT     udp  --  *      virbr0  0.0.0.0/0            0.0.0.0/0            udp dpt:68
    0     0 ACCEPT     tcp  --  *      virbr0  0.0.0.0/0            0.0.0.0/0            tcp dpt:68
PING 142.250.186.142 (142.250.186.142): 56 data bytes

--- 142.250.186.142 ping statistics ---
3 packets transmitted, 0 packets received, 100% packet loss
1c1
< Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
---
> Chain INPUT (policy ACCEPT 220 packets, 56220 bytes)
3c3
<     0     0 LIBVIRT_INP  all  --  *      *       0.0.0.0/0            0.0.0.0/0
---
>   220 56220 LIBVIRT_INP  all  --  *      *       0.0.0.0/0            0.0.0.0/0
5c5
< Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
---
> Chain FORWARD (policy ACCEPT 3 packets, 252 bytes)
7,8c7,8
<     0     0 DOCKER-USER  all  --  *      *       0.0.0.0/0            0.0.0.0/0
<     0     0 DOCKER-ISOLATION-STAGE-1  all  --  *      *       0.0.0.0/0            0.0.0.0/0
---
>     6   504 DOCKER-USER  all  --  *      *       0.0.0.0/0            0.0.0.0/0
>     6   504 DOCKER-ISOLATION-STAGE-1  all  --  *      *       0.0.0.0/0            0.0.0.0/0
11c11
<     0     0 ACCEPT     all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0
---
>     3   252 ACCEPT     all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0
13,15c13,15
<     0     0 LIBVIRT_FWX  all  --  *      *       0.0.0.0/0            0.0.0.0/0
<     0     0 LIBVIRT_FWI  all  --  *      *       0.0.0.0/0            0.0.0.0/0
<     0     0 LIBVIRT_FWO  all  --  *      *       0.0.0.0/0            0.0.0.0/0
---
>     3   252 LIBVIRT_FWX  all  --  *      *       0.0.0.0/0            0.0.0.0/0
>     3   252 LIBVIRT_FWI  all  --  *      *       0.0.0.0/0            0.0.0.0/0
>     3   252 LIBVIRT_FWO  all  --  *      *       0.0.0.0/0            0.0.0.0/0
17c17
< Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
---
> Chain OUTPUT (policy ACCEPT 267 packets, 34045 bytes)
19c19
<     0     0 LIBVIRT_OUT  all  --  *      *       0.0.0.0/0            0.0.0.0/0
---
>   267 34045 LIBVIRT_OUT  all  --  *      *       0.0.0.0/0            0.0.0.0/0
26,27c26,27
<     0     0 DOCKER-ISOLATION-STAGE-2  all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0
<     0     0 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
---
>     3   252 DOCKER-ISOLATION-STAGE-2  all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0
>     6   504 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
32c32
<     0     0 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
---
>     3   252 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
36c36
<     0     0 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0
---
>     6   504 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

$ sudo iptables -L -v -n -t  nat
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
  129 46233 DOCKER     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DOCKER     all  --  *      *       0.0.0.0/0           !127.0.0.0/8          ADDRTYPE match dst-type LOCAL

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    6   504 MASQUERADE  all  --  *      !docker0  172.17.0.0/16        0.0.0.0/0
18336 2849K LIBVIRT_PRT  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain DOCKER (2 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 RETURN     all  --  docker0 *       0.0.0.0/0            0.0.0.0/0

Chain LIBVIRT_PRT (1 references)
 pkts bytes target     prot opt in     out     source               destination
   29  2852 RETURN     all  --  *      *       192.168.122.0/24     224.0.0.0/24
    0     0 RETURN     all  --  *      *       192.168.122.0/24     255.255.255.255
    2   120 MASQUERADE  tcp  --  *      *       192.168.122.0/24    !192.168.122.0/24     masq ports: 1024-65535
    6  3810 MASQUERADE  udp  --  *      *       192.168.122.0/24    !192.168.122.0/24     masq ports: 1024-65535
    2    64 MASQUERADE  all  --  *      *       192.168.122.0/24    !192.168.122.0/24

A: If you can access the network using the host's network stack (--network=host) but cannot without it, it would mean that the container network stack is not configured properly (IP address, default gateway..)
There could also be issues with the firewall which can prevent the container from accessing the network.
You could check the network configurations of your container using:
docker inspect <your_container>

You can also check the listings of all your active networks with
docker network ls

Could provide insight if there is any network related issues preventing the container from accessing the internet

A: After some debug commands it turned out the container does send out the icmp request packet, and the response packet arrives at the host.
Right now it is unclear why the response icmp packet is not forwarded to the container. Iptables (filter and nat) looked ok. Something inside docker failed.
The system was up to date and docker was installed in the latest (current) version.
Solution:
Setup an own bridged network. Like network create --subnet=172.20.0.0/24 --gateway=172.20.0.1 docker20 read documentation for details.
See answer answer for details.
Disclaimer: I'm not able to reproduce this issue. The root cause is still unclear but will not be investigated any more.
Recommendation: instead of starting containers directly with docker run use docker compose files instead.
A docker compose file would look like
version: "3.1"
services:
  alpine-sshd:
    image: busybox
    container_name: busybox
    command:   [ping , "-c2", "142.250.186.142"]
# optional own network
networks:
   default:
     external: true
     name: <NETWORKNAME>

A: I had the same problem on Ubuntu 22.04 LTS.  The containers on my machines spun up via docker compose had no outbound connectivity.
I noticed that docker networks created via "docker compose" did not have any of the options enabled, when compared to the default "bridge" network that containers attach to via "docker run".
For example, running "docker network inspect bridge" shows the following options.
<<snipped>>
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
<snipped>>

I was able to fix the "docker compose" created network by explicitly creating a network and setting those same options in the docker-compose file.
version: '3'
services:

  busybox:
    hostname: busybox
    image: "busybox:latest"
    restart: always
    command: sh -c "while true; do date; sleep 60; done"
    links:
      - influxdb2
    networks:
      - default

# "docker compose" on my ubuntu 20.04 seems to not declare default options.
#   This is needed... unclear why
networks:
  default:
    driver: bridge
    driver_opts:
      com.docker.network.driver.mtu: "1450"
      com.docker.network.bridge.default_bridge: "true"
      com.docker.network.bridge.enable_icc: "true"
      com.docker.network.bridge.enable_ip_masquerade: "true"
      com.docker.network.bridge.host_binding_ipv4: "0.0.0.0"
      com.docker.network.bridge.name: "docker0"
      com.docker.network.driver.mtu: "1500"

From there, I'm able to do a:
docker compose up -d
docker compose exec -it busybox ping google.com

A: I had this same issue, and resolved it by disabling IPv6. This can be done via sysctl.

*

*Add the following to /etc/sysctl.conf
net.ipv6.conf.all.disable_ipv6=1
net.ipv6.conf.default.disable_ipv6=1
net.ipv6.conf.lo.disable_ipv6=1

*Apply changes with sudo sysctl -p


text:
Q: Broken pin on Intel heatsink - is it a risk? I recently needed to remove the heatsink/fan from my H61M-HVS motherboard to reapply thermal paste to it for the first time since it was bought almost a decade ago. After removing the heatsink/fan combination, cleaning the CPU and  reapplying thermal paste to it (I used Arctic MX-2), I had a lot of frustration getting the heatsink's plastic push-pins to go back into the slots on the motherboard, and in the process broke the end of one of the pins, making it no longer possible to push it down to lock it.
This isn't my picture, but the pins are identical to those seen here:

I managed to rotate and push down the other three pins, and the heatsink doesn't budge when moved, but I'm concerned that this missing pin will mean the heatsink isn't flush with the CPU, and by extension, the thermal paste.
I'm also planning to install a third, 7200 RPM hard drive soon, which will only increase the heat in the system and make it even more necessary that the heat dissipation of the system isn't compromised to a dangerous point.
Help threads online for identical scenarios recommend that the entire heatsink be replaced for a new one, but I don't want to do this unless absolutely necessary since I'm on a very low income.
Do I need to buy a new heatsink, or will 3 out of 4 secured pins be enough to make sure the thermal paste doesn't run and that the system doesn't heat up more than it should?
This is the heatsink/fan combination in question:

A: tbh, if you're super worried getting a cheap third party heatsink should be an option.
Its not about pins though. Its about having appropriate, even clamping force. If the existing pins can hold down the heatsink properly (and I guess they might), you should be fine. You even know why if your PC starts overheating, and intel has decent thermal protection built in for over a decade.
While technically it is a comment -

but I'm not sure about whether that improvement will hold, especially after the new HDD is installed

Shouldn't affect your core temperatures more than a dodgy chip.
So, options!
Just leave it, and buy a heat sink if and when your system starts acting up. Useful if its an older system, less so if its an only system
Buy a heatsink - there's decent 30 dollar or so ones, or you might even be able to buy yourself a stock Intel heatsink off some online marketplace.
But if your temperatures are fine, I'd guess the diagonally opposed pins are holding the heatsink tight enough and you're fine. Just be careful the next time.

A: Unfortunate
You already know you're running a greater risk of overheating with only three pins.
You even say:

...increase the heat in the system and make it even more necessary that the heat dissipation of the system isn't compromised

It's too bad that it broke, but you should replace it and move on, worry free.

A: Super old post but here's my 2 cents .., I managed to do the same thing... 3 pins worked fine for around 2 years .. I used silver fox paste. Then I went to clean again and took my comp to a friend's house ended up breaking off another ... also I ran out of silver fox thermal paste and used some generic stuff ... I went from fine to idling at 70c . Soo not sure if it was just the power of the compound being high quality that kept it good or if two pins is too little to keep it tight, either way I used it for about a year like that no issues , but it's starting to cause me issues ... just ordered a new stock 8dollar heatsink and some more thermal paste . All good to go. 30-50c again =] cheers


text:
Q: How to wrap a React component by React.cloneElement using a function? For example, lets say I have the following routes:
<Switch>
  <Route path='/login' component={Login} />
  <Route path='/home' component={HomePage} />
  <Route path='/profile' component={Profile} />
</Switch>

And I want to Wrap this components in a div, to pass a style and a new prop, using a function to be more reusable, like so:
<Switch>
  <Route path='/login' component={wrapper(Login, 'red')} />
  <Route path='/home' component={wrapper(Home, 'blue')} />
  <Route path='/profile' component={wrapper(Profile, 'green')} />
</Switch>

Where wrapper would be something like this:
const wrapper = (component, color) => {
  return (

       <Component color={color} />

  )
}

How is that possible? I tried some alternatives like:
const wrapper = (component, text) => {
  return React.cloneElement(component, {color: text})
 }

But not sure how I can do this using React.cloneElement or any other pattern.

A: You could use the render prop instead of the component prop and pass the color prop to the components that way.
<Switch>
  <Route path='/login' render={(props) => <Login color="red" {...props} />} />
  <Route path='/home' render={(props) => <HomePage color="blue" {...props} />} />
  <Route path='/profile' render={(props) => <Profile color="green" {...props} />} />
</Switch>


text:
Q: Why are these boxes spaced like this html/css
I have this webpage I'm creating, and I want there to be these three boxes at the bottom. there is a weird space between the background image and the boxes, I want there to only be a 15px space but no matter what I change, it still does this.

#Textboxes {
      width: 1280px;
      height: 600px;
      margin-left: auto;
      margin-right: auto;
      margin-top: 0px;
    }

#Textboxes div {
      list-style: none;
      display: inline;
      width:427px;
      height:600px;
    }

.Text-sub ul {
      display: inline-block;
      background-color: #3f3f3f;
      list-style: none;
      width: 378px;
      height: 600px;
      margin-left: 5px;
      opacity: 0.7;
      filter: alpha(opacity=70);
      margin-top: 10px;
    }

.Text-sub ul:hover {
      background-color: #696969;
      transition: all 0.6s;
      opacity: 100;
      filter: alpha(opacity=0)
    }

.Text-sub ul li h2 {
      text-align: center;
    }

.Text-sub ul li h3 {
      text-align: center;
    }

.Text-sub ul li h4 {
      text-align: center;
    }
.Text-sub ul li a {
      color: black;
    }
.Text-sub ul li p {
      padding-right: 30px;
    }

Information Example

This is where information about the company will go.

FAQ Example

This is where Frequently asked questions will go

More

Privacy

Terms of Use

Store Locator

Social Media

A: Because the default vertical alignment for inline elements is baseline. You probably want top for your .Text-sub ul elements:

#Textboxes {
  width: 1280px;
  height: 600px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 0px;
}
#Textboxes div {
  list-style: none;
  display: inline;
  width: 427px;
  height: 600px;
}
.Text-sub ul {
  display: inline-block;
  background-color: #3f3f3f;
  list-style: none;
  width: 378px;
  height: 600px;
  margin-left: 5px;
  opacity: 0.7;
  filter: alpha(opacity=70);
  margin-top: 10px;
    vertical-align:top;

}
.Text-sub ul:hover {
  background-color: #696969;
  transition: all 0.6s;
  opacity: 100;
  filter: alpha(opacity=0)
}
.Text-sub ul li h2 {
  text-align: center;
}
.Text-sub ul li h3 {
  text-align: center;
}
.Text-sub ul li h4 {
  text-align: center;
}
.Text-sub ul li a {
  color: black;
}
.Text-sub ul li p {
  padding-right: 30px;
}

Information Example

This is where information about the company will go.

FAQ Example

This is where Frequently asked questions will go

More

Privacy

Terms of Use

Store Locator

Social Media

A: It's just because of the content and the inline-block. By default inline-blocks are baseline aligned. Give the fix to the elements that are displayed inline-block:
vertical-align: top;

And it should display well.

#Textboxes {
  width: 1280px;
  height: 600px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 0px;
}
#Textboxes div {
  list-style: none;
  display: inline;
  width: 427px;
  height: 600px;
}
.Text-sub ul {
  display: inline-block;
  background-color: #3f3f3f;
  list-style: none;
  width: 378px;
  height: 600px;
  margin-left: 5px;
  opacity: 0.7;
  filter: alpha(opacity=70);
  margin-top: 10px;
  vertical-align: top;
}
.Text-sub ul:hover {
  background-color: #696969;
  transition: all 0.6s;
  opacity: 100;
  filter: alpha(opacity=0)
}
.Text-sub ul li h2 {
  text-align: center;
}
.Text-sub ul li h3 {
  text-align: center;
}
.Text-sub ul li h4 {
  text-align: center;
}
.Text-sub ul li a {
  color: black;
}
.Text-sub ul li p {
  padding-right: 30px;
}

Information Example

This is where information about the company will go.

FAQ Example

This is where Frequently asked questions will go

More

Privacy

Terms of Use

Store Locator

Social Media

Preview


text:
Q: How to create a attacment from visualforce site? How to create a attacment from visualforce site? I have created godaddy domain in our salesforce and given certificates for domain. for this domain i have access to view the visuaforce pages.I have created visualforce page as renderas"PDF" and i am calling from visualforce page attachment is created successfully but when i run the page from site its not created the attachment. i have given access the visualforce page andenter code here apex controller and also i have given access to object and fields.see below code.
account acc =[select id,name from account where id='myrecordid'];
pagereference pgref = page.mypdfpage;
pageref.getParameters().put('id',acc.Id);
pageref.setRedirect(false);
blob body;
body= pageref.getContentAsPDF();
Attachment attach = new Attachment();
attach.body = body;
attach.Name = 'myattachpage';
attach.Isprivate = false;
attach.ParentId = acc.Id;
attach.ContentType = 'pdf';
insert attach;


text:
Q: Why won't ogrinfo write to new column using informaiton from previous columns? I'm having problems classifying an area of mixed forest using ogrinfo.
I have an .sqlite file which contains the three columns; proportionclass1. proportionclass2, proportionclass3.
I'm trying to assign a description for each observation in a new column (assessment) based on if the percentage of any of the classes is over a certain threshold (this case 70). So if proportionclass1 is over 70 I want it to write NutrientDeficient to the assessment column, if proportionclass2 is over 70 I want it to write Healthy to the assessment column, if proportionclass3 is over 70 I want it to write BareSoil to the assessment column, and if none of the cells for any observations of the three proportion classes are over 70 then i want it to write mixed in the assessment column.
The code i have is below, could anyone point out what im missing or what i've done wrong as the code will run without an error but the assessment column will remain blank.
ogrinfo -dialect SQLite -sql "ALTER TABLE table_name ADD COLUMN assessment Text" classified_area.sqlite

ogrinfo -dialect SQLite -sql "SELECT *,
                                CASE
                                 WHEN proportionclass1 > 70 THEN 'NutrientDeficient'
                                 WHEN proportionclass2 > 70 THEN 'Healthy'
                                 WHEN proportionclass3 > 70 THEN 'BareSoil'
                                 ELSE 'Mixed'
                                END AS assessment
                                FROM layer_name" classified_area.sqlite

A: You have field "assessment" in the table and is gets selected by select *. Then you try to make another selection with the same name with your CASE statement but the result from selecting "assessment" for the first time is not overwritten.
Same query but edited into END AS assessment2gives expected results.
Layer name: SELECT
Geometry: None
Feature Count: 3
Layer SRS WKT:
(unknown)
proportionclass1: Integer (0.0)
proportionclass2: String (0.0)
proportionclass3: String (0.0)
assessment: String (0.0)
assessment2: String (0.0)
OGRFeature(SELECT):0
  proportionclass1 (Integer) = 70
  proportionclass2 (String) = (null)
  proportionclass3 (String) = (null)
  assessment (String) = (null)
  assessment2 (String) = Mixed

OGRFeature(SELECT):1
  proportionclass1 (Integer) = (null)
  proportionclass2 (String) = 70
  proportionclass3 (String) = (null)
  assessment (String) = (null)
  assessment2 (String) = Mixed

OGRFeature(SELECT):2
  proportionclass1 (Integer) = (null)
  proportionclass2 (String) = (null)
  proportionclass3 (String) = 70
  assessment (String) = (null)
  assessment2 (String) = Mixed

If you want to store the values into the database you must write SQL as -sql "update layer_name set assessment=...


text:
Q: ASp.net core IActionResult csv encoding problem I have a problem when trying to save a csv file though an IActionResult. Special characters like åøæ will not be shown properly when opening the csv file. I have tried a lot of different approaches, but nothing seems to work. My latest attempt was trying to use the CsvHelper library but doesn't seem to work neither. Here is my latest attempt.
        byte[] result;
        await using (var memoryStream = new MemoryStream())
        await using (var streamWriter = new StreamWriter(memoryStream, new UTF8Encoding(true)))
        {
            var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture);
            csvWriter.Configuration.Delimiter = ";";
            await csvWriter.WriteRecordsAsync(data);
            await streamWriter.FlushAsync();
            result = memoryStream.ToArray();
        }

        return new FileStreamResult(new MemoryStream(result), "text/csv")
        { FileDownloadName = $"data.csv" };

I hobe someone can help me, thanks in advance.

A: As far as I know, this issue is related with Excel not asp.net core application. We could set the download file format to use utf-8, but excel doesn't open it with right format.
You could open your csv file and find it shows as below:

But excel shows like this:

To force excel to show the special character, you should follow below steps:
1.Open Excel and new a empty excel
2.Import the data using Data-->Import External Data --> Import Data
3.Select the file type of "csv" and browse to your file
4.In the import wizard change the File_Origin to "65001 UTF" (or choose correct language character identifier)
5.Change the Delimiter to comma
6.Select where to import to and Finish
Generate csv codes:
          List<Student> students = new List<Student>
{
    new Student { Id = 1, FirstName = "éåæÉà;some other value", LastName = "Kanjilal" },
    new Student { Id = 2, FirstName = "Steve", LastName = "Smith" },
    new Student { Id = 3, FirstName = "Anand", LastName = "Narayaswamy"}
};
            try
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("Id,FirstName,LastName");
                foreach (var student in students)
                {
                    stringBuilder.AppendLine($"{student.Id},  { student.FirstName},{ student.LastName}");
                }
                return File(Encoding.UTF8.GetBytes
                (stringBuilder.ToString()), "text/csv;charset=utf-8", "student.csv");
            }
            catch
            {
                return Error();
            }


text:
Q: How to write a float32 picture to video file in OpenCV2? I am experiencing a weird problem here.
I get back an output image from my neural network, it has dtype float32. I add a background picture I took from the internet, convert it to float32 from uint8, and then added my output on top of the background picture.
Now, I want to save it, but cv2.VideoWriter.write(blahblah) only takes in uint8. I thought that to convert float32 to uint8, one would just do * 255, but that is probably wrong because I experience some weird glares (my picture can be found here: OpenCV image shows weird glare after un-normalizing with * 255) when I do so, probably because of floating point classic errors or things of that nature. So, how do I safely convert float32 to uint8? Or, how do I write float32 to file?
To be honest, I am very confused about some of the things. I know uint8 is [0, 255] and float32 is [0, 1], and I know that cv2.videowriter.write takes in uint8, that's it. On the side note, a solution appears to be to change everything to .astype(uint8) from the beginning, but I my neural net spits out a float32 so I have to work with that.

A: Float32 does not set is from 0 till 1 that is mostlikly done by your neuralnetwork (softmax or sigmoid as last activation function). To set something to a different range this can be used:
normalized_array = (array - np.min(array))/(np.max(array) - np.min(array)) # this set the range from 0 till 1
img_array = (normalized_array * 255).astype(np.uint8) # set is to a range from 0 till 255


text:
Q: Modify Post Excerpts I am using a wordpress install with the Advanced Excerpt plugin. I have changed the settings so that no text is displayed in excerpt, but I cant get it to remove the category and tag labels aswell.

A: I have solved the issue by inserting the following code into stylesheet.css;
.archive-excerpt {
display: none;
}


text:
Q: Calculate limit of two integrale I have no idea how to calculate (I know that the answer is 1 but why ?).
Maybe with a theorem or with trigonometric properties ...

$$ \lim_{m\to\infty} \frac{\int_0^{\pi/2}(\sin x)^{2m}dx}{\int_0^{\pi/2}(\sin x)^{2m+1}dx} $$

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

With Laplace's Method:

\begin{align}
\int_{0}^{\pi/2}\sin^{p}\pars{x}\,\dd x & =
\int_{0}^{\pi/2}\cos^{p}\pars{x}\,\dd x =
\int_{0}^{\pi/2}\exp\pars{p\ln\pars{\cos\pars{x}}}\,\dd x\quad
\pars{\begin{array}{l}
\mbox{The integral "main}
\\
\mbox{contribution"}
\\
\mbox{occurs at}\ x \gtrsim 0
\end{array}}
\\[5mm] & \stackrel{\mrm{as}\ p\ \to\ \infty}{\sim}\,\,\,
\int_{0}^{\infty}\exp\pars{-\,{p \over 2}\,x^{2}}\,\dd x = \root{\pi \over 2}\,
{1 \over p^{1/2}}
\end{align}

$\ds{\implies \lim_{m \to \infty}{\int_{0}^{\pi/2}\sin^{2m}\pars{x}\,\dd x \over \int_{0}^{\pi/2}\sin^{2m + 1}\pars{x}\,\dd x} =
\lim_{m \to \infty}\root{1 + {1 \over 2m}} = \bbx{\large 1}}$

A: I'll use the result $2\int_0^{\pi/2}\sin^{2a-1}x\cos^{2b-1}xdx=\frac{\Gamma (a)\Gamma (b)}{\Gamma (a+b)}$ so $$\frac{\int_0^{\pi/2}\sin^{2m}xdx}{\int_0^{\pi/2}\sin^{2m+1}xdx}=\frac{\Gamma(m+\frac{1}{2})\Gamma(m+\frac{3}{2})}{\Gamma^2(m+1)}=\exp (\ln\Gamma (m+\tfrac{1}{2})-2\ln\Gamma (m+1)+\ln\Gamma (m+\tfrac{3}{2})).$$Since $x\mapsto x+1$ increases $\ln\Gamma (x)$ by $\ln x$, the right-hand side approximates $$\exp\frac{1}{2}\ln\frac{m+1}{m+1/2},$$where we have linearised the log-Gamma function. Since the exponential's argument is $O(\frac{1}{m})$, the limit is $1$.


text:
Q: Array.join inserts extra characters when joining strings created with String.fromCharCode I have an array of bytes that I would to to encode to a string to pass to btoa in the browser.  These bytes use the full 0-255 range.  I encountered what at first seemed to be a bug with btoa, but it turns out to be a bug (or at least quite unexpected behavior) with javascript's Array.prototype.join.  To illustrate the problem, I'll start with some base64-encoded data:
gACJNqQ0cg==

This can be decoded to a byte array as follows:
atob('gACJNqQ0cg==').split('').map(c => c.charCodeAt(0))
> [128, 0, 137, 54, 164, 52, 114]

Now, you would expect to be able to reverse the operation and get back the original string:
btoa([128, 0, 137, 54, 164, 52, 114].map(String.fromCharCode).join(''))

But instead, you get a much larger string:
gAAAAAEAiQIANgMApAQANAUAcgYA

Upon further investigation, the problem occurs when joining any strings created with String.fromCharCode:
'Hi'.split('').join('').length
> 2
'Hi'.split('').map(c => c.charCodeAt(0))
> [72, 105]
[72, 105].map(String.fromCharCode).join('').length
> 6
//what?

I see this behavior everywhere I have tried it: Chrome (60), Firefox (53), and Node (6.9.4).  In the browser, you don't have simple alternatives such as node's
new Buffer(array, 'binary').toString('base64') to work around this problem.  How can I safely create a string from an array of byte values, which can be passed to btoa?

A: Your code works for me if you specify an arrow function in map instead of directly passing the String.fromCharCode method to it:

console.log(btoa([128, 0, 137, 54, 164, 52, 114].map(x => String.fromCharCode(x)).join('')));

A: I found a simple workaround to this complicated problem:  String concatenation.  Here's an example:
let str = '';
[128, 0, 137, 54, 164, 52, 114].forEach(c => {
    str += String.fromCharCode(c);
});

str.length
> 7
btoa(str)
>
).join('').length

It works, and it should perform well enough for strings that aren't huge.  But I would love to see a better, cleaner, solution, or even just to understand more fully what's going on here with String.fromCharCode and Array.prototype.join.


text:
Q: How is the transition of code made in view source page While viewing a page source in fireBug the code is displayed in html. But my code is written in xhtml. How is the conversions made.
Thanks.

A: Firebug does not show the source. It shows a representation of the live DOM.
Additionally, browsers will treat XHTML as HTML if the server tells them it is Content-Type: text/html instead of Content-Type: application/xhtml+xml.

A: Firebug dose not show the source code .Firebug use as a debugging tool .Main Reason of use firebug
-->The Key to Successful Web Development
-->Debugging and Testing the Web with Firebug
-->Debug and tune applications on the fly with Firebug
-->Quick & Easy CSS Development with Firebug So on

when we try to see source view of a page browser return the code as a plain Html.This is one of reason you cannot see your code which is written in xhtml


text:
Q: Change date format of the DatePickerDialog Calendar in Android I'm using DatePickerDialog in my code. And I want to know, How to change date format of the DatePickerDialog Calendar in format dd mm yyyy.
My code is :-
public static class DatePickerDialogTheme5 extends DialogFragment implements DatePickerDialog.OnDateSetListener{

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState){
            SimpleDateFormat sdf=new SimpleDateFormat("dd MM yyyy");
            Date d=new Date();
            sdf.format(d);
            final Calendar calendar = Calendar.getInstance();
            calendar.setTime(d);

            calendar.set(calendar.YEAR,d.getYear());
            calendar.set(calendar.MONTH,d.getMonth());
            calendar.set(calendar.DAY_OF_MONTH,d.getDay());

            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog datepickerdialog = new DatePickerDialog(getActivity(),
                    //AlertDialog.THEME_TRADITIONAL,this,day,month,year);
            AlertDialog.THEME_DEVICE_DEFAULT_DARK,this,year,month,day);

            return datepickerdialog;
        }

        public void onDateSet(DatePicker view, int year, int month, int day){
            TextView textview = (TextView)getActivity().findViewById(R.id.textView1);
            textview.setText(day + ":" + (month+1) + ":" + year);
        }
    }

I Want to show Date Picker Dialog like this

A: Not sure what you would like to achieve, but you could use a Calendar instance with SimpleDateFormat to format your Date according to your needs.
For example:
public void onDateSet(DatePicker view, int year, int month, int day) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, day);

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy");

    String dateString = dateFormat.format(calendar.getTime());

    TextView textview = (TextView)getActivity().findViewById(R.id.textView1);
    textview.setText(dateString);
}

A: Here i disabled previous dates also

 inside onclick listener
    edit_event_date.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DatePickerFragment dFragment = new DatePickerFragment();
                    dFragment.show(DashBoardActivity.this.getFragmentManager(), "Date Picker");

                }
            });

     @SuppressLint("ValidFragment")
        public class DatePickerFragment extends android.app.DialogFragment implements DatePickerDialog.OnDateSetListener {
            int year, month, day;

            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {

                final Calendar calendar = Calendar.getInstance();
                year = calendar.get(Calendar.YEAR);
                month = calendar.get(Calendar.MONTH);
                day = calendar.get(Calendar.DAY_OF_MONTH);
                DatePickerDialog dpd = new DatePickerDialog(getActivity(), this, year, month, day);
                dpd.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
                return dpd;
            }

            public void onDateSet(DatePicker view, int syear, int selectedmonth, int selectedday) {
                view.setMinDate(System.currentTimeMillis() - 1000);//disable dates

                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(0); ////disable dates
                cal.set(syear, selectedmonth, selectedday, 0, 0, 0);
                SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
                String dateString = dateFormat.format(cal.getTime());
//in loolipop disable dates also we can select so for that restriction below condition
                if (syear == year && (selectedmonth + 1) == month + 1) {
                    if (selectedday < day) {
                        Toast.makeText(getActivity(), "invalid date", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                edit_event_date.setText(dateString);

            }

        }

A:  @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        edt_date_of_birth.setText(null);
        edt_date_of_birth.setInputType(InputType.TYPE_NULL);

        int day = dayOfMonth;
        int yy = year;
        int month = ++monthOfYear;
        String str_day = day < 10 ? "0" + day : "" + day;
        String str_month = month < 10 ? "0" + month : "" + month;
        String date_select = String.valueOf(yy) + "-" + str_month + "-" + str_day;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = null;
        try {
            date1 = format.parse(date_select);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String date = format.format(date1);
        if(date.endsWith("01") && !date.endsWith("11"))
            format = new SimpleDateFormat("d'st' MMM, yyyy");
        else if(date.endsWith("02") && !date.endsWith("12"))
            format = new SimpleDateFormat("d'nd' MMM, yyyy");
        else if(date.endsWith("03") && !date.endsWith("13"))
            format = new SimpleDateFormat("d'rd' MMM, yyyy");
        else
            format = new SimpleDateFormat("d'th' MMM, yyyy");
        String yourDate = format.format(date1);
        edt_date_of_birth.setText(yourDate);
    }