text:
Q: How to sort row index case-insensitive way in Pandas DataFrame I have the following data:
Set Coolthing Route Organ Up Down
set4 Pam3CSK4 ID LL 81 60
set4 Poly_IC ID LL 542 92
set4 Poly_IC ID MM 73 73
set4 cdiGMP ID MM 143 78
set4 Poly_IC ID BB 32 82
set4 cdiGMP ID BB 90 129

With the following code:
import pandas as pd
df = pd.io.parsers.read_table("http://dpaste.com/2PHS7R0.txt",sep=" ")
df = df.pivot(index="Coolthing",columns="Organ").fillna(0)
df.drop('Set',axis=1,inplace=True)
df.drop('Route',axis=1,inplace=True)
df.index.name = None
df.columns.names = (None,None)

I get the following:
In [75]: df
Out[75]:
          Up            Down
          BB   LL   MM    BB  LL  MM
Pam3CSK4   0   81    0     0  60   0
Poly_IC   32  542   73    82  92  73
cdiGMP    90    0  143   129   0  78

What I want to do is to sort the row with case insensitive way
yielding this:
          Up            Down
          BB   LL   MM    BB  LL  MM
cdiGMP    90    0  143   129   0  78
Pam3CSK4   0   81    0     0  60   0
Poly_IC   32  542   73    82  92  73

How can I achieve that?

A: Building on @Marius case_insensitive_order, a single liner using reindex
In [63]: df.reindex(sorted(df.index, key=lambda x: x.lower()))
Out[63]:
          Up            Down
          BB   LL   MM    BB  LL  MM
cdiGMP    90    0  143   129   0  78
Pam3CSK4   0   81    0     0  60   0
Poly_IC   32  542   73    82  92  73

A: You can force this by using the new CategoricalIndex (new in 0.16.1, I think), but I'm not sure if it's a great idea as it may have unpredictable effects:
case_insenstive_order = sorted(df.index, key=lambda x: x.lower())
case_insenstive_order
Out[4]: ['cdiGMP', 'Pam3CSK4', 'Poly_IC']

df.index = pd.CategoricalIndex(df.index,
                               categories=case_insenstive_order,
                               ordered=True)
df.sort_index()
Out[7]:
          Up           Down
          BB   LL   MM   BB  LL  MM
cdiGMP    90    0  143  129   0  78
Pam3CSK4   0   81    0    0  60   0
Poly_IC   32  542   73   82  92  73

A: I consider this a valid answer too:
df = df.iloc[df.index.str.lower().argsort()]

However, reindex certainly works a bit faster:
%timeit df.reindex(sorted(df.index, key=lambda x: x.lower()), copy=True)
1000 loops, best of 3: 794 µs per loop

%timeit df.iloc[df.index.str.lower().argsort()]
1000 loops, best of 3: 850 µs per loop

I tested here with pandas 0.20.3 and python2 on a table that had 500 rows and about 50 columns.


text:
Q: Does $\sum_{n=1}^\infty {\frac{ \sin(\frac{n\pi}{6})}{\sqrt {n^4 + 1}}}$ converge? Does the series
$$\sum_{n=1}^\infty {\frac{ \sin(\frac{n\pi}{6})}{\sqrt {n^4 + 1}}}$$ converge?
I tried with comparison test, limit comparison test, ratio test and others but I cannot figure this out.

A: I think comparison test is useful. Since $|\sin x| \le 1$ and $\sqrt{n^4+1}\ge n^2$,
$$
0\le\left|\frac{\sin\frac{n\pi}{6}}{\sqrt{n^4+1}}\right| \le \frac{1}{n^2}
$$
and $\displaystyle \sum_{n=1}^{\infty}\frac{1}{n^2}$ converges. Therefore, given series converges absolutely.

A: $$\left|\frac{\sin\left(\frac{n\pi}{6}\right)}{\sqrt{n^4 +1}}\right|\leq\frac{1}{n^2}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: nar-maven-plugin and native-library-loader dont load native lib I testing with nar-maven-plugin, then in the next project I need JNI :( . I choosed the it0003 example from git repo. Without the native-library-loader, manual placing of the library and setting of library path its run. Then i would use the native-library-loader. For that, I added the dependency and the assembly-plugin for single JAR file. My current pom:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  Native ARchive plugin for Maven
  %%
  Copyright (C) 2002 - 2014 NAR Maven Plugin developers.
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.github.maven-nar.its.nar</groupId>
    <artifactId>it-parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../it-parent/pom.xml</relativePath>
  </parent>

  <artifactId>it0003-jni</artifactId>
  <packaging>nar</packaging>

  <name>NAR JNI Test</name>
  <version>1.0-SNAPSHOT</version>
  <description>
    Simple JNI Library
  </description>
  <url>http://maven.apache.org/</url>

  <properties>
    <skipTests>true</skipTests>
  </properties>

  <build>
    <defaultGoal>install</defaultGoal>
    <plugins>
      <plugin>
        <groupId>com.github.maven-nar</groupId>
        <artifactId>nar-maven-plugin</artifactId>
        <extensions>true</extensions>
        <configuration>
          <cpp>
            <debug>true</debug>
          </cpp>
          <c>
            <testOptions>
              <testOption>-DTESTOPT="this is a nar-testCompile flag"</testOption>
            </testOptions>
          </c>
          <libraries>
            <library>
              <type>jni</type>
              <narSystemPackage>it0003</narSystemPackage>
              <linkCPP>false</linkCPP>
            </library>
          </libraries>
          <javah>
            <includes>
              <include></include>
            </includes>
          </javah>
          <tests>
            <test>
              <name>HelloWorld</name>
            </test>
          </tests>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.4.1</version>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          <archive>
            <manifest>
              <mainClass>it0003.HelloWorldJNI</mainClass>
            </manifest>
          </archive>
        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>
      <dependency>
          <groupId>org.scijava</groupId>
          <artifactId>native-lib-loader</artifactId>
          <version>2.0.2</version>
      </dependency>
  </dependencies>
</project>

Then I placed the resulting JAR and the NAR in the same directory and starts with:
    rd4@PC222-VirtualBox ~/Schreibtisch/nartest $ java -Djava.library.path=/home/rd4/Schreibtisch/nartest/ -jar it0003-jni-1.0-SNAPSHOT-jar-with-dependencies.jar

Then i get following error:
java.lang.RuntimeException: Library 'libit0003-jni-1.0-SNAPSHOT.so' not found!
    at it0003.NarSystem.getLibPath(NarSystem.java:141)
    at it0003.NarSystem.loadLibrary(NarSystem.java:45)
    at it0003.HelloWorldJNI.<clinit>(HelloWorldJNI.java:27)
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Library 'libit0003-jni-1.0-SNAPSHOT.so' not found!
    at it0003.NarSystem.getLibPath(NarSystem.java:141)
    at it0003.NarSystem.loadLibrary(NarSystem.java:45)
    at it0003.HelloWorldJNI.<clinit>(HelloWorldJNI.java:27)

Has anyone an idea what my mistake is?

A: Ran into this same issue.
Make sure your $JAVA_HOME environment variable is set. On Linux, you can find this using which java, then exporting the path using export <path>.
Additionally, you should link to the include paths in the compiler options in your pom.xml file:
<c>
  <name>gcc</name>
  <exceptions>false</exceptions>
  <debug>false</debug>
  <includes>
    <include>**/*.c</include>
  </includes>
  <options>
    <option>-I${java.home}/include</option>
    <option>-I${java.home}/include/linux</option>
  </options>
</c>

<linker>
  <name>gcc</name>
  <options>
    <option>-I${java.home}/include</option>
    <option>-I${java.home}/include/linux</option>
  </options>
</linker>

Hopefully this helps, pretty sure this was what fixed it. If I figure out what actually fixed it, I'll update this answer.


text:
Q: How to avoid requiring any native libraries for compression in Spark We are doing a POC on a variety of server machines/architectures. We do not have the ability to rebuild native compression libraries for all of them.
Which codec is software only?  The default snappy is giving the following error:
Caused by: java.lang.IllegalArgumentException
    at org.apache.spark.io.SnappyCompressionCodec.<init>(CompressionCodec.scala:152)

A:  lz4

Is software only. That is working.
The way to configure: in $SPARK_HOME/conf/spark-defaults.conf:
 spark.io.compression.codec lz4


text:
Q: Транспонирование матриц - оптимизация кода
Задание:
1) Реализуйте метод transpose, транспонирующий матрицу и
  возвращающую результат. Данный метод модифицирует экземпляр класса
  Matrix.
2) Реализуйте статический метод transposed, принимающий Matrix и
  возвращающий транспонированную матрицу. Данный метод НЕ модифицирует экземпляр класса Matrix

Мой код:
from copy import deepcopy

class Matrix(object):
    def __init__(self, matrix):
        self.matrix = deepcopy(matrix)

    def __str__(self):
        return '\n'.join('\t'.join(map(str, row)) for row in self.matrix)

    def transpose(self):
        tmatrix = list(zip(*self.matrix))
        self.matrix = tmatrix
        return Matrix(tmatrix)

    @staticmethod
    def transposed(m):
        return '\n'.join('\t'.join(map(str, row)) for row
                         in list(list(x) for x in list(zip(*m.matrix))))

2 теста отрабатывают нормально. Тест 1:
m = Matrix([[10, 10], [0, 0], [1, 1]])
print(m)
m1 = m.transpose()
print(m)
print(m1)

10  10
0   0
1   1
10  0   1
10  0   1
10  0   1
10  0   1

Тест 2:
m = Matrix([[10, 10], [0, 0], [1, 1]])
print(m)
print(Matrix.transposed(m))
print(m)

10  10
0   0
1   1
10  0   1
10  0   1
10  10
0   0
1   1

А теперь интрига: проверяющая система выдает ошибку по тесту, содержание которого никому неизвестно, в виде Runtime error (задала вопрос на форуме курса - пока тишина). Возможные варианты: код действительно можно оптимизировать чтобы работал быстрее, transposed реализован не статическим методом.
Как думаете, что можно улучшить?

A: Попробуйте так:
class Matrix(object):
    def __init__(self, matrix):
        self.matrix = deepcopy(matrix)

    def __str__(self):
        return '\n'.join('\t'.join(map(str, row)) for row in self.matrix)

    @staticmethod
    def transposed(m):
        return Matrix(list(zip(*m.matrix)))

    def transpose(self):
        self.matrix = list(zip(*self.matrix))
        return self

Решение позаимствованное отсюда, которое наконец удовлетворило "autograder" Курсеры:
def transpose(self):
    """
    Transpose matrix, update exist object
    :return: transposed exist matrix object
    """
    self.rows = [list(l) for l in zip(*self.rows)]
    return self

@staticmethod
def transposed(matrix):
    """
    Transpose input matrix object
    :param matrix:
    :return: new transposed matrix object
    """
    matrix = Matrix(matrix.rows).transpose()
    return matrix


text:
Q: Extract separate double values from string value visual basic. Net I'm trying here to extract double values 3.6, 2.4, 4.8 separately - each one into a separate text box- from this string text "3.6 (2.4 to 4.8)"
Dim A as string = textbox1.text ' "3.6 (2.4 to 4.8)"
Textbox2.text = value1' 3.6
Textbox3.text = value2' 2.4
Textbox4.text = value3' 4.8

Thanks in advance :)
An update
I searched and tried to use this code
Dim A as string = textbox1.text ' "3.6 (2.4 to 4.8)"
Dim M as Match = Regex.Match(A, "\d+(?:[.,]\d+) *")
If M.Success Then
Dim R1 = M.groups(0).value
Textbox2.text = R1 ' 3.6

But i don't know how to extract other 2 values

A: I wrote this code and it works for me:
Dim mc As MatchCollection = Regex.Matches(TextBox1.Text, "\d+(?:[.,]\d+) *")
Dim texts(2) As String ' Specifically assigns for 0, 1, 2 (3 elements)
Dim index As Byte = 0 ' Index increment-er

For Each m As Match In mc
    texts(index) = m.ToString ' Writes texts(0... 1... 2...) with m1, m2, m3
    index += 1
Next

TextBox2.Text = texts(0) ' Output
TextBox3.Text = texts(1)
TextBox4.Text = texts(2)


text:
Q: An infinitely-many-variable formal power series ring ${\Bbb F}_p[[X_1,\ldots]]$ We shall define a infinitely-many-variable formal power series ring ${\Bbb F}_p[[X_1,\ldots]]$ as follows$\colon$
${\Bbb F}_p[[X_1,\ldots]]\colon= \underset{n \geq 1}{\varprojlim}\, {\Bbb F}_p[[X_1,\ldots,X_n]]$.
${\Bbb F}_p[[X_1,\ldots]]$ should be a coherent non-noetherian ring which has not been known yet. To prove its coherence, everything boils down to showing the following fact$\colon$
Let us define $A_{n} \colon= {\Bbb F}_p[[X_1,\ldots,X_{n}]]$, $A_{\infty} \colon= {\Bbb F}_p[[X_1,\ldots]]$ and denote by $F_{\infty}$ the fractional field of $A_{\infty}$. Because each $A_n$ is metrizable, the inverse limit $A_{\infty} \colon= \underset{n \geq 1}{\varprojlim}\,A_n$ is also metrizable. So we shall denote by $d$ the metric on $A_{\infty}$.
We fix an arbitrary positive integer $m$ and consider the vector space
$V \colon= F_{\infty}^{\oplus m}$
over $F_{\infty}$. We put $O \colon= (0,\ldots,0)$ which is the origin of $V$. The lattice of $V$ is defined as
$L \colon= A_{\infty}^{\oplus m}$.
The above meric $d$ on $A_{\infty}$ is inherited on $L$ as well.
Now, let us choose $(m-1)$ vectors $v_1,\ldots,v_{m-1} \in V$ such that $v_1,\ldots,v_{m-1}$ are linearly independent over $F_{\infty}$.
For $c_1,\ldots,c_{m-1} \in F_{\infty}$, we set
$v(c_1,\ldots,c_{m-1}) \colon= c_1v_1 + \ldots + c_{m-1}v_{m-1}$.
Suppose that the following two conditions are satisfied$\colon$

*

*$c_1 \notin A_{\infty}$.

*$v(c_1,\ldots,c_{m-1})=(a_1,\ldots,a_m) \in L$ such that ${\mathrm{GCD}}(a_1,...,a_m) = 1$.
Q. under these two conditions, is there a constant $C > 0$ such that the following inequalty holds?$\colon$
$d(O, v(c_1,\ldots,c_{m-1})) > C$.


text:
Q: How do I solve the gcc error on finding pkg-config? This question seems to have been asked a zillion times, but unfortunately, none of the answers helped me.
I believe I have installed gtk correctly. My pkg-config environment seems okay. I'm not so sure of gcc.
I removed all the mingw and cygwin folders from my path environment, as I am only going to be using msys2 packages. So I have my path environment this way:-
GTK_LIB_DIR
C:\msys64\mingw64\lib
PKG_CONFIG_PATH
C:\msys64\mingw64\lib\pkgconfig
Path - C:\msys64\usr\bin;C:\msys64\mingw64\bin;%GTK_LIB_DIR%
The problem I am having is with compilation. Running this...
gcc pkg-config --cflags gtk+-3.0 -o gtkTest C:\dev\test_gtk3.c pkg-config --libs gtk+-3.0
I get...
cc: error: `pkg-config: No such file or directory
gcc: error: gtk+-3.0`: No such file or directory
gcc: error: `pkg-config: No such file or directory
gcc: error: gtk+-3.0`: No such file or directory
gcc: error: unrecognized command line option '--cflags'
gcc: error: unrecognized command line option '--libs'

I can run the following commands separately, with expected results. e.g.
pkg-config --cflags gtk+-3.0
pkg-config --libs gtk+-3.0
gcc -o gtkTest C:\dev\test_gtk3.c

Of course the last command returns an error, since gtk is not referenced.
I tried various combinations, some of my own. Some recommended, but one error persists, on pkg-config.
e.g.
C:\WINDOWS\system32>gcc -o gtkTest C:\dev\test_gtk3.c "pkg-config --cflags gtk+-3.0 pkg-config --libs gtk+-3.0"
gcc: error: pkg-config --cflags gtk+-3.0 pkg-config --libs gtk+-3.0: No such file or directory

The last answer I found says "If pkg-config reports that it couldn't find the package, then you didn't install the Gtk development package as offered by your Linux distribution."
I'm using Windows, but I think I installed gtk correctly, since I followed the instructions, and I get what seems to be the expected results (please correct me if I am mistaken).
C:\WINDOWS\system32>pkg-config --cflags gtk+-3.0
-pthread -mms-bitfields -I/mingw64/include/gtk-3.0 -I/mingw64/include/cairo -I/m
ingw64/include -I/mingw64/include/pango-1.0 -I/mingw64/include/fribidi -I/mingw6
4/include -I/mingw64/include/atk-1.0 -I/mingw64/include/cairo -I/mingw64/include
/pixman-1 -I/mingw64/include -I/mingw64/include/freetype2 -I/mingw64/include -I/
mingw64/include/harfbuzz -I/mingw64/include -I/mingw64/include/libpng16 -I/mingw
64/include/gdk-pixbuf-2.0 -I/mingw64/include -I/mingw64/lib/libffi-3.2.1/include
 -I/mingw64/include/glib-2.0 -I/mingw64/lib/glib-2.0/include -I/mingw64/include

C:\WINDOWS\system32>pkg-config --libs gtk+-3.0
-L/mingw64/lib -L/mingw64/lib/../lib -L/mingw64/lib -lgtk-3 -lgdk-3 -lz -lgdi32
-limm32 -lshell32 -lole32 -Wl,-luuid -lwinmm -ldwmapi -lsetupapi -lcfgmgr32 -lep
oxy -lopengl32 -lgdi32 -lpangocairo-1.0 -lm -lgdi32 -lpangoft2-1.0 -lm -lpangowi
n32-1.0 -lm -lusp10 -lgdi32 -lpango-1.0 -lm -lfribidi -lthai -ldatrie -latk-1.0
-lcairo-gobject -lcairo -lz -lpixman-1 -lm -pthread -lfontconfig -liconv -lexpat
 -lfreetype -lbz2 -lharfbuzz -lm -lusp10 -lgdi32 -lrpcrt4 -lgraphite2 -lpng16 -l
z -lgdk_pixbuf-2.0 -lm -lgio-2.0 -pthread -lintl -lshlwapi -ldnsapi -liphlpapi -
lws2_32 -lgmodule-2.0 -pthread -lintl -lz -lgobject-2.0 -pthread -lintl -lffi -l
glib-2.0 -lintl -lws2_32 -lole32 -lwinmm -lshlwapi -pthread -lm -lpcre

C:\WINDOWS\system32>gcc -o gtkTest C:\dev\test_gtk3.c | pkg-config --cflags --libs gtk+-3.0
-pthread -mms-bitfields -I/mingw64/include/gtk-3.0 -I/mingw64/include/cairo -I/m
ingw64/include -I/mingw64/include/pango-1.0 -I/mingw64/include/fribidi -I/mingw6
4/include -I/mingw64/include/atk-1.0 -I/mingw64/include/cairo -I/mingw64/include
/pixman-1 -I/mingw64/include -I/mingw64/include/freetype2 -I/mingw64/include -I/
mingw64/include/harfbuzz -I/mingw64/include -I/mingw64/include/libpng16 -I/mingw
64/include/gdk-pixbuf-2.0 -I/mingw64/include -I/mingw64/lib/libffi-3.2.1/include
 -I/mingw64/include/glib-2.0 -I/mingw64/lib/glib-2.0/include -I/mingw64/include
-L/mingw64/lib -L/mingw64/lib/../lib -L/mingw64/lib -lgtk-3 -lgdk-3 -lz -lgdi32
-limm32 -lshell32 -lole32 -Wl,-luuid -lwinmm -ldwmapi -lsetupapi -lcfgmgr32 -lep
oxy -lopengl32 -lgdi32 -lpangocairo-1.0 -lm -lgdi32 -lpangoft2-1.0 -lm -lpangowi
n32-1.0 -lm -lusp10 -lgdi32 -lpango-1.0 -lm -lfribidi -lthai -ldatrie -latk-1.0
-lcairo-gobject -lcairo -lz -lpixman-1 -lm -pthread -lfontconfig -liconv -lexpat
 -lfreetype -lbz2 -lharfbuzz -lm -lusp10 -lgdi32 -lrpcrt4 -lgraphite2 -lpng16 -l
z -lgdk_pixbuf-2.0 -lm -lgio-2.0 -pthread -lintl -lshlwapi -ldnsapi -liphlpapi -
lws2_32 -lgmodule-2.0 -pthread -lintl -lz -lgobject-2.0 -pthread -lintl -lffi -l
glib-2.0 -lintl -lws2_32 -lole32 -lwinmm -lshlwapi -pthread -lm -lpcre
C:\dev\test_gtk3.c:1:10: fatal error: gtk/gtk.h: No such file or directory
    1 | #include <gtk/gtk.h>
      |          ^~~~~~~~~~~
compilation terminated.

Has anyone here struggled with this for hours, like I have, and finally got to understand what the problem is.
Please share your solution. Thank you.

A: Using this Installing gtk and compiling using gcc under windows? helped me get past the errors.
I used the following suggestion.

"Instead of a batch file, you may find more convenient to create an
  user environmental variable and store the flags in there, that way you
  will be able to compile from within a normal command prompt."

So I created two new environment variables (e.g. GTK_FLAGS_VARS; GTK_LIBS_VARS), and pasted the outputs in the variable values. Then in path place %GTK_FLAGS_VARS%;%GTK_LIBS_VARS%
Afterward gcc -o gtkTest C:\dev\test_gtk3.c %GTK_FLAGS_VARS% %GTK_LIBS_VARS%


text:
Q: Are all integers fractions? In a college class I was asked this question on a quiz in regards to sets:

All integers are fractions. T/F.

I answered False because if an integer is written in fraction notation it is then classified as a rational number. The teacher said the answer was True and gave me the link http://www.purplemath.com/modules/numtypes.htm. As a teacher of mathematics in the K-12 system I have always taught that integers were all whole numbers above and below zero, and including zero. All of the resources I have used agree to my definition. Please clarify this for me.
What is the truth, or are she and I just mincing words?

A: Every integer $x \in \mathbb Z$ can be expressed as the fraction $x \over 1$

A: I think you have a case to take to the teacher on this based on the teacher's use of the word "fraction" instead of "rational number". All integers are rational numbers also, everyone agrees (or should agree) on that. That is because all integers can be expressed as a ratio of integers. So here's the case:

Is $3$ a binary number?

I'd be surprised if too many people say "yes" to that question. Note that even though $3$ can be expressed as a binary number ($11$), we don't call it a "binary number" unless it is expressed as one.
Similarly, even though every integer can be expressed as a fraction (of integers, even), even mathematicians are likely to agree (for consistency's sake at least) that an integer is not itself a fraction even if it is always a rational number.

A: The important question is what is a fraction. If it is any number that can be expressed as $\frac ab$ with $a,b$ integers, then any integer $c$ can be expressed as $\frac c1$. If the fractions exclude the integers, integers are not fractions.

A: $$
\begin{align}
-7 &= \frac{-7}{1} \\
0 &= \frac{0}{1}\\
1 &= \frac{1}{1} \\
4 &=\frac{4}{1}\\
\end{align}
$$
Note here the $=$. So for example $-7$ is indeed an integer and as a number (element in the set of integers) it is the same as $\frac{-7}{1}$. It is not about thinking about numbers in different ways.

A: I'll assume by "fraction" you mean "rational number". If you want to be extremely pedantic, the answer is, in some sense, no. We don't really have $\mathbb{Z} \subset \mathbb{Q}$, but rather, we identify the rational numbers of the form $a/1$ with the integers. In cases like this, however, we always say that $\mathbb{Z}$ is a subset of $\mathbb{Q}$, even though it isn't strictly true. It would be pointless to so pedantic to say that integers are not rational numbers.
We have the same thing going on when we ask whether $\mathbb{Q}$ sits in $\mathbb{R}$. But, sometimes when doing math, I find it useful to switch between thinking of things as subsets, and thinking of things embedding into another thing, even when something isn't actually a subset.

A: Integers are a subset of rational numbers. This doesn't make them not-rational numbers.

A: The set of rational numbers can be partitioned into the set of ratios and the set of integers. Five clearly falls into the second partition. So the question is, do you define "fraction" as "ratio" (the first partition only) or as "rational".
I would tend to agree with you and define fractions as being non-integral rational numbers, or ratios.
If an integer is a fraction, that legitimizes nonsense like: 5 is 3, plus a fractional part of 2.
Also, note that we never say that numbers are divisible by 1. Prime numbers simply have no divisor, and two relatively prime integers have no common divisor, and that is that. The phrase "other than one" is added so that school children don't get excited. "Fractions" with a denominator of 1, do not count, in a certain sense.
Oh, and by the way, I slipped today and fractured my leg. Luckily, it was fractured in zero places so it is not actually broken. Each bone manifests itself in one whole, healthy fragment!

A: Integers are fractions, because a number is itself no matter how you write it.
A relevant section from Lockhart's A Mathematician's Lament:

In place of a natural problem context in which students can make decisions about what they want their words to mean, and what notions they wish to codify, they are instead subjected to an endless sequence of unmotivated and a priori "definitions." The curriculum is obsessed with jargon and nomenclature, seemingly for no other purpose than to provide teachers with something to test the students on. No mathematician in the world would bother making these senseless distinctions: 2 1/2 is a "mixed number," while 5/2 is an "improper fraction." They're equal for crying out loud. They are the same exact numbers, and have the same exact properties. Who uses such words outside of fourth grade?

Here's a relevant comic from SMBC:

A: I want to point out a different perspective. This is a typical issue where non-rigorous use of language leads to confusion. We often treat objects that are equivalent (under a possibly unspoken equivalence relation) as if they are equal.
Integers and rational numbers are not fractions, in the strictest sense of the word "are". For example, the fractions $1/1$, $4/4$, and $8/8$ are all different fractions, but they all represent the same integer. (Actually, I should say "the fractions represented by the expressions $1/1$, $4/4$, and $8/8$.") None of the fractions $1/1$, $4/4$, and $8/8$ literally is the integer 1. If they were all the same as the integer $1$, they would all be the same as each other - but they are not, because they are different fractions. What is true is that they have the same value as each other.
Similarly, the fractions $1/2$ and $2/4$ are not both the same as the rational number $1/2$, because they are not the same as each other, because they have different numerators. Who would claim that a rational number has a numerator?
When we write
$$
1 = 4/4 = 8/8
$$
the "equals" there only means that fractions represent the same number (they have the same value), not that they are the same fraction. In other words, the $=$ we write is actually an equivalence relation on a set of fractions - the equivalence relation being "has the same value". We have no symbol that we typically use to denote "actual" equality of fractions. This point is often ignored completely in lower-level texts.
The first place that people start to consider these things in detail is in abstract algebra. In that context, we run into many interesting distinctions that would not be visible in elementary math. For example, under the definitions in most algebra books, $\mathbb{Z}$ is an extension of the semigroup $\mathbb{N}$ to a group; $\mathbb{Q}$ is the field of fractions of $\mathbb{Z}$; and $\mathbb{R}$ is the Dedekind completion of $\mathbb{Q}$. It follows from these definitions that the natural number 1 is not the same as the integer 1, both are different than the rational number 1, and all three of those are different from the real number 1.

A: Any integer is a rational number being that the definition of a rational number is any number that can be expressed as the ratio of two integers.  It is enough to have the property without having to explicitly express it as such.  As far as the semantics go I would disagree and say that any integer is not a fraction.  Any integer can be written as a fraction but until you write it in that format its an integer.  Just like you do not say 10/5 is an integer but call it a fraction.
Also, I see a lot of people mentioning that all fractions are rational numbers which is not true.  sqrt(2)/2, while a fraction, is not rational


text:
Q: External interrupts of 8051 in c This code written to display speed in mph by calculating number of external interrupts at INT0 for a particular time delay, works a part ie it just displays 'Read out:'
and then nothing.
I have seen 8051 derivatives page in c51 development tools. It shows me no needed information.
http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.kui0002a/c51_dv_8051deriv.htm
I have not understood why sometimes its written
    void ex0_isr(void) interrupt 0 using 2
Can someone help me understand where am wrong?
Simulation is working fine.
//Calculating speed

 #include <reg51.h>
 #include <string.h>

 void read(unsigned int q);
 void delay(void);
 void delay1(unsigned long int time);
 void SerInit();
 void SerTx(unsigned char x);
 void SerTx_str(unsigned char msg[]);

 unsigned char msg[]="Speed=  ";
 unsigned char buffer[12];
 sbit in_port=P3^2;
 sbit EDGT=TCON^0;
 unsigned char volatile count;
 unsigned int q;

  void ex0_isr(void) interrupt 0
  {
    count++;
  }

  void timer0(void) interrupt 1
  {
     TR0=0;
  {

 void main()
  {

    SerInit();                 //serial initialisation
    SerTx_str("Read out:");    //send string to hyperterminal
    SerTx('\n');
    delay1(20);                //delay using loop
    SerTx('\r');
    in_port=1;             //input port pin
    EDGT=1;                //make IT0 =1 an edge triggered
    while(1)
    {
      count=0;             //initialize count
      IE=IE|0x81;          //enable global and INT0
      delay();             //delay using timers for a time to measure  count
      SerTx_str("Dbg");   //check
      IE=IE&0xFE;          //disable INT0
      q=count;
      read(q);             //function called for ASCII conversion
      SerTx_str(msg);      //send message to terminal
      SerTx_str(buffer);   // send count to terminal
      SerTx('\n');
      delay1(2000);
      SerTx('\r');
    }
  }

 void read( unsigned int q)
  {
    unsigned int d1,d2,d3;
    d1=q%10;
    q=q/10;
    d2=q%10;
    d3=q/10;

    buffer[0]=d3+'0';
    buffer[1]=d2+'0';
    buffer[2]=d1+'0';
  }

  void delay(void)
  {
    unsigned int i;
    for(i=0;i<45;i++)
    {
        TMOD=0x01;      //Timer 0, mode1(16 bit)
        TL0=0xFD;       //load TL0
        TH0=0x4B;       //load TH0
        IE=IE|0x02;     //enable Timer 0 interrupt
        TR0=1;          //turn on Timer 0
       do
        {
         q=count;
        }
       while(TF0==0);

    //if there's overflow ie, TF=1, goto interrupt 1
    //
    //> TMOD=0x01;
      >  TL0=0xFD;
      >  TH0=0x4B;
      >  TR0=1;
      >  while(TF==0);
      >   TR0=0;
      >   TF0=0;  // previous code

    }
  }

A: My guess is that by doing:
IE=0x81;

You are accidentally disabling the timer interrupts, which means that your delay() function never returns. I suspect you probably want to do something like this instead:
IE = IE | 0x01;          // enable INT0
delay();                 // delay using timers for a time to measure  count
IE = IE & 0xFE;          // disable INT0


text:
Q: TypeError: 'int' object is not subscriptable in dataframe.iterrows I am trying to loop over a dataframe like the following:
for row, index in split[0].iterrows():
        kitname = row['kit_name'][0]
        print(kitname)

where split is a list of dataframes
split[0] :

  kit_name          kit_info         part_name part_number
0  KIT0001  Standard FLC Kit  Standard FLC Kit           0
1  KIT0001  Standard FLC Kit  Standard FLC Kit           0
2  KIT0001  Standard FLC Kit  Standard FLC Kit           0

but the following error is coming:
TypeError: 'int' object is not subscriptable

I am using the same code in a different script and it's working fine there

A: Problem is you swap index and row variables, so row are integers so select ['kit_name'] failed:
for row, index in split[0].iterrows():
    kitname = row['kit_name'][0]
    print(kitname)

Need:
for index, row in split[0].iterrows():
    kitname = row['kit_name'][0]
    print(kitname)


text:
Q: QGIS Python SyntaxError file=sys.stderr) File "C:\OSGeo4W64\apps\Python37\lib\site.py", line 177 I am executing a .py file from a windows .bat file for doing a QGIS Desktop 3.8.3 geoprocessing task.
I am using the following .bat file :
@echo off
call C:\OSGeo4W64\bin\o4w_env.bat
REM Change OSGEO4W_ROOT to point to the base install folder
set QGIS_PREFIX_PATH=C:\OSGeo4W64\apps\qgis
REM Gdal Setup
set GDAL_DATA=C:\OSGeo4W64\share\gdal\
REM Python Setup
set PATH=C:\OSGeo4W64\bin;C:\OSGeo4W64\apps\qgis\bin;%PATH%
SET PYTHONHOME=C:\OSGeo4W64\apps\Python37
set PYTHONPATH=C:\OSGeo4W64\apps\qgis\python;%PYTHONPATH%

REM Launch python job
python C:/Task/Task.py
pause

When I execute this Task.bat in C:/Task/, I am getting the following error.
  File "C:\OSGeo4W64\apps\Python37\lib\site.py", line 177
    file=sys.stderr)
        ^
SyntaxError: invalid syntax
Press any key to continue . . .

There are 2 python files namely Python27 and Python37 in C:\OSGeo4W64\apps\ .
The python-core.bat file in C:\OSGeo4W64\etc\ini\ is :
SET PYTHONHOME=%OSGEO4W_ROOT%\apps\Python37
PATH %OSGEO4W_ROOT%\apps\Python37\Scripts;%PATH%

When I open OSGeo4W.bat in C:\OSGeo4W64\ and type 'python', it is showing me SyntaxError and when I type 'python3', it is showing the version of python as given below.
run o-help for a list of available commands
C:\OSGeo4W64>python
  File "C:\OSGEO4~1\apps\Python37\lib\site.py", line 177
    file=sys.stderr)
        ^
SyntaxError: invalid syntax

C:\OSGeo4W64>python3
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

My python code C:/Task/Task.py starts as given below :
from osgeo import ogr, gdal
from gdalconst import *
from qgis.core import *
import qgis.utils, sys
from qgis.gui import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QFileInfo
app = QApplication([])
QgsApplication.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)
QgsApplication.initQgis()
sys.path.append('C:/OSGeo4W64/apps/qgis/python/plugins')
import processing
from processing.core.Processing import Processing
Processing.initialize()
from processing.tools import *

How can I solve this SyntaxError for executing Task.bat in C:/Task/ ?

A: The solution to this issue is to change python C:/Task/Task.py to python3 C:/Task/Task.py in C:/Task/Task.bat, so that it is using python3 interpreter.


text:
Q: Is this an appropriate proof to show that $n(\gamma,a)=-n(-\gamma,a)$ Given the closed rectifiable curve $\gamma:[0,1]\rightarrow \Bbb C$. we define $-\gamma(t)=\gamma(1-t)$.
I want to prove that $n(\gamma,a)=-n(-\gamma,a).$, where n is the winding number.
Is the following an appropriate proof ? :
I started by using the definition of the winding number
$n(\gamma,a)=\tfrac{1}{2\pi i}\int_{\gamma}\tfrac{dz}{z-a}=\tfrac{1}{2\pi i}\int_0^{2\pi}\tfrac{\gamma'(t)}{\gamma(t)-a}dt=\tfrac{1}{2 \pi i }\int_0^{2\pi}\tfrac{rine^{int}}{re^{int}}dt=n$
(this is obviously circular reasoning though.  I think perhaps the following is proof enough )
$-n(-\gamma,a)=-\tfrac{1}{2\pi i}\int_{-\gamma} \tfrac{dz}{z-a}=\tfrac{-1}{2\pi i}\int_0^{2\pi}\tfrac{-\gamma '(t) dt}{-\gamma(t)-a}$
Now recall that $-\gamma(t)=\gamma(1-t)=a+re^{in}e^{-int}$. So
$-n(-\gamma, a)=\tfrac{-1}{2 \pi i}\int_0^{2\pi}\tfrac{-ne^{in}e^{-int}ri}{re^{in}e^{-int}}dt=\tfrac{n}{2\pi} \int^{2 \pi}_0dt=n$
therefore $n(\gamma,a)=-n(-\gamma,a)=n$
What do you guys think is this is a sufficient proof ?

A: (1) It seems that you only consider the special case $\gamma : [0, 2\pi] \to \mathbb{C},\gamma(t) = a + e^{int}$. But your proof can be adapted to work for any closed piecewise continuously differentiable $\gamma : [a,b] \to \mathbb{C}$. In fact, you have $(-\gamma) = \gamma \circ\iota$, where $\iota : [a,b] \to [a,b], \iota(t) = a + b - t $. Then the chain rule yields $(-\gamma)'(t) = \gamma'(\iota(t))\iota'(t)$.
This shows
$$\int_a^b\tfrac{\gamma'(t)}{\gamma(t)-a}dt = \int_{\iota(a)}^{\iota(b)}\tfrac{\gamma'(\iota(s))}{\gamma(\iota(s))-a}\iota'(s)ds = \int_{b}^{a}\tfrac{(-\gamma)'(s)}{(-\gamma)(s)-a}ds = - \int_{a}^{b}\tfrac{(-\gamma)'(s)}{(-\gamma)(s)-a}ds$$
which immediately implies
$$n(\gamma,a) = - n(-\gamma,a) .$$
(2) You claim that $n(\gamma,a) = - n(-\gamma,a)$ for closed rectifiable curves (which are more general than closed piecewise continuously differentiable curves). This can easily be shown if you write down the definition of $\int_\gamma \tfrac{dz}{z -a}$ for such curves.

A: The proof is acceptable and well written. This is not the place to post such questions.


text:
Q: Should these symbols be italicised? Differentials should not be italicised according to ISO standards
$$ \int f\,dx \Rightarrow \int f\,\mathrm{d}x
$$
But should these symbols be italicised?

*

*Continuous functions: $C(X,Y)$ vs $\mathrm C(X,Y)$

*Imaginary unit: $i$ vs $\mathrm i$

*Lp spaces: $L^p(\mu)$ vs $\mathrm L^p(\mu)$

*Subscripts: $C_c(X)$ vs $C_{\mathrm c}(X)$, $\lVert\cdot\rVert_u$ vs $\lVert\cdot\rVert_{\mathrm u}$

A: Language is determined by actual usage, not by "authorities" (who are generally viewed by linguists as describers, not prescribers).  See, for example, What Is 'Correct' Language, from the Linguistic Society of America.
Technical language is no different in this regard from ordinary language.
From what I've seen, mathematicians, at least in the U.S., tend to use an italicized $d$ in a differential (and this can be seen in the house style in many mathematics journals), whereas engineers and physicists generally use a roman $\mathrm{d}$ (the latter in accordance with what ISO says is the standard).
As for the specific symbols you mentioned, I would look at common usage in the journals that you would like to publish in; also, take geography into account because there are regional differences in typography as well. One final remark: Use your own personal sense of esthetics too.


text:
Q: Empty interior of union of cosets? The following question arises from trying to understand Lemma 1.3(ii) of arXiv:math/0405063.  I believe a particular case of the proof (and in fact I think the proof is essentially equivalent to this claim) is:

Let $G$ be a locally compact group.  Let $C,D$ be cosets (not assumed open, closed etc.) each of which has empty interior.  Then $C\cup D$ also has empty interior.

This is not try in general topology, of course: let $C,D$ be the rational, respectively, irrationals, in $\mathbb R$.  However, I cannot decide if being a coset rules out this sort of example.  Is the claim true, and if so, what is a proof?

A: This is false. Take the (compact abelian) group $G=(\mathbf{Z}/2\mathbf{Z})^\mathbf{N}$ and let $H$ be a dense subgroup of index 2 (there are many, since $G$ has only countably many closed subgroups of index 2 but has $2^c$ subgroups of index $2$, and clearly a subgroup of index 2 is either closed or dense). Then $G=H\cup (G\smallsetminus H)$ and both $H$ and its coset $G\smallsetminus H$ have empty interior.

A: With an additional assumption that there exists an interior point $x\in C\cup D$ such that $x\in C\cap D$, one can prove this fact for any topological group. It doesn't require local compactness.
Note that $e$ is in the interior of $x^{-1}C\cup x^{-1}D$ and both sets are subgroups. Thus, WLOG, $x=e$ and $C$, $D$ are subgroups.
Now pick an open neighbhourhood of $e$ such that $U\subseteq C\cup D$. Pick another open neighbhourhood of $e$ such that $V^2\subseteq U$.
Now an easy algebraic argument shows that $V$ must by a subset of $C$ or $D$. Otherwise, pick $y\in V\setminus D$ and $z\in V\setminus C$. The product $yz$ must be in $U$, so in $C$ or $D$. Both lead to a contradiction.


text:
Q: Loading and releasing UIView dynamically I want to load a view dynamically on click of a button.
Lets say view is 'MyView'
I declared it as
IBOutlet UIView *myView;

and connected it via interface builder from a myView.xib made.
I did not set property and synthesize for this view
Now what i want is to allocate this view a memory on click of a button
so i tried in button pressed method of my viewController
(void) buttonPressed1{
   myView = myView = [[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] objectAtIndex:0];
   myView.frame = CGRectMake(30, 40, 200, 200);
   [self.view addSubview:myView];
}

It was Successfully loaded. :)
Now i want to access this view in other button click..
so i wrote
-(IBAction) buttonPressed2:(id)sender
{
    myView.alpha = 0;
    [myView release];
}

so when i run this ---it works ok
on buttonPressed it adds that view on other click it fades out and releases that view.
But now when i again click on button to add view it says
modifying layer that is being finalized - 0x6807b60

then on clicking button 2 , it crashes...
Basically my requirement is to keep that view in memory only when it is used after it has been used, it should be deallocated..
so is above approach is good one or there is any other way to do it...
and what does that error mean????
! more query is
Here in above case....
Memory to myView is allocated at run time on click of button ????....
As when i am testing this via instrument in xcode, there is no allocations showing in graph on button click...
so please help me out...
Please help..
Thanks in advance

A: When you are releasing view : [myView release]; it is not removed from superview. Moreover : you should not release it as it was created as autoreleased object.
The solution could be next:
(void) buttonPressed1{
  if (myView)
  {
      [myView removeFromSuperview];
  }
  myView = [[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] objectAtIndex:0];
  myView.frame = CGRectMake(30, 40, 200, 200);
  [self.view addSubview:myView];
}
-(IBAction) buttonPressed2:(id)sender
{
    myView.alpha = 0;
    //[myView release];
}


text:
Q: Micromax USB Modem Model MMX 352G not recognized in Ubuntu 10.04 LTS It recognizes my modem as a mass storage device. Can someone provide me step by step instruction on how to get it working?
Browsed through some similar questions, none of the answers made sense, but seems like output of lsusb is important, so here goes
Bus 002 Device 004: ID 1c9e:f000
Bus 002 Device 003: ID 064e:f203 Suyin Corp.
Bus 002 Device 002: ID 8087:0020
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0bda:0158 Realtek Semiconductor Corp. Mass Storage Device
Bus 001 Device 002: ID 8087:0020
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

A: I would highly recommend you to upgrade to 12.04. Ubuntu 10.04 is very old and without any support.12.04 is also LTS
However try the following in 10.04
Don't use memory card in the slot of modem if any.

*

*open synaptic package manager and download these two libraries.

*

*usb-modeswitch

*usb-modeswitch-data

*Press ALT+ F2 and type gconf-editor

*Disable auto mount :
Click on apps folder in left and then navigate to nautilus, double click on preferences directory.
on right hand side panel,uncheck the following options:

*

*media_automount

*media_automount_open

Check this option

*

*media_autorun_never

*Reboot system. You can keep usb stick connected.

Now that you have everything setup, you can create configuration for this USB modem in network connections.


text:
Q: How can i decode UPS maxicode barcode I have a maxicode UPS barcode on an image which I need to decode.

*

*Any known .Net utilities?

*The data AFAIK is internaly encoded, which mean I need some UPS stuff.

Does someone have it? How can I get it?


text:
Q: Is it possible to embed images into emails sent from tsql that will work on gmail? I have a tsql script
SET @body_custom = '<head>
                </head>
                <body>
                <img src="cid:testgif.gif" width="267" height="236" alt="">
                </body>'

EXEC msdb.dbo.sp_send_dbmail
@profile_name = @dsysProfileName
, @recipients = 'email@gmail.com'
, @subject = 'SQl 2008 R2 Email Test'
, @body = @body_custom
, @body_format = 'HTML'
, @file_attachments = 'D:\testgif.gif'

And it attaches a file, and sends it to my email address, but instead of an image i see an empty square. Attachments are properly added. I tried using src="testgif.gif" but it also didn't work. Is there a way to attach an inline image to a message sent to gmail using only tsql?
EDIT: I forgot to mention, adding a link to a https server with the image path does work (the image shows) but I can't use it, it has to be a local imgae

A: Most email clients will block images for a host of security reasons. You may want to consider hosting the required images securely on a public site with a SSL certificate then referencing these via html image tags.


text:
Q: SAT solver set default result(cryptominisat) I'm modeling a problem with SAT and trying to solve it with cryptominisat. I'd like to give my variable a default value if there's no constraint for it.
I went through the manual and set_default_polarity seems like the answer. I tried it out but it doesn't work as I expected. I don't really get the term polarity here. Some googling didn't help me out as I'm not familiar with logic.
So, my questions are:

*

*Would you kindly explain what polarity is or point me to some introductory-level sources?

*Is there an interface in cryptominisat(or in SAT solvers generally) to set default value for logic variables? What is the term for such functionality?
Thanks.

A: cryptominisat --hhelp (note the extra h!) gives the following extended help:
.....
  --polar arg (=auto)                   {true,false,rnd,auto} Selects polarity
                                        mode. 'true' -> selects only positive
                                        polarity when branching. 'false' ->
                                        selects only negative polarity when
                                        brancing. 'auto' -> selects last
                                        polarity used (also called 'caching')
.....

I use --polar=false to let cryptominisat search for solutions with false/0 variables first, because my examples have most solution variables that way.
In the source, this corresponds to solverconf.h:
enum class PolarityMode {
    polarmode_pos
    , polarmode_neg
    , polarmode_rnd
    , polarmode_automatic
};

The respective SolverConf variable is PolarityMode polarity_mode
In main.cpp is shown how to set this configuration property in a program:
if (vm.count("polar")) {
        string mode = vm["polar"].as<string>();

        if (mode == "true") conf.polarity_mode = polarmode_pos;
        else if (mode == "false") conf.polarity_mode = polarmode_neg;
        else if (mode == "rnd") conf.polarity_mode = polarmode_rnd;
        else if (mode == "auto") conf.polarity_mode = polarmode_automatic;
        else throw WrongParam(mode, "unknown polarity-mode");
    }

Other SAT solvers are using terms like phase or sign.
Microsoft Z3 can be parameterized via commandline sat.phase=always_false to try false phase first. See a related question. Actually, my first question on StackOverflow back in 2012.
Clasp is using commandline syntax --sign-def=neg to take false polarity first.


text:
Q: Code Plagiarism: How hard or how easy to detect this? Suppose you want to develop an application, in midst of development you find out that one similar application already exists, highly recognized and used. It's a cross platform application but it's unknown whether this application is open source or not.
However you decide to reverse engineer it without taking care of its license and eventually you succeed in it. And now you are using some portion of it for your application, which in some manner improvement of the application and -being based on same idea and targeting some platforms that the original application also covers- comes into straight competition of it.
Can original developer detect that you plagiarized the original code? If yes how?

A: It sounds like you are performing clean room design. As long as there are no patents involved, carrying out clean room design properly has been found to be legal in courts in the US. In order for this to work, however, you can have no knowledge or access to knowledge of the internal workings of the other system.
I would consult a lawyer or someone with expertise in patent, trademark, and copyright laws, however. They would know more about what you might need to do to claim clean room design and if any other laws are applicable to your situation.

A: If you did not have access to their source, then I would not call it plagarism, since you had no ability to copy them at the code level. Your code might look similar, but it could look very different. That part is a matter of chance. A good example of this is the Mono Project. If you have ever worked with Microsoft on .Net, seen the .Net source, or used a decompiler on the .Net Framework, then you are not allowed to contribute to Mono.
What might want to be concerned about, and what they might be concerned about is if you blatantly ripped off parts of their functionality. This happens all the time, of course, but it also can be a source of litigation.
I could be wrong, but it does seem you are walking a tight rope on some moral grey area. Even if there are no legal implications, I think the old "Don't be evil" slogan might apply here. No, they probably will not be able to tell that you plagarized their code, but are you really ok with that? It sounds like you did not plagarize, but if you were to use any "shadier" techniques such as a decompiler, knowledge of their source, or copying a feature that is patented, then I would be concerned.

A: Well if you use the exact same code (variables, functions names etc) and the original developer reversed engineered it then yes he would. If you change the function names/variables then most likely yes. There are software tools that can compare code and provide a probability that they are a copy of each other.
If you implemented the same algorithm he may still be able to detect if his algorithm is unique or performs in a particular way.
It is just a bad idea to do this.

A: So instead of doing your own work you want to steal that of others and change the looks a bit in the hope noone will notice.
At the very least that's highly unethical, most likely it's illegal as hell. Hopefully is will land you in serious legal trouble, and hopefully (if you did it without the knowledge of your employer) they'll be among those sueing you for every penny you'll ever be worth.


text:
Q: JS file upload validation, but instant in windows window I have a form and did validation in JS, that the form is not send when user sends sth different than .doc/.docx. (CV uploading).
But I want this faster. To get the error instantly when the file is selected, not when the button is submitted. (in windows window).
How to do it? It's standard form:

                                        Your CV
                                        <input required type="file" accept="application/msword" class="form-control" name="cv" id="cv" aria-describedby="name" placeholder="Select a CV file"/>

A: I've just got an answer. Here's the code (isDoc is my own function):
    function onChange(event) {
         var file = $('#file_cv')[0].files[0];
         if ( !isDoc(file.name) ) {
            alert("Please, choose .doc or .docx type.");
            document.getElementById("file_cv").value="";
}
}

Now, it's impossible to submit form without sending proper file.


text:
Q: Getting Same Request.UrlReferrer I have one page Result.aspx.this is main page of my website.
There are many images of proudcts in this pages.
When i click on image of product, it is redirected to DetailResult.aspx
Image Code is here:

    <a href="<%#Eval("DetailsURL")%>">
        <asp:Image runat="server" ID="ImgThumb" Width="115" Height="81" />

Now, On load event of DetailResult.aspx, i am getting runtime error for NullReferenceException(or any).
To handle runtime error, i have configured web.config with CustomErrors tag
CustomErrors Tag Code here:
<customErrors mode="On" defaultRedirect="~/Result.aspx?RunTimeError=1">

</customErrors>

So the runtime error of DetailResult.aspx page redirects to Result.aspx.
In this case, on Result.aspx when i try to get previous page URL using Request.UrlReferrer, i am getting its value "Result.aspx" instead of "DetailResult.aspx"

A: UrlReferrer is an http header sent by your browser. If you click a link on Result.aspx, and you end up on Result.aspx?RunTimeError=1, your browser (not unreasonably) decides that the UrlReferrer should be set to the page that initiated the action. That there was a 302 redirect from DetailResult.aspx is not particularly important.
If you would like to know the page that caused the error, you could configure an errorpage that will append this information to the querystring before redirecting.
Menno


text:
Q: Searching tree-like data I have a tree-like structure in which I need to search data. For example if I have the following object:
{
  rowData: 32,
  children: {
    rowData: 33,
    children: {
      rowData: 2,
      children: {
        rowData: 55,
      },
    },
  },
}

If I search for "2" I would like to end up with this:
{
  rowData: 32,
  children: {
    rowData: 33,
    children: {
      rowData: 2
    },
  },
}

Do you have any ideas how I can achieve this?


text:
Q: Which method is better to store data in database and make one-to-many relationship? I've a problem i'm looking at different methods of storing data in database.. and cant decided which one is better then other.. for example we are making multi user blogging website and want to store data of post and relate it with authors(user) as one to many relationship.

*

*the first way is to make two tables

*

*post:

*

*post_id

*post_title

*post_body

*user_id

*post_timestamp

*user:

*

*user_id

*user_name

*user_email

*user_password

*user_timestamp

*The sec way is to make 3 table

*

*post:

*

*post_id

*post_title

*post_body

*post_timestamp

*user:

*

*user_id

*user_name

*user_email

*user_password

*user_timestamp

*post_user:

*

*post_user_id

*user_id

*post_id

*user_timestamp

so which method is more efficient and professional?

A: One:many -- The id of the "one" is in the "many" table, and indexed.  In your example, user_id would be in the table Posts.
Many:many -- This is an extra table with pairs of ids.  (Example:  Many students taking many classes.)  More discussion:  http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table


text:
Q: How to share Swagger documentation I recently started using Swagger for my documentation but there are few things that are still unclear to me. I created my YAML document and now I would like to be able to share my documentation in a .pdf or HTML/Javascript page with the rest of my team. I can't use SwaggerHub because they don't have private repositories and Swagger Editor doesn't appear to allow to share the panel on the right.
Just to be clear, I would like to be able to get something like:

What am I missing?

A: I'm biased as I work on swaggerhub, but that's what the project is for:
https://swaggerhub.com
From there, you can push your swagger specs automatically to github and also make other users collaborators on the API (or just read-only).

A: We are trying to collaborate with another company but only have the basic four licence Team arrangement. It is a product we are developing so my API has to be private. I am using SwaggerHub but was disappointed to see that users can only see my private APIs if they are "collaborators" and hence covered by a paid licence (you can easily share public APIs on SwaggerHub). I guess this will mean hosting the HTML doco (which you can download from your SwaggerHub API) in my own Cloud-hosted instance of Swagger UI and securing it behind a logon...Open to suggestions!


text:
Q: MQTT connection Timeout in some client browsers  var myhost="some ip";
 var myport="80";
 var websocketclient = {
    'client': null,
    'connect': function ()
    {
        var host =myhost;
        var port = myport;
        clientId = 'clientId-' + randomString(10);
        var keepAlive = 60;
        this.client = new Messaging.Client(host,port, clientId);
        this.client.onConnectionLost = this.onConnectionLost;
        this.client.onMessageArrived = this.onMessageArrived;

        var options = {
                timeout: 30,                       //seconds
                keepAliveInterval: keepAlive,
                onSuccess: this.onConnect,
                onFailure: this.onFail
        };
        if (username.length > 0 && password.length > 0){
            options.userName = username;
            options.password = password;
            this.client.connect(options);
        }

    }};

In some clients browsers mqtt is not connecting. websocket connection is connected.
I'm Using hivemq mqttws31.js file. Please help me.

A: I had fixed this issue. Actual problem is with client avast anti virus. Avast is blocking 80 port.After unblocking 80 port its working.

A: So Change Your port number other than 80 so every user will connect from any browser and no anti virus will block the port.


text:
Q: How to change xml source of svg image in a imageview I Found lots of questions for image changing in imageview with another image but I have different problem.
I have to two svg images in xml format in drawable folder.
I want to toggle between images on click of imageview. Like if image a.xml is there then on click on it image b.xml should be displayed, to do that I have to fetch the current xml image source of imageview nd set it to the other one.
How to do that ?
MainActivity.java :
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
ImageView iv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv = (ImageView) findViewById(R.id.imageView);

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(v == iv){

                    if(/* How to check current current source of imagevie here  */  ){
/* How to set new xml svg source to imagevie here  */
                    }

                }

            }
        });

    }
}

xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    tools:context="com.abcd.MainActivity">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        app:srcCompat="@android:drawable/alert_dark_frame"
        android:src="@drawable/a"
        android:layout_centerHorizontal="true"

        android:id="@+id/imageView"
        android:layout_alignParentTop="true" />

</FrameLayout>

drawable folder containing two svg sources

A: figured out the partial solution because I can set the new svg source to imageview but still can't the current source :
  if(v == iv){

                int k = 10;
                switch (count) {
                    case 1 :

                        iv.setImageResource(R.drawable.a);
                        k = 0 ;
                        break;
                    case 0 :
                        iv.setImageResource(R.drawable.b);
                        k=1 ;
                        break;
                }
                count = k ;

            }


text:
Q: jQuery Mobile Date & Time Input Not Working jquery mobile provides its own way for inputting date and time, which is
<input type = "date" />
<input type = "time" />

This is working fine on a browser and on some phones (android). It brings up the native menu with the slide bar to select times and date. However, on an android tablet, it does not work and the input simply serves as any regular text input.
I tried using the datepicker plugin before but it was very slow...
Is there any way i can fix this issue? Or are there any useful, simple plugins I can use?
Thanks!

A: <script>
  //reset type=date inputs to text
  $( document ).bind( "mobileinit", function(){
    $.mobile.page.prototype.options.degradeInputs.date = true;
  });
</script>


text:
Q: How would i embed a user interface to input various types of cars using and array list instead of the array i have already THIS IS MY CLASS
package javaapplication1;

public class Car {

private String model;
private String reg;
private String colour;
private double litreEngine;

//Default Constructor
public Car() {
    model = null;
    reg = null;
    colour = null;
    litreEngine = -1;
}

public Car(String startModel, String startReg, String startColour, double startLitreEngine) {
    model = startModel;
    reg = startReg;
    colour = startColour;
    litreEngine = startLitreEngine;
}

//Prints out Car attributes

public void print() {
    System.out.println("Model:" + model + "Reg:" + reg + "Colour:" + colour + "litreEngine:" + litreEngine);
}

public String toString() {
   return ("Model:" + model + " Reg: " + reg + " Colour: " + colour + " Litre Engine: " + litreEngine);
}

//Get and set Methods
public String getModel() {
    return model;
}

public String getReg() {
    return reg;
}

public String getColour() {
    return colour;
}

public double getLitreEngine() {
    return litreEngine;
}

public void setModel(String new_model)
{
    model = new_model;
}

public void setReg(String new_Reg)
    {
        reg = new_Reg;
}

public void setnumberOfHoursPerWeek(String new_colour)
{
            colour = new_colour;
}

public void setcompulsory(double new_litreEngine)
{
            litreEngine = new_litreEngine;
}

}

THIS IS MY TEST CLASS
package javaapplication1;

import java.util.Scanner;

public class CarTestApp {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    Car[] values = new Car[4];
    int i = 0;
    String Continue = "Y";
    String Stop = "N";
    String answer = null;

    //Car c = new Car("VW Golf", "01D1234", "Red", 1.6);
    //Car d = new Car("Mazda MX-5", "03WW324", "Olive", 1.6);
    //Car e = new Car();

    // Creates car details from user input.
    do {
        System.out.println("Enter model details: ");
        String model = in.nextLine();

        System.out.println("Enter reg details: ");
        String reg = in.nextLine();

        System.out.println("Enter colour details: ");
        String colour = in.nextLine();

        System.out.println("Enter engine details:(Number) ");
        String line = in.nextLine();
        double litreEngine = Double.parseDouble(line);
        //double litreEngine = in.nextDouble();

        Car one = new Car(model, reg, colour, litreEngine);
        values[i] = one;
        i++;

        if (i < values.length) {
            System.out.println("Do you want to add another car?(Y/N)");
            answer = in.nextLine();
        }
    } while (answer.equalsIgnoreCase(Continue) && i < values.length);

    System.out.println("Thank you for inputting this information");

    System.out.println(values[0]+"\t"+values[1]+"\t"+values[2]+"\t"+values[3]);
}
}

A: I think you need a menu-driven program to interact with user to do different task.
First you would need different method, that will do the job of adding a car. And then you can have a switch-case, that will handle your various case.
public static void main(String args) {

    int choice = 0;
    char redo = 'n';

    do {
        System.out.println("Enter your choice:");
        System.out.println("1. Add a car \n 2. Exit");

        choice = /** Read choice from user **/

        switch (choice) {
              case 1: addCar();
                      System.out.println("Do you want to continue? (Y or N)?");
                      redo = /** read char from user ('y' or 'n') **/
                      break;

              case 2: redo = 'n';
                      break;
        }

    } while (redo == 'Y' || redo == 'y'));
}

public static void addCar() {
    // Add the Car adding logic here
}

Rather than using an Array for storing Cars, you can declare an ArrayList that can increase in size dynamically. And you need to declare it outside your main method as an instance variable.


text:
Q: please help me for this question at projective R-modules if $a$ is a nonzero element of projective $R-module$ $P$  ; prove that:
homorphism $f$ $:$ $P$ $\to$ $R$ is exist where $f(a)$ $\neq$ $0$.

my work :
  proof by contradiction ; suppose $f(a)$ $=$ $0$
  since $P$ is projective $R-module$ then exist homorphism $h$ $:$ $P$ $\to$ $A$
  where if $g$ $:$ $A$ $\to$ $R$ is arbitrary homomorphism then $gh$$=$$f$
  can you help me for I continued my work ?

A: $P$ projective means there is a module $P'$ such that $P\times P'\cong R^n$ for some natural $n$. Let $\phi$ be this isomorphism. Then define $f':P\to R^n$ by $f'(p)=\phi(p,0)$. Because $a \neq 0$ and $f'$ is injective, $f'(a) \neq 0$, and therefore, at least one of the components of $f'(a)$ must be non-zero. Let $\pi_i:R^n\to R$ be projection into this component. Then $f=\pi_i\circ f'$ is the homomorphism you're after.


text:
Q: MS SQL datetime prior than 1/1/1900 Surely there is a way to store a date value prior than 1-1-1900 in a column other than varchar? Or do I really have to break this out, and perform my own datetime library for date differences, sorting, and such?
Yes, I understand how datetime's are actually stored (an integer value from a specific date), but I remember there being another workaround from years ago. It's just slipping me now.

A: Yes the SQL Server DateTime type can store dates from 1 January 1753.

A: smalldatetime vs. datetime!
http://msdn.microsoft.com/en-us/library/ms187819.aspx
http://msdn.microsoft.com/en-us/library/ms182418.aspx
!

A: SQL Server 2008 has the DATE data type which can range from 0001-01-01 through 9999-12-31.
With previous versions, your SOL if you need a date prior to 1753-01-01 (Minimum value for DATETIME).


text:
Q: Passing values(array) from a checkbox in a php page to another php page using jinput I am trying to retrieve the value of checkboxes when selected in a form. I have used the following method to store all the check boxes in an array; using [] after the input name:
<input type="checkbox" class="form-control" name="documents[]" value="<?php echo $this->user->construction; ?>" />Construction of building

And then I store the selected values right after, on submit:
if(isset($_POST['submit'])){//to run PHP script on submit
                                    if(!empty($_POST['documents'])){
                                    // Loop to store and display values of individual checked checkbox.
                                    foreach($_POST['documents'] as $selected){
                                    echo $selected."
";
                                    }
                                    }
                                    }

On the other php page, I try to retrieve the value of the selected checkboxes in the variable call "documents":
$app = JFactory::getApplication();
$documents = $app->input->getVar('documents',array());

But after retrieving the data, the only value returned is = Array.
Any help will be appreciated.

A: I was finally able to get this done on my own:
   $docs = $_POST['documents'];
        foreach ($docs as $documents)
{
        $msg .= "$documents\n"  ;

}

Then I used the variable, $msg to hold the values of the checkbox in the array.

A: To retrieve a JForm post data using Jinput, you can use
$jinput   = JFactory::getApplication()->input;

$formData = new JRegistry($jinput->get('jform', '', 'array'));

$documents= $formData->get('documents','');


text:
Q: OpenCV Mat::data is zero after image operation I have a problem in OpenCV C++.
I read in an image from file and use the threshold-function to get a binary image.
After that I want to access the pixel values of the thresholded image.
PROBLEM:
The Mat::data array of the thresholded image is 0.
I use
threshold(src, img, 220, 255, CV_THRESH_BINARY);
with src and img beig cv::Mat.
After that call in the img::data = " "
Here is my code:
// read image source
Mat src = imread("image.png", CV_LOAD_IMAGE_COLOR);
if(src.empty())
{
    return -1;
}

cvtColor(src,src,CV_RGB2GRAY);

threshold(src, src, 220, 255, CV_THRESH_BINARY );

    int line[1200];
int lineCount = 0;

for(int i=src.rows; i>src.rows/2; i-=10)
{
    uchar* rowi = src.ptr(i-1);

    int columnCount = 0;
    // begin on the left of the image
    for(int j=0; j<src.cols; j++)
    {
        uchar grayscale = src.at<uchar>(rowi[j]);

        // write data to array
        line[columnCount] = grayscale;

        columnCount++;
    }
}

I think the problem might be about cv::Mat with referencing and copying Mat::data:
Thanks for your help!

A: I suppose you have checked that your image.png (after having been converted to grayscale) contains values higher than 220?
You may want to try to perform cvtColor as a non-in-place operation, as it might not properly support in-place conversion (see https://stackoverflow.com/a/15345586/19254). This you would do for example like this:
Mat dst;
cvtColor(src, dst, CV_RGB2GRAY);

... and then do threshold on dst. Alternatively, you could read the image into memory in grayscale mode to begin with (second parameter to imread can be CV_LOAD_IMAGE_GRAYSCALE), in which case the cvtColor call is not necessary.
Between each call, you can imwrite your image to disk in order to find out which step is not working as expected.


text:
Q: How to add dynamic variables in data target for django {% for key,value in config.items %}
     <button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-target='#'{{key}}></button>

          <button type="button" class="close" data-dismiss="modal">×</button>

{{key}}

Some text in the modal.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

{% endfor %}

//I want to call each element by {{key}} so that I can display all the values based on the loop value.Please anyone suggest me how to fix this issue


text:
Q: id field resolution when using JObject.FromObject I have a family of custom Json Converters. They work like this:
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) {
  JObject jo = JObject.FromObject(value);
  // do my own stuff to the JObject here -- basically adding a property. The value of the property depends on the specific converter being used.
  jo.WriteTo(writer, this);
}

The problem with this is that the id field of the JObject is always 1. Not good. So I tried using an inner serializer to get the id field:
private JsonSerializer _InnerSerializer {get;set;}
private JsonSerializer InnerSerializer {
  get {
    if (_InnerSerializer == null) {
      _InnerSerializer = new JsonSerializer();
    }
    return _InnerSerializer;
  }
}

public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) {
  JsonSerializer inner = this.InnerSerializer;
  jo = JObject.FromObject(value, inner);
  //my stuff here
  jo.WriteTo(writer, this);
}

That gives a different id each time, even if it hits the same object twice. What I really want is to use Json's usual id resolution with my custom serialization. How can I do that?

A: Your idea of using an inner serializer will not work as-is.  The id-to-object mapping table is held in a private field JsonSerializerInternalBase._mappings with no way to copy it from the outer serializer to the inner serializer.
As an alternative, you could make a recursive call to serialize using the same serializer, and have the converter disable itself using a thread-static pushdown stack along the lines of Generic method of modifying JSON before being returned to client and JSON.Net throws StackOverflowException when using [JsonConvert()].  You would need to enhance the converters in these examples to manually check for and add the necessary "$id" and "$ref" properties by making use of the JsonSerializer.ReferenceResolver property.
However, since your converters just add properties, a more straightforward solution to your problem might be to create a custom contract resolver that allows types to customize their contract as it is generated via a callback method declared in an attribute applied to the type, for instance:
public class ModifierContractResolver : DefaultContractResolver
{
    // As of 7.0.1, Json.NET suggests using a static instance for "stateless" contract resolvers, for performance reasons.
    // http://www.newtonsoft.com/json/help/html/ContractResolver.htm
    // http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Serialization_DefaultContractResolver__ctor_1.htm
    // "Use the parameterless constructor and cache instances of the contract resolver within your application for optimal performance."
    // See also https://stackoverflow.com/questions/33557737/does-json-net-cache-types-serialization-information
    static ModifierContractResolver instance;

    // Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
    static ModifierContractResolver() { instance = new ModifierContractResolver(); }

    public static ModifierContractResolver Instance { get { return instance; } }

    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        var contract = base.CreateObjectContract(objectType);

        // Apply in reverse order so inherited types are applied after base types.
        foreach (var attr in objectType.GetCustomAttributes<JsonObjectContractModifierAttribute>(true).Reverse())
        {
            var modifier = (JsonObjectContractModifier)Activator.CreateInstance(attr.ContractModifierType, true);
            modifier.ModifyContract(objectType, contract);
        }
        return contract;
    }
}

public abstract class JsonObjectContractModifier
{
    public abstract void ModifyContract(Type objectType, JsonObjectContract contract);
}

[System.AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class JsonObjectContractModifierAttribute : System.Attribute
{
    private readonly Type _contractModifierType;

    public Type ContractModifierType { get { return _contractModifierType; } }

    public JsonObjectContractModifierAttribute(Type contractModifierType)
    {
        if (contractModifierType == null)
        {
            throw new ArgumentNullException("contractModifierType");
        }
        if (!typeof(JsonObjectContractModifier).IsAssignableFrom(contractModifierType))
        {
            throw new ArgumentNullException(string.Format("{0} is not a subtype of {1}", contractModifierType, typeof(JsonObjectContractModifier)));
        }
        this._contractModifierType = contractModifierType;
    }
}

Then, apply it to your types as in the following example:
[JsonObjectContractModifier(typeof(TestContractModifier))]
public class Test
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
}

class TestContractModifier : JsonObjectContractModifier
{
    class EmptyValueProvider : IValueProvider
    {
        // Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
        static EmptyValueProvider() { }

        internal static readonly EmptyValueProvider Instance = new EmptyValueProvider();

        #region IValueProvider Members

        public object GetValue(object target)
        {
            var test = target as Test;
            if (test == null)
                return null;
            return test.A == null && test.B == null && test.C == null;
        }

        public void SetValue(object target, object value)
        {
            var property = target as Test;
            if (property == null)
                return;
            if (value != null && value.GetType() == typeof(bool) && (bool)value == true)
            {
                property.A = property.B = property.C = null;
            }
        }

        #endregion
    }

    public override void ModifyContract(Type objectType, JsonObjectContract contract)
    {
        var jsonProperty = new JsonProperty
        {
            PropertyName = "isEmpty",
            UnderlyingName = "isEmpty",
            PropertyType = typeof(bool?),
            NullValueHandling = NullValueHandling.Ignore,
            Readable = true,
            Writable = true,
            DeclaringType = typeof(Test),
            ValueProvider = EmptyValueProvider.Instance,
        };

        contract.Properties.Add(jsonProperty);
    }
}

And serialize as follows:
var settings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects,  // Or PreserveReferencesHandling.All
    ContractResolver = ModifierContractResolver.Instance,
};

var json = JsonConvert.SerializeObject(root, Formatting.Indented, settings);

This produces the following JSON:
[
  {
    "$id": "1",
    "A": "hello",
    "B": "goodbye",
    "C": "sea",
    "isEmpty": false
  },
  {
    "$ref": "1"
  },
  {
    "$id": "2",
    "A": null,
    "B": null,
    "C": null,
    "isEmpty": true
  },
}

As you can see, both the synthetic "isEmpty" property and reference handling properties are present.  Prototype fiddle.


text:
Q: How can i do a search view search in two different languages? Hello Guys
I am developing a dictionary application where users can search Arabic <-> Turkish. I'm getting the data from firebase, no problem here. In my algorithm, the user's keyboard language is selected when the user presses the search view. If this language is Turkish, the text entered by the user is listed as Turkish in the search view (+recycle view), sends it to the recycle view and is listed. If that language is Arabic, I list it as Arabic. By the way, you can think of the data I listed as key & value. The Turkish equivalent of each Arabic word is on the same line. So far the app is working fine for me because I am using my phone's default keyboard and I can get the keyboard language.
The problem starts here;
I can't get this keyboard language when user uses custom keyboards published in Play Store. I can't list it because I can't get the keyboard language. I opened a thread on Stackoverflow but was told that I can't access the language of these custom keyboards in any way. So, how can I sort by understanding whether the user is searching in Arabic or Turkish, without picking up the keyboard language or in any way asking the user in which language to search? Thanks in advance and good work.

A: You will have to maintain a translation in your server, when user searches in one language the corresponding meaning in other language should also be searched, the corresponding meaning will be stored on the server(or on client).

A: If you can't reliably get the keyboard's locale, that seems like a no-go for what you want to do. But even if someone's using a Turkish keyboard, that doesn't mean they're typing Turkish text, right? Since it basically covers the latin character set - they could even be typing in romanised Arabic! (I don't know how likely that is, but it's possible)
You might want to look into a library that detects languages - from a quick search there are a few, and ML-Kit is a Google library that people seem to recommend for it.
I think whatever you do, you probably want the user to be able to set their input language explicitly - give them the final say (and responsibility for ensuring it's correct!). Similar to how Google Translate does it - you can type and it can guess what language you're using (and it says something like (automatically detected) next to it) but the user gets to explicitly choose

edit since you really want this to be automatic (I'd really recommend giving the user control over this, just in case) could you do something like checking if the characters they've entered are Arabic script?
Doesn't help with romanised Arabic (I don't know if that's really used much at all!) - but if you can assume Arabic uses Arabic script, and Turkish is anything else (or you could do the same with the Turkish characters) then maybe you could take a guess just by comparing their input to a set of potential characters. There might even be a convenient Unicode grouping you can check, but I'm not sure off-hand. Might be worth looking into


text:
Q: How can I pass csv row specific information to my function? I am working on a script to check a csv and get the resolution of the images in the links and it then appends this info into a new csv file. I had it working, but it wasn't including headers. I found a way to add the headers, but now I don't know how to pass my size information for each row to the function when I actually call it.
When I run my script I get an error saying size is not defined (referring to the size = str(width) + " x " + str(height) line int the function def).
Error:
  File "image_resolution_check.py", line 38, in <module>
    lambda row, line_num: row.append(header_of_new_col) if line_num == 1 else row.append(
  File "image_resolution_check.py", line 32, in add_column_in_csv
    transform_row(row, csv_reader.line_num)
  File "image_resolution_check.py", line 39, in <lambda>
    size))
NameError: global name 'size' is not defined

Script:
import requests
from PIL import Image
from io import BytesIO
from csv import reader
from csv import writer

input_file = sys.argv[1]
output_file = str(input_file).replace('.csv', '') + '_Output.csv'
header_of_new_col = 'Resolution'

def get_image_size(url):
    data = requests.get(url).content
    im = Image.open(BytesIO(data))
    return im.size

def add_column_in_csv(input_file, output_file, transform_row):

    with open(input_file, 'r') as read_obj, \
        open(output_file, 'wb') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            if row[1] != 'image_num':
                width, height = get_image_size(row[1])
                size = str(width) + " x " + str(height)
            # Append the default text in the row / list
                #row.append(str(width) + " x " + str(height))
                transform_row(row, csv_reader.line_num)
            # Add the updated row / list to the output file
                csv_writer.writerow(row)

add_column_in_csv(input_file, output_file,
                      lambda row, line_num: row.append(header_of_new_col) if line_num == 1 else row.append(
                          size))

A: The easiest solution would be to add size as another argument for your lambda function.
lambda row, line_num, size: row.append(header_of_new_col) if line_num == 1 else row.append(size)

of course than you'll have to change the call to the function and pass size there a well.
transform_row(row, csv_reader.line_num, size)

But this lambda function starts to get long and complicated, and maybe you'll want to use different function that only gets two argument. So what I'll recommend is extracting the lambda to a named function and performing the size calculation inside that function.
.
.
.

def add_size_to_row(row, line_num):
    if line_num == 1:
        row.append(header_of_new_col)
    else:
        width, height = get_image_size(row[1])
        size = str(width) + " x " + str(height)
        row.append(size)

def add_column_in_csv(input_file, output_file, transform_row):

    with open(input_file, 'r') as read_obj, \
        open(output_file, 'wb') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            if row[1] != 'image_num':
            # Append the default text in the row / list
                #row.append(str(width) + " x " + str(height))
                transform_row(row, csv_reader.line_num)
            # Add the updated row / list to the output file
                csv_writer.writerow(row)

add_column_in_csv(input_file, output_file, add_size_to_row)


text:
Q: FuzzyFinder in vim - prevent duplicate filenames in Windows I'm using the FuzzyFinder plugin for vim (specifically with gvim on Windows). It works great, except for one problem: it has many duplicate filenames.
As far as I can tell, this happens because it's case sensitive to filenames, whereas Windows is not. So when I open a file from someplace that lists the directory as "C:\", and another place that lists it as "c:\", I get two different filenames.
Does anyone know of a way that I can fix this?
Thanks!

A: You should not ask this on SO: first search fuzzyfinder documenation, second create a new issue and let the author fix if nothing from the documentation worked. Have you tried g:fuf_ignoreCase option?


text:
Q: Not Found: /media/media/photos/e.jpg in django I've deployed a project on a web server. In my project everything is working fine but I'm unable to print an image on the profile page. On my local environment everything is working fine but on the deployed version I'm getting the following error: Not Found: /media/media/photos/e.jpg in django.
models.py
class Matr(models.Model):
    photo = models.ImageField(upload_to='media/photos/', null=True,
            blank=True)

settings.py
MIDIA_ROOT=os.path.join(BASE_DIR,'media')
MEDIA_URL='/media/'

urls.py
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
    document_root=settings.MEDIA_ROOT)

profile.html
{% if user.matr.photo %}

{% endif %}

A: Try this
models.py
class Matr(models.Model):
     photo = models.ImageField()

settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')

urls.py
if settings.DEBUG:
     import debug_toolbar
     urlpatterns += [path('__debug__/', include(debug_toolbar.urls))]
     urlpatterns += static(settings.MEDIA_URL,
                      document_root=settings.MEDIA_ROOT)

profile.html

And make sure that after uploading photo, you have that photo in 'media_root' library.


text:
Q: How does declaration, definition and initialization work? I've stated how I understand it and would like to get corrected I've learned about declaration, definition and initialization. I seem to understand but still not so confident about it.
So I assume that declaration is putting (as well as declaring) a date type or a function (or something else perhaps I don't know) in the code and in most cases it's going to be a definition too. Basically everything that takes up memory could be considered both a declaration and a definition.
It could be a challenge making it intentionally of not being a definition. For example, we'd need to put extern specifier to a data type which'd drastically say: it. exists. don't. do. anything. And since functions don't take up memory, they in fact can be declared but not defined, such as void function(). When we open curly braces after the function, then it's officially considered a definition too.
Initialization is used to initialize the first value entered after the data type. So if the value is int thing = 3, the first value will be initialized as 3. But if we decide to reuse the thing variable while leaving the previous value behind and assign a value such as 4 (int thing = 4), then thing will be executed having value of 4.
Did I understand the concept right? It took me quite some time to read how others describe them as, so I'm wondering whether what I stated here is right or wrong.
Thanks for taking your time. I personally do not consider this as a duplicate as I'm reviewing my knowledge.

A: Yes, in simple terms you are correct. The standard draft devotes a page or so to declarations and definitions in par. 6.1. I liked how it described declarations (emphasis by me):

A declaration (Clause 10) may introduce one or more names into a translation unit or redeclare names
introduced by previous declarations.

The standard is vague about the nature of these names (in particular it doesn't mention "objects", "variables" or "types"!) because there is a great variety: Classes, functions, enum declarators, plain old variables, parameters, static class members etc.
The standard is also vague about the nature of this "introduction" because it varies as well. The common denominator is that a declaration gives the compiler enough information about the name to work with it it, although perhaps only in a restricted manner. For example, after the forward declaration of a class (class MyClass;) the compiler knows only that the name designates a type; but that's enough to define pointers to it (because all pointers to objects are created equal). It is not enough though to create an object of that type or call a method: The data and function members are, after all, unknown.
One can probably say that a declaration often specifies the outward properties — enough to use a name in some manner —, while a definition specifies the inner workings, i.e. what happens when it is being used.
For example, probably the most common "pure" declarations are function declarations, typically in headers. They inform the compiler how they can be called and which code must be produced to call them. A function definition, by contrast, specifies what happens when the function is called.
Similarly for a variable declaration vs. definition: *How can it be used vs. what happens when it is being used (which memory is manipulated).
The standard then goes on for half a page to list declarations which are not also definitions; about 10% of that are unknown terms for me (not sure whether that reflects badly on the standard or on me). With variables though, a declaration is, as you said, typically a definition unless it comes with the extern specifier and no initialization.


text:
Q: CodeMirror fill Div and make Div 100% height Probably a solution that has been answered, but with all the wrong answers (aka, answers that do not solve this problem), it is very difficult to sift through to find the correct one.
The issue is this ---  How to make CodeMirror fill 100% of the parent div --- without forcing the rest of the page into 100% height as this causes the following issues :
When using
html, body { height: 100%; }

You are effectively telling the page that the entire height is the view port of the browser for the entire page including all contents.  The problem with this, is that I do not want everything on the page to be constrained to this proportion.  What I would like to do, is have normal access to the page without breaking responsiveness (aka, mobile, etc support), and still have a single div on the page (right panel) have a div that ONLY THAT div is 100% height --- of the space in that div.  I do not want 100% height to overflow into the menu, go underneath/over the menu, etc.  It must stay within the box.

A: Have you tried this attribute :
/* Firefox */
height: -moz-calc(100vh - 190px);
/* WebKit */
height: -webkit-calc(100vh - 190px);
/* Opera */
height: -o-calc(100vh - 190px);
/* Standard */
height: calc(100vh - 190px);

Using calc combined with vh allows you to constrain the size of the element to the visible area.


text:
Q: Android Failure 5(database is locked) issue In my app need to cal several web service in async task and insert large data into different tables in a database with each response, for each table fast insertion iam locking the database by begin and end transactions. the problem is after all the web-services if i try to insert new record the log shows Failure 5(database is locked). I have checked if the database is locked by inTransaction(), isDbLockedByOtherThreads and isDbLockedByCurrentThread. all returned false.
how to solve this.

A: Sqlite does not allow concurrent writes and by default when a write is in progress, attempt to start another transaction will fail with this error. In the C API, there is a function to make it retry repeatedly with short sleeps between instead (set_busy_timeout) for specified time, but I don't see similar API in the Android Java wrapper, so you'll probably have to handle retrying on this error yourself.
Also make sure that you correctly either commit or rollback all transactions (without explicit transactions finish all statements) under all possible error conditions.
The isDbLockedByOtherThreads is returning false probably either because the other transaction finishes before you call it or only start after you do or simply because it does not really know, since I am not aware of any function to do this check on the C level.
There is also similar error that happens if you want to modify a table and have an unfinished statement referring to it, but that is status 6 (table is locked).


text:
Q: How to approve a comment in Drupal when admin is replying to that comment? I want to auto approve a comment when an admin is replying to a particular comment. This feature is available in wordpress.

A: If you know how to write a module you could do that by implementing hook_comment_insert():
function MODULE_comment_insert($comment) {
  global $user;
  //check for the administrators
  if(in_array('administrator', array_values($user->roles))) {
    $comment->status = 1; // 0 for unpublished.
    comment_save($comment);
  }
}


text:
Q: When I use Install-Module on a VM where are the modules being stored? I am working in Windows PowerShell in a VM. I am trying to setup everything so that I can create a Hybrid Runbook. The thing is my VM is not connected to the internet. So I download the module packages from the PowerShell gallery and have to place them in the VM. I was wondering where they should be placed?

A: By default, the modules are located here: C:\Users\user_name\Documents\WindowsPowerShell\Modules.


text:
Q: How to extract a zip file Asynchronously in c# to not block the UI? There doesn't seem to be a method in C# where you can unzip a file using await, so I created a task and I am trying to await that. I get the following error:
Cannot implicitly convert type 'void' to 'System.Threading.Tasks.Task'

When I run this code..
Task taskA = await Task.Run(() => ZipFile.ExtractToDirectory(tempPath + @"\" + ftpFile, pvtdest));

Any thoughts on this would be greatly appreciated! Thank you :)

A: Just remove the Task taskA =, like this:
await Task.Run(() => ZipFile.ExtractToDirectory(tempPath + @"\" + ftpFile, pvtdest));

Once you await a Task, you usually don't need to do anything else. A Task doesn't have a result value, so that's why the compiler is complaining about "void". The await will handle propagating exceptions and continuing the method when your Task.Run is complete, and that should be all you need.

A: Try:
Task.Factory.StartNew(() =>
{
    ZipFile.ExtractToDirectory(tempPath + @"\" + ftpFile, pvtdest)
}

You should include System.Threading.Tasks;


text:
Q: Optaplanner: How to write pickup before delivery constraint using java stream api Can any one help me how to write pick up before delivery constraint using java stream api
screenshot2. screenshot3
rule "pickupBeforeDelivery"
    when
        Visit(visitType == VisitType.PICKUP, $ride : ride, $vehicle : vehicle, $pickupVisitIndex : visitIndex)
        Visit(ride == $ride, visitType == VisitType.DELIVERY, vehicle == $vehicle, visitIndex < $pickupVisitIndex, $deliveryVisitIndex : visitIndex)
    then
        scoreHolder.addHardConstraintMatch(kcontext, - ($pickupVisitIndex - $deliveryVisitIndex));
end

using stream api
  return factory.from(TimeWindowedPlanningVisit.class)
                .filter(timeWindowedPlanningVisit -> timeWindowedPlanningVisit.getVisitType()==VisitType.PICKUP)
                .filter(timeWindowedPlanningVisit -> timeWindowedPlanningVisit.getRide().getDeliveryVisit().getVisitIndex() < timeWindowedPlanningVisit.getVisitIndex() &&
                        timeWindowedPlanningVisit.getVehicle() == timeWindowedPlanningVisit.getRide().deliveryVisit.getVehicle())
                .penalizeLong("pickup before delivery",
                        BendableLongScore.ofSoft(2, 1, 0, 1),
                        x -> (x.getVisitIndex() - x.getRide().getDeliveryVisit().getVisitIndex() ));

A: If you already have a DRL, turning it into a Constraint Stream is fairly straight-forward. Just follow the logic of the rule.
First, you have:
Visit(visitType == VisitType.PICKUP, ...)

This naturally translates to:
factory.from(Visit.class)
    .filter(visit -> visitType == VisitType.PICKUP)

Then, the DRL follows:
Visit(ride == $ride, vehicle == $vehicle, visitIndex < $pickupVisitIndex, ...)

This then has to become a join with several joiners:
.join(Visit.class,
    Joiners.equal(Visit::getRide),
    Joiners.equal(Visit::getVehicle),
    Joiners.greaterThan(Visit::visitIndex))

Of course this second Visit can only be a DELIVERY, so you add another filter:
.filter((pickup, delivery) -> delivery.getVisitType() == VisitType.DELIVERY)

And then finally, all that is left is the consequence. In your case:
.penalize("pickup before delivery",
    BendableLongScore.ofSoft(2, 1, 0, 1), // Your choice.
    (pickup, delivery) -> pickup.getVisitIndex() - delivery.getVisitIndex())

Putting this all together:
factory.from(Visit.class)
    .filter(visit -> visitType == VisitType.PICKUP)
    .join(Visit.class,
        Joiners.equal(Visit::getRide),
        Joiners.equal(Visit::getVehicle),
        Joiners.greaterThan(Visit::visitIndex))
    .filter((pickup, delivery) -> delivery.getVisitType() == VisitType.DELIVERY)
    .penalize("pickup before delivery",
        BendableLongScore.ofSoft(2, 1, 0, 1), // Your choice.
        (pickup, delivery) -> pickup.getVisitIndex() - delivery.getVisitIndex());

But we can do better than that in this case. As you can see, the second filter is only applied after the join is already produced. That is slightly inefficient, as the join will first spend time retrieving all the matching pairs of Visits, only to throw away some of them later. The solution to that is to use a join with a nested stream:
factory.from(Visit.class)
    .filter(visit -> visitType == VisitType.PICKUP)
    .join(
        factory.from(Visit.class)
             .filter(visit -> visit.getVisitType() == VisitType.DELIVERY), // Nested stream.
        Joiners.equal(Visit::getRide),
        Joiners.equal(Visit::getVehicle),
        Joiners.greaterThan(Visit::visitIndex))
    .penalize("pickup before delivery",
        BendableLongScore.ofSoft(2, 1, 0, 1), // Your choice.
        (pickup, delivery) -> pickup.getVisitIndex() - delivery.getVisitIndex());

This way, the nested stream will be filtered first and the join will only happen after that - ensuring that no performance is wasted creating pairs that will not be used.

A: @Lukáš Petrovický
i changed as below
 factory.from(Visit.class)
                .filter(visit -> visit.getVisitType() == VisitType.PICKUP)
                .join(factory.from(Visit.class)
                                .filter(visit -> visit.getVisitType() == VisitType.DELIVERY)) // Nested stream.)
                .filter((pickupVisit, deliveryVisit) -> pickupVisit.getVehicle()==deliveryVisit.getVehicle()
                        && deliveryVisit.getVisitIndex()< pickupVisit.getVisitIndex())
                .penalize("pickup before delivery",
                        BendableLongScore.ofSoft(2, 1, 0, 1), // Your choice.
                        (pickup, delivery) -> pickup.getVisitIndex() - delivery.getVisitIndex());