text:
Q: GraalVM native-image with spring boot postgresql just won't build I am currently experimenting with the GraalVM native-image tool. The goal is to run a spring boot webapp in postgresql.
My project compiles with mvn clean package and the .JAR runs like a charm with docker-postgresql, yet I am unable to build a native-image out of this.
I found this neat compile script from Josh Long from Spring tips which helped a lot with the configuration in previous projects. So far, I have no clue why the native-image wont build since its just throwing a StringIndexOutOfBoundsException. I have another project with h2 and jpa where it does just that with exactly the same parameters.
Hoping for some suggestions where to change the config or experiences and ofc solutions.
I am currently using GraalVM Version 20.1.0 (Java Version 1.8.0_252) as JDK.
Below is the stacktrace and the sample project. I also uploaded the terminal output of ./compile.sh here https://file.io/HXudRpH80dDz because its too long if that helps.
Fatal error:java.lang.StringIndexOutOfBoundsException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:598)
    at java.util.concurrent.ForkJoinTask.get(ForkJoinTask.java:1005)
    at com.oracle.svm.hosted.NativeImageGenerator.run(NativeImageGenerator.java:463)
    at com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:359)
    at com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:518)
    at com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:117)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at org.springframework.graalvm.type.TypeSystem.resolve(TypeSystem.java:208)
    at org.springframework.graalvm.type.Method.getReturnType(Method.java:199)
    at org.springframework.graalvm.type.Type.collectAtMappingMarkedReturnTypes(Type.java:1655)
    at org.springframework.graalvm.support.ResourcesHandler.processResponseBodyComponent(ResourcesHandler.java:428)
    at org.springframework.graalvm.support.ResourcesHandler.processSpringComponents(ResourcesHandler.java:310)
    at org.springframework.graalvm.support.ResourcesHandler.processExistingOrSynthesizedSpringComponentsFiles(ResourcesHandler.java:177)
    at org.springframework.graalvm.support.ResourcesHandler.register(ResourcesHandler.java:124)
    at org.springframework.graalvm.support.SpringFeature.beforeAnalysis(SpringFeature.java:78)
    at com.oracle.svm.hosted.NativeImageGenerator.lambda$runPointsToAnalysis$7(NativeImageGenerator.java:679)
    at com.oracle.svm.hosted.FeatureHandler.forEachFeature(FeatureHandler.java:70)
    at com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:679)
    at com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:538)
    at com.oracle.svm.hosted.NativeImageGenerator.lambda$run$0(NativeImageGenerator.java:451)
    at java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1386)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Error: Image build request failed with exit status 1
com.oracle.svm.driver.NativeImage$NativeImageError: Image build request failed with exit status 1
    at com.oracle.svm.driver.NativeImage.showError(NativeImage.java:1541)
    at com.oracle.svm.driver.NativeImage.build(NativeImage.java:1299)
    at com.oracle.svm.driver.NativeImage.performBuild(NativeImage.java:1260)
    at com.oracle.svm.driver.NativeImage.main(NativeImage.java:1219)

real    0m36,107s
user    1m0,314s
sys 0m2,100s

compile.sh
#!/usr/bin/env bash

ARTIFACT=${1}
MAINCLASS=${2}
VERSION=${3}

JAR="${ARTIFACT}-${VERSION}.jar"

rm -rf target
mkdir -p target/native-image
mvn package
rm -f $ARTIFACT
cd target/native-image
jar -xvf ../$JAR
cp -R META-INF BOOT-INF/classes

LIBPATH=`find BOOT-INF/lib | tr '\n' ':'`
CP=BOOT-INF/classes:$LIBPATH
GRAALVM_VERSION=`native-image --version`

time native-image \
  --verbose \
  -H:EnableURLProtocols=http \
  -H:+RemoveSaturatedTypeFlows \
  -H:Name=$ARTIFACT \
  -H:+TraceClassInitialization \
  --initialize-at-build-time=org.springframework.util.unit.DataSize \
  -H:+ReportExceptionStackTraces  \
  -Dspring.native.verbose=true \
  -Dspring.native.remove-jmx-support=true \
  -Dspring.native.remove-spel-support=true \
  -Dspring.native.remove-yaml-support=true \
  -cp $CP $MAINCLASS  \
  --no-fallback\
  --allow-incomplete-classpath\
  -Dspring.native.remove-xml-support=true

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>postgres</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for postgresql native-image</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!--  -->
        <dependency>
            <groupId>org.springframework.experimental</groupId>
            <artifactId>spring-graalvm-native</artifactId>
            <version>0.7.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-indexer</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>

            <!--
            <plugin>
                <groupId>org.hibernate.orm.tooling</groupId>
                <artifactId>hibernate-enhance-maven-plugin</artifactId>
                <version>${hibernate.version}</version>
                <executions>
                    <execution>
                        <configuration>
                            <failOnError>true</failOnError>
                            <enableLazyInitialization>true</enableLazyInitialization>
                            <enableDirtyTracking>true</enableDirtyTracking>
                            <enableExtendedEnhancement>false</enableExtendedEnhancement>
                        </configuration>
                        <goals>
                            <goal>enhance</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>

application.properties
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=admin

spring.datasource.initialization-mode=always
spring.datasource.schema=classpath:/schema.sql
spring.datasource.continue-on-error=true

PostgresApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration;

@SpringBootApplication(
        exclude = SpringDataWebAutoConfiguration.class,
        proxyBeanMethods = false
)
public class PostgresApplication {

    public static void main(String[] args) {
        SpringApplication.run(PostgresApplication.class, args);
    }

}

Employee.java
public class Employee {

String employeeId;
String employeeName;
String employeeEmail;
String employeeAddress;

public String getEmployeeEmail() {
    return employeeEmail;
}
public void setEmployeeEmail(String employeeEmail) {
    this.employeeEmail = employeeEmail;
}
public String getEmployeeId() {
    return employeeId;
}
public void setEmployeeId(String employeeId) {
    this.employeeId = employeeId;
}
public String getEmployeeName() {
    return employeeName;
}
public void setEmployeeName(String employeeName) {
    this.employeeName = employeeName;
}
public String getEmployeeAddress() {
    return employeeAddress;
}
public void setEmployeeAddress(String employeeAddress) {
    this.employeeAddress = employeeAddress;
}}

EmployeeRowMapper.java
import java.sql.ResultSet;
import java.sql.SQLException;

import com.example.postgres.entity.Employee;
import org.springframework.jdbc.core.RowMapper;

public class EmployeeRowMapper implements RowMapper<Employee> {

    @Override
    public Employee mapRow(ResultSet rs, int arg1) throws SQLException {
        Employee emp = new Employee();
        emp.setEmployeeId(rs.getString("employeeId"));
        emp.setEmployeeName(rs.getString("employeeName"));
        emp.setEmployeeEmail(rs.getString("employeeEmail"));
        emp.setEmployeeAddress(rs.getString("employeeAddress"));

        return emp;
    }
}

EmployeeDao.java
import com.example.postgres.entity.Employee;

import java.util.List;

public interface EmployeeDao {

    List<Employee> findAll();

    void insertEmployee(Employee emp);

    void updateEmployee(Employee emp);

    void executeUpdateEmployee(Employee emp);

    public void deleteEmployee(Employee emp);
}

EmployeeDaoImpl.java
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.postgres.entity.Employee;
import com.example.postgres.mapper.EmployeeRowMapper;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDaoImpl implements EmployeeDao{

    public EmployeeDaoImpl(NamedParameterJdbcTemplate template) {
        this.template = template;
}
    NamedParameterJdbcTemplate template;

    @Override
    public List<Employee> findAll() {
        return template.query("select * from employee", new EmployeeRowMapper());
    }
    @Override
    public void insertEmployee(Employee emp) {
         final String sql = "insert into employee(employeeId, employeeName , employeeAddress,employeeEmail) values(:employeeId,:employeeName,:employeeEmail,:employeeAddress)";

            KeyHolder holder = new GeneratedKeyHolder();
            SqlParameterSource param = new MapSqlParameterSource()
                    .addValue("employeeId", emp.getEmployeeId())
                    .addValue("employeeName", emp.getEmployeeName())
                    .addValue("employeeEmail", emp.getEmployeeEmail())
                    .addValue("employeeAddress", emp.getEmployeeAddress());
            template.update(sql,param, holder);

    }

    @Override
    public void updateEmployee(Employee emp) {
         final String sql = "update employee set employeeName=:employeeName, employeeAddress=:employeeAddress, employeeEmail=:employeeEmail where employeeId=:employeeId";

            KeyHolder holder = new GeneratedKeyHolder();
            SqlParameterSource param = new MapSqlParameterSource()
                    .addValue("employeeId", emp.getEmployeeId())
                    .addValue("employeeName", emp.getEmployeeName())
                    .addValue("employeeEmail", emp.getEmployeeEmail())
                    .addValue("employeeAddress", emp.getEmployeeAddress());
            template.update(sql,param, holder);

    }

    @Override
    public void executeUpdateEmployee(Employee emp) {
         final String sql = "update employee set employeeName=:employeeName, employeeAddress=:employeeAddress, employeeEmail=:employeeEmail where employeeId=:employeeId";

         Map<String,Object> map=new HashMap<String,Object>();
         map.put("employeeId", emp.getEmployeeId());
         map.put("employeeName", emp.getEmployeeName());
         map.put("employeeEmail", emp.getEmployeeEmail());
         map.put("employeeAddress", emp.getEmployeeAddress());

         template.execute(sql,map,new PreparedStatementCallback<Object>() {
                @Override
                public Object doInPreparedStatement(PreparedStatement ps)
                        throws SQLException, DataAccessException {
                    return ps.executeUpdate();
                }
            });

    }

    @Override
    public void deleteEmployee(Employee emp) {
         final String sql = "delete from employee where employeeId=:employeeId";

         Map<String,Object> map=new HashMap<String,Object>();
         map.put("employeeId", emp.getEmployeeId());

         template.execute(sql,map,new PreparedStatementCallback<Object>() {
                @Override
                public Object doInPreparedStatement(PreparedStatement ps)
                        throws SQLException, DataAccessException {
                    return ps.executeUpdate();
                }
            });
    }
}

EmployeeService.java
import java.util.List;

import com.example.postgres.entity.Employee;

public interface EmployeeService {
    List<Employee> findAll();

    void insertEmployee(Employee emp);

    void updateEmployee(Employee emp);

    void executeUpdateEmployee(Employee emp);

    void deleteEmployee(Employee emp);

}

EmployeeServiceImpl.java
import javax.annotation.Resource;
import java.util.List;

import com.example.postgres.dao.EmployeeDao;
import com.example.postgres.entity.Employee;
import org.springframework.stereotype.Component;

@Component
public class EmployeeServiceImpl implements EmployeeService{
    @Resource
    EmployeeDao employeeDao;
    @Override
    public List<Employee> findAll() {
        return employeeDao.findAll();
    }
    @Override
    public void insertEmployee(Employee emp) {
        employeeDao.insertEmployee(emp);

    }
    @Override
    public void updateEmployee(Employee emp) {
        employeeDao.updateEmployee(emp);

    }
    @Override
    public void executeUpdateEmployee(Employee emp) {
        employeeDao.executeUpdateEmployee(emp);

    }

    @Override
    public void deleteEmployee(Employee emp) {
        employeeDao.deleteEmployee(emp);

    }
}

ApplicationController.java
import java.util.List;

import javax.annotation.Resource;

import com.example.postgres.entity.Employee;
import com.example.postgres.service.EmployeeService;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/postgresApp")
public class ApplicationController {

    @Resource
    EmployeeService employeeService;

    @GetMapping(value = "/employeeList")
    public List<Employee> getEmployees() {
        return employeeService.findAll();

    }

    @PostMapping(value = "/createEmp")
    public void createEmployee(@RequestBody Employee emp) {
         employeeService.insertEmployee(emp);

    }
    @PutMapping(value = "/updateEmp")
    public void updateEmployee(@RequestBody Employee emp) {
         employeeService.updateEmployee(emp);

    }
    @PutMapping(value = "/executeUpdateEmp")
    public void executeUpdateEmployee(@RequestBody Employee emp) {
         employeeService.executeUpdateEmployee(emp);

    }

    @DeleteMapping(value = "/deleteEmpById")
    public void deleteEmployee(@RequestBody Employee emp) {
         employeeService.deleteEmployee(emp);

    }

}


text:
Q: How can I open gthumb maximized? Is there a way to open images with gthumb using the full width and height of the screen? I mean to open them maximized. Now when I click on an image it always opens filling 1/4 of the screen.
When i click on image and open it now, it opens like this:

When I actually want to open gthumb maximized like this:

Now I need to click maximize every time I open an image.

A: If you open gthumb options through its menu, Edit > Preferences, you'll find a tab called "visualization" or something similar (I don't know the exact name, because my installation is not in English).
There, you can chose how to open new images, as you can see in this screenshot:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding Image Function In Context With Matrix I have the following matrix:
mat <- matrix(c(1,1,1,0,0,0,1,0,1), nrow=3, byrow=TRUE)

which is a 3 by 3 matrix.
      [,1] [,2] [,3]
[1,]    1    1    1
[2,]    0    0    0
[3,]    1    0    1

Passing the above matrix to the image function as :
image(mat)

produces something which looks like:

I cannot relate this picture to what I passed to the image function. What just happened?

A: It's essentially rotated 90 degrees counter-clockwise. This is explained in the help file at ?image (emphasis mine):

Notice that image interprets the z matrix as a table of f(x[i], y[j]) values, so that the x axis corresponds to row number and the y axis to column number, with column 1 at the bottom, i.e. a 90 degree counter-clockwise rotation of the conventional printed layout of a matrix.

You can also see fortunes::fortune("image") for a bit of explanation:

"Mathematical conventions are just that, conventions. They differ by field of mathematics. Don't ask us why matrix rows are numbered down but graphs are numbered up the y axis, nor why x comes before y but row before column. But the matrix layout has always seemed illogical to me."
Brian D. Ripley, answering a question why the layouts of print(x) and image(x) are different
R-help, August 2004


text:
Q: Filter one data frame based on other data frame in pandas I have two DataFrames in pandas:
import pandas as pd

df1 = pd.DataFrame({'Name': ["A", "B", "C", "C","D","D","E"],
                   'start': [50, 124, 1, 159, 12, 26,110],
                   'stop': [60, 200, 19, 200, 24, 30,160]})
df2 = pd.DataFrame({'Name': ["B", "C","D","E"],
                   'start': [126, 143, 19, 159],
                   'stop': [129, 220, 27, 200]})

print(df1)

  Name  start  stop
0    A     50    60
1    B    124   200
2    C      1    19
3    C    159   200
4    D     12    24
5    D     26    30
6    E    110   160

print(df2)

  Name  start  stop
0    B    126   129
1    C    143   220
2    D     19    27
3    E    159   200

I want to filter df1 to remove rows based on df2 using the following criteria:

*

*Name should be present in both df1 and df2

*The range from start to stop for a Name overlaps with the range from start to stop for that Name in the other DataFrame

This would give:
  Name  start  stop
0    B    124   200
1    C    159   200
2    D     12    24
3    D     26    30
4    E    110   160

Where:

*

*A has been dropped as there is no A in df2

*B is kept as the start and stop of B in df2 are nested in those of B in df1

*One of the C's of df1 has been dropped as its values didn't overlap with df2, whereas the other was kept as it is nested in the start and stop range of C in df2

*Both D's are kept as both have an overlap with the range of D in df2

*E is kept as its range overlaps with E in df2

Any help would be greatly appreciated!

A: To solve your problem, I applied an SQL-like way that mimics the following query:
SELECT
  df.Name, df.start_x AS start, df.stop_x AS stop
FROM (
  SELECT
    df1.Name, df1.start AS start_x, df1.stop AS stop_x,
              df2.start AS start_y, df2.stop AS stop_y
    FROM df1
    INNER JOIN df2
      ON df1.Name = df2.Name
) AS df
WHERE (df.stop_y >= df.start_x) AND (df.stop_x >= df.start_y)

This query has been converted to the following code fragment that uses the pandas.merge method. Note that you must use parentheses in the expression (df.stop_y> = df.start_x) & (df.stop_x> = df.start_y). Without them, the code throws the exception

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

import pandas as pd

df1 = pd.DataFrame({'Name': ["A", "B", "C", "C","D","D","E"],
                   'start': [50, 124, 1, 159, 12, 26,110],
                   'stop': [60, 200, 19, 200, 24, 30,160]})
df2 = pd.DataFrame({'Name': ["B", "C","D","E"],
                   'start': [126, 143, 19, 159],
                   'stop': [129, 220, 27, 200]})
df = pd.merge(df1, df2, on=['Name'])
df = df[(df.stop_y >= df.start_x) & (df.stop_x >= df.start_y)]
df.rename(columns={'start_x':'start', 'stop_x':'stop'}, inplace=True)
df.drop(['start_y', 'stop_y'], axis=1, inplace=True)
df.reset_index(drop=True, inplace=True)
print(df)

Output:
  Name  start  stop
0    B    124   200
1    C    159   200
2    D     12    24
3    D     26    30
4    E    110   160

Demo on Repl.it.

A: For anyone who is interested, I figured out a way to do it...
df3=[]
for index1, row1 in df1.iterrows():
    for index2, row2 in df2.iterrows():
        if row1["Name"] == row2["Name"]:
            x = range(row1["start"],row1["stop"])
            x = set(x)
            y = range(row2["start"],row2["stop"])
            if len(x.intersection(y)) > 0:
                df3.append(row1)
df3 = pd.DataFrame(df3).reset_index(drop=True)
print(df3)

  Name  start  stop
0    B    124   200
1    C    159   200
2    D     12    24
3    D     26    30
4    E    110   160

Gets the job done albeit a bit clumsy.
Would be interested if anyone can suggest a less messy way!


text:
Q: Why I have conflicts only if I pull from other git branch? I'm learning Git and I don't understand why if I do git pull from the same branch I don't have conflicts, but if I do git pull origin other-branch I have conflicts.
For example:
case1: I have branch1 with a txt file and I have character "12", then I push it to github, then I modify with "13" on remote. Then I do git pull and everything is fine I don't have conflicts.
case2: I have the same branch1 and a txt file with "12", then I push it to github. After that I create another branch branch2 from branch1, and I modify "12" with "13", then push to remote to branch2. Then I go back to branch1 and do git pull origin branch2. This time I have conflicts like this:
Auto-merging bcde.txt
CONFLICT (content): Merge conflict in bcde.txt
Automatic merge failed; fix conflicts and then commit the result.
[pc@pc-PC bca (master *+|MERGING)]$ cat bcde.txt
<<<<<<< HEAD
12
=======
13

So I have "12" and pull "13" from same branch everything is fine, no conflicts, but if I have "12" and pull "13" from other branch this time I have conflicts. Can somebody explain me why I have conflicts?
Thank you!

A: When you are comparing changes in the same branch git is able to see which one is newer and automatically overwrite the old one. It assumes that the code has just been updated to the newer version. When it comes to separate branches though, git thinks that the second branch could have been worked on in parallel to the first one and sees that a change has been made on the same line. When these two branches are then merged by you doing git pull origin branch2, git is not sure which branch is correct and so creates a conflict. This allows the user to decide which is the correct version.


text:
Q: What is the number of $s-t$ cuts on $n$ vertices? I am trying to know why exactly the number of $s-t$ cuts (cuts that have $s$ in the tail and $t$ in the head) is $2^{n-2}$?
I tried to assume that $s$ has to be on the first set and $t$ has to be in the second set:
$=<\{s,.... \},\{t,.... \}>$
Then since the order is relevant, so we have to use permutation. And we have to fix $s$ and $t$, so could you please tell me to proceed from here to get the final answer $2^{n-2}$?

A: For each of the $n-2$ vertices other than $s$ and $t$, you have a choice between $2$ options: put the vertex in the first set or the second set. These choices are independent, giving $2^{n-2}$ total outcomes.


text:
Q: jQueryMobile Checkbox fires change event for entire controlgroup I have a set of checkboxes setup in a series of div fieldcontain + fieldset controlgroups. They are grouped by topic with 12 main topics and 2-5 sub-topic under each.
When I "change" a checkbox, it fires the change event for the entire controlgroup. If I remove the control group fieldset, it fires the change event (when tapped) for the entire list, whether I use input[name="checkbox_name"] or input.checkbox-class.
How do I get the change for just the actual checkbox changed (from unchecked to checked or checked to unchecked)?

A: Assuming you're doing something like this:
$('input:checkbox').change(function ()
{
    // stuff
});

You can prevent the event from bubbling using event.stopPropagation():
$('input:checkbox').change(function (e)
{
    e.stopPropagation();
});

You can stop event bubbing and prevent other event handlers on the same element from running using event.stopImmediatePropagation().

A: Thanks @Matt Ball but I found this did what I needed:
$('input[name="subtopics_chosen"]:checked').live('change',function()
Before I had
$('input[name="subtopics_chosen"]').live('change',function()
I'll keep your StopPropagation tip for another day, though, I did not know about it.


text:
Q: Narrow jquery selection of checkboxes by a class name I want to disable only checkboxes that are checked AND have a specific class.  There are a lot of very similar questions but I couldn't find anything that was able to get this working.
http://jsfiddle.net/silvajeff/snfDM/
In the below example only the second item should be disabled:
  HTML:
  <input type="checkbox" class='boundParent' />
  <input type="checkbox" class='boundParent' checked/>
  <input type="checkbox" class="boundChild" />
  <input type="checkbox" class="boundChild" />

  Javascript:
  $('[input:checked][class*="boundParent"]').prop("disabled", true);

A: $("input.boundParent:checked").prop("disabled", true);

A:   $('input[type="checkbox"][class*="boundParent"]:checked').prop("disabled", true);

OR
$(':checkbox:checked[class="boundParent"]').prop("disabled", true);

OR
$(':checkbox:checked.boundParent').prop("disabled", true);

CHECK FIDDLE

A: $(':checkbox:checked[class*="boundParent"]').prop("disabled", true);

A: $('input[type="checkbox"]').is(":checked").hasClass("boundChild").prop("disableb",true);

A: Use this
$('.runTest').click(function(){
    $('input[class^="bound"]:checked').prop("disabled", true);
});

You can check this here
http://jsfiddle.net/9D8Xw/1/

A: Check this FIDDLE
$('.boundParent:checked').prop("disabled", true);

A: most succinct form i can think of would be
$('input.boundParent[type=checkbox]:checked').prop("disabled", true);

I have a few comments on other answers
// will select radioboxes as well

$("input.boundParent:checked").prop("disabled", true);

// :checkbox is deprecated now

$(':checkbox:checked[class*="boundParent"]').prop("disabled", true);


text:
Q: Why, when I state listorder = m, m turns into listorder When I use this code, for some reason instead of listorder becoming m, m becomes list order. http://pastebin.com/mfLx10e4
When I compile, I tried to print all of m
9
3
[1, 1, 1]
[1, 1, 1]
[2, 1, 1]
[3, 1, 1]
[4, 1, 1]
[5, 1, 1]
[6, 1, 1]
[7, 1, 1]
[7, 1, 1]
[7, 1, 1]
5

But for some reason m is increasing when it should be staying the same.
Any help is appreciated.


text:
Q: How to add a logo on top left of my screen []
Please I am a beginner in flutter and I want to add a logo on top of my screen in the image shown below.
Secondly how do I identify background colors and how do I place the text in middle of the screen. Thank you.
I tried adding a appbar but the position of the logo was in different position and the colors too i was not able to identify the colors.

A: Stack(
        children: [
          Positioned(
            left: 10,
            top: 10,
            child: Image.asset('assets/logo.png'),
          ),
          //Your other widget
        ],
      ),

Stack could be one of the options to achieve that, however you can use Appbar as well to achieve the same.
THe code for the elevated Button
SizedBox(
           width: double.maxFinite,
                                child: ElevatedButton(
                                  child: Text('Button'),
                                  onPressed: null,
                                  style: ButtonStyle(
                                      side: MaterialStateProperty.all(
                                          BorderSide(
                                              width: 2, color: Colors.white)),
                                      backgroundColor:
                                          MaterialStateProperty.all(
                                              Colors.transparent),
                                      padding: MaterialStateProperty.all(
                                          EdgeInsets.all(12)),
                                      textStyle: MaterialStateProperty.all(
                                          TextStyle(fontSize: 30))),
                                ),
                              ),


text:
Q: I have a question about webrtc implementation I have trouble implementation webrtc between androids. I nearly have finished implementation webrtc, but I don't understand situation that the one need to send other device reductant SDP offer.

See above image. I show you my implementation as sequence diagram.
My webrtc implementation must need to send other device (reductant/unnecessary) createOffer.
What did I make a mistake? I want to catch little clue.
In advance, thank you.

A: You were failing to trickle ICE candidates (send them piecemeal to the other peer).
It works the second time because by then, the ICE candidates generated locally so far, have also been stashed in pc.localDescription. So when the peers exchange their updated offer and answer, these contain enough candidates to connect.
Trickle ICE is an optimization, meant to reduce connection time.

A: I found out it.
    public void onIceCandidateReceived(PeerConnection peer, IceCandidate iceCandidate) {
        peer.addIceCandidate(iceCandidate);
...

The above code has a problem. That iceCandidate must send to other peer.
I solved it, however I have a question.
Why did they work on second call?


text:
Q: How to identify which community Users is coming at run time apex We have five communities in our org. We have bunch of common components in ORGS which common among org. Can we identify at run time in apex call is coming from which community.
Let suppose we have comm1, comm2, coom3, comm4 & comm5.
We are trying to implement logic like,
 if( comm1){

}
if( comm2){

}

Thanks

A: I would expected the Apex call Network.getNetworkId() to return an Id that you can then used to query the Network object to e.g. return the community name.
(But watch out in unit tests - this method will return null there. So you will have to use e.g. Test.isRunningTest to add test-only fake code.)


text:
Q: Reference variables undefined when used on devextreme form On a devextreme form, you'll see the added reference variables "#email", "#twitter", and "#phone". I'm trying to pass the value of each input to a function, but these are returning an undefined object.

:(

    Sorry, this feature is not yet implemented. Please subscribe and we will let you know when the feature is complete.

    <dx-form [colCount]="1"
             labelLocation="left">
        <dxi-item #email dataField="Email Address"></dxi-item>
        <dxi-item #twitter dataField="Twitter"></dxi-item>
        <dxi-item #phone dataField="Phone Number"></dxi-item>

    </dx-form>

        <dx-button text="Subscribe"
                   type="success"
                   icon="check"
                   (click)="onSubscribe(email.value, twitter.value, phone.value)">
        </dx-button>

If I use a regular input element, the values are indeed passed as expected to the function:
<input #email placeholder="email">
<input #twitter placeholder="twitter">
<input #phone placeholder="phone number">

The function simply is returning a console message:
onSubscribe(emailAddress: string, twitterHandle: string, phoneNumber: string) {
    console.log(emailAddress, twitterHandle, phoneNumber);
}

How can I use these variable references to pass the input values to the function?

A: dxi-item didn't have the value property. You can define a template which contains an editor with a reference like below:
<dxi-item>
    <dxo-label text="e-mail"></dxo-label>
    <dx-text-box #email [(value)]="data.email"></dx-text-box>
</dxi-item>
...
{{email.value}}


text:
Q: Where/how to get the Mac OSX "login" command To make a long story short, my terminal was not working so a forum said to delete the "login" command in /usr/bin. It worked. Now, a month later, I am trying to install fink, and it is not working because it cannot find the "login" command.
No backup disks (grrr)
The install disk is not working (I hold down "C" and it logs me in anyway)
So, I was wondering if there was somewhere I could download the unix executable or--since mac is not open source, download the source code for the login command and compile it. It would have to work on my mac (10.5.8) so I really do not know where to start.

A: "mac is not open source" is not accurate. Portions of Mac OS X are open source and the source code is available at http://opensource.apple.com. Specifically, login for Mac OS 10.5.8 is available at http://www.opensource.apple.com/source/system_cmds/system_cmds-433.8/login.tproj.
That being said, compiling system components is not really trivial, even with help from DarwinBuild. I would say your best shot is to grab a copy of the installation media. Have you tried contacting Apple (Store) support?


text:
Q: Convert Number to Unicode sign I have to print out the letters from A to Z each for itself. So I tried the following:
for(var i = 65; i < 91; i++) {
     $('#alphabet').append('
' + '%' + i + '
');
}

My idea is to use the decimal numbers of the letters (for example: 65 - A) to easily print them via loop. Is this possible or do I have to use an array?
Best regards.

A: You can use String.fromCharCode to convert a character code to string.

A: For this use (printing letters from A to Z), String.fromCharCode is sufficient; however, the question title specifies Unicode. If you are looking to convert Unicode codes (and if you came here from search, you might), you need to use String.fromCodePoint.
Note, this function is new to ES6/ES2015, and you may need to use a transpiler or polyfill to use it in older browsers.


text:
Q: Leaflet.js - Can I add multiple holes/cutouts inside of a Single Polygon Looking over the documentation for the L.Polygon constructor, it looks like you can pass in multiple arrays of coordinates after the initial array to construct a Polygon, with multiple holes in it.
I tried a few small samples of data with multiple arrays, and the holes were shaded in after the first one was added.  But when one is added, it worked fine.
Coming from MSSQL, the shapes are reported as valid using the geometry::STIsValid function.
Is my data incorrect, or is this not supported at the time?
The documentation would suggest it is supported.  And every example I find on stackoverflow or the general internet only shows single holes.
This is also with the L.Polygon function (not GeoJSON).

A: Looks to work with multiple holes:
var coords = [
  [ // Exterior Ring
    [48.84, 2.3],
    [48.9, 2.3],
    [48.9, 2.4],
    [48.84, 2.4],
    [48.84, 2.3]
  ], // Then holes (interior rings)
  [ // First hole
    [48.85, 2.31],
    [48.89, 2.31],
    [48.89, 2.33],
    [48.85, 2.33],
    [48.85, 2.31]
  ],
  [ // Second hole
    [48.85, 2.34],
    [48.89, 2.34],
    [48.89, 2.35],
    [48.85, 2.35],
    [48.85, 2.34]
  ],
  [ // Third hole
    [48.85, 2.36],
    [48.89, 2.36],
    [48.89, 2.39],
    [48.85, 2.39],
    [48.85, 2.36]
  ]
];

L.polygon(coords).addTo(map);

JSFiddle: http://jsfiddle.net/ve2huzxw/204/


text:
Q: Comparar informações iguais de períodos diferentes da mesma tabela Senhores, preciso comparar dois períodos de informações iguais, saber quem permaneceu e quem saiu de um mês para o outro.
Ex:
-- Nesta Query estou buscando somente dados de novembro
SELECT *
FROM HIST
WHERE DS_PRODUTO like '%Fla%'
AND ST_CONTA_VALIDA = 's'
AND ST_CARTAO_VALIDO <> 'n'
AND DT_MOVIMENTO >= '2022-11-30'

-- Nesta Query estou buscando somente dados de outubro
SELECT *
FROM HIST
WHERE DS_PRODUTO like '%Fla%'
AND ST_CONTA_VALIDA = 's'
AND ST_CARTAO_VALIDO <> 'n'
AND DT_MOVIMENTO >= '2022-10-30'

Eu gostaria de comparar as informações de outubro com as informações de novembro, identificar quem não está mais e quem permanece de um mês para o outro.
Utilizo SQL Server


text:
Q: Making a Sieve of Eratosthenes more efficient & printing values of a boolean array For a class assignment I was asked to write code in Java for the sieve of Eratosthenes and my code is VERY inefficient. It doesn't take long to run but I'm fairly certain there's room for another loop besides listing out everything as I did..
Here's my code:
public class test
{

    public static boolean[] myArray()
    {
        boolean[] myArray = new boolean[100];
        for(int i = 1;i <100; i++)
        {
                if(i % 2 ==0)
                    {
                        myArray[i] = true;
                    }
                if(i % 3 ==0)
                    {
                        myArray[i]= true;
                    }
                if(i % 5 ==0)
                {
                    myArray[i]= true;
                }
            if(i % 7 ==0)
                {
                    myArray[i]= true;
                }
            if(i % 11 ==0)
                {
                    myArray[i]= true;
                }
        }
        myArray[2]=false;
        myArray[3]=false;
        myArray[5]=false;
        myArray[7]=false;
        myArray[11]=false;

        return myArray;
    }
}

Basically what I did was set all elements that are NOT prime numbers to true..
So my main 2 questions are
1. Is there any way I could implement a loop to make the code shorter
2. How do I print off all elements of this array that are true (prime)

A: I hope this helps. The sieve is a long topic anyway:
public class test
{

    public static boolean[] myArray(int MAX)
    {
        boolean[] myArray = new boolean[MAX+1];
        // myArray[i] == false iff i is prime
        for(int i = 2; i*i <= MAX; i++) // optimization: i*i to not check repeated divisors
        {
            if (!myArray[i]) // if i is prime
                for (int j=i+i; j <= MAX; j += i) // mark all its multiples as not prime
                    myArray[j] = true;
        }
        return myArray;
    }

    public static void print(int[] myArray) { // print the array once computed
        for (int i=2; i< myArray.length; ++i)
            if (!myArray[i])
                System.out.println(i+" is prime");
    }
}

P.S.: the code is not tested.

A: What you are doing here is marking all of the multiples of 2, 3, 5, 7, and 11 to true, then setting those numbers themselves to false, but you're doing all of that 100 times.
What you need to do for the Sieve is the following:
Initially, all numbers are "prime so far", until marked composite.

*

*Mark all numbers in the array as true, i.e. "prime so far".

*In your for loop, if that number is still true, it's prime.  Mark all of its multiples, starting at twice that number, false for being composite.  You can use an inner loop for this.

*Else if that number is false, then it's composite and its multiples are already marked composite as well.

*Stop your for loop after iterating through the square root of 100, 10.  This optimization is possible because you're not going to find any more numbers to mark composite.  If a number here is composite and a multiple of a number greater than 10, then there is also a factor less than 10 that already marked that number as composite.


text:
Q: Center component in react Hello I have the following header component :
import React from 'react';
import './style.css';
import SearchBar from './SearchBar';
import logo from '../../assets/logo.png';

export default function Header() {
  return (
    <>

        <SearchBar />

    </>
  );
}

And a search bar component that is imported in Header:
import React from 'react';

export default function SearchBar() {
  return (

      <form className="search-form">
        <input
          type="text"
          className="search-form__input"
          placeholder="Zoeken naar merken of producten..."
        ></input>
      </form>

  );
}

and the css :
.header-top {
  width: 100%;
  height: 30px;
  background: black;
  color: white;
  font-weight: bold;
}

.header {
  width: 100%;
  background: white;
  height: 60px;
  box-shadow: 0px 11px 13px -9px rgba(141, 141, 141, 0.75);
  display: flex;
  align-items: center;
}

.header__logo {
  height: 20px;
  padding-right: 100px;
  object-fit: contain;
}

.search-form__input {
  width: 700px;
  height: 45px;
  border: none;
  background: #f6f6f6;
  padding-left: 20px;
  color: black;
  border-radius: 5px;
}

The produced result is this :

what i want is to center the searchbar inside header. But only searchbar. i would like the logo to just stay separate on the right side. When i add justify-content:center, it centers everything including logo.
How do i achieve this result? Thanks in advance

A: one way of doing it would be wrapping a container inside the component and  you can justify content to center

        <SearchBar />

would be like

           <SearchBar />

in you css you could change things by
.justify-center{ display:flex; justify-content:center;}


text:
Q: ReactJS Webpack bundle.js syntax error for 'class' The following code is generated in bundle.js.
Internet Explorer states there's a syntax error for class and that is correct.
Why is this in my bundle.js and how can I fix this?
let Screen = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_mobx_react__["observer"])
    (_class = class Screen extends __WEBPACK_IMPORTED_MODULE_0_react__["Component"] {
componentDidMount() {
    if (this.componentWillRender) {
        this.componentWillRender(this.props);
        }
    }
}) || _class;

SCRIPT0001: Syntax error
  bundle.js (12470,99)


text:
Q: How to count perpage using crystal language and kemal I have some menu, example:
Dashboard
List Table
Category
Detail

And I want to create Quick Actions dropdown menu with the most viewed.
My jquery:
var mySession = window.sessionStorage, pageCount;
        window.addEventListener('load', function(){
           if(!mySession.getItem("pageCount")){
              mySession.setItem('pageCount', 1);
           } else {
              pageCount = mySession.getItem("pageCount");
              pageCount = parseInt(pageCount) + 1;
              mySession.setItem('pageCount', pageCount );
           }
           console.log('page view count of current browsing session', mySession.getItem("pageCount"));
           var x = pageCount;
           console.log(x)

           $.ajax({
              type: 'POST',
              url: '/dashboard',
              data: {"count":x},
              complete: function(r){
            alert("success");
            }

            });
        });

And my backend :
get "/dashboard" do |env|
render "views/dashboard.ecr"
end

post "/dashboard" do |env|

body = env.params.body
spawn do
data = {
  "page"  => "dashboard",
  "count" => body["count"],
  "user" => "admin",
}

check_page = DB1["page_count"].find_one({"page" => "dashboard"})
if check_page
  DB1["page_count"].update({"page" => "dashboard"},
    {
      "$set" => {"count" => body["count"]},
    })
else
  DB1["page_count"].insert(data)
end
  end
env.redirect "/dashboard"
end

But,this way count all page. I will count page per page every page is click by user. Can help me.

A: I would do it like this:

*

*Opening the page the user make a GET request to the app -> route (for example '/dashboard'), accordingly, we can assume that one request as +1 for dashboard page count.

*In the MongoDB you create collection with two keys: page_name like dashboard_views_count (for store page name) and views (for increment count of views), then you need to learn operator $inc in MongoDB. This will give a simple way to increment counter.

*After, we make middleware for catch requests. It help extract from env page path and write to MongoDB.
In result this will be look at:

*

*User open '/dashboard'

*Middleware catch this request and extract page name from env

*Middleware write page name and +1 into MongoDB

P.S. Instead of Mongo I propose to consider Redis for counter store.


text:
Q: How to pass Controller data value in nestedset custom function in Laravel blade file Find below the controller code and blade file code,
Tested & Working
Controller Code:
$nodes = Category::get()->toTree();

Blade File Code
Returning Value = 6 {{$data->category_id}}

I need to pass this variable value inside the below traverse function of NestedSet Laravel Package
    @php

    $traverse = function ($categories, $prefix = '-') use (&$traverse) {
        foreach ($categories as $category) {
            if($data->category_id==$category->id) { //How to return Category id Here to Compare ($data->category_id Not returning any value here)
                echo $prefix.'
<input type="radio" checked name="parent_id"
                value="'.$category->id.'"> '.$category->name.'

';
            }
        $traverse($category->children, $prefix.'-');
        }
    };

    $traverse($nodes);

    @endphp

Without any modification, this traverse function working well.
So How to deal with it, when I need to pass an additional value to compare from another controller?
Using lazychaser/laravel-nestedset Package for this scenario.

A: Solved Using
use (&$traverse,&$data_cat_id)

Modified as
@php
$data_cat_id = $data->category_id;

    $traverse = function ($categories, $prefix = '-') use (&$traverse,&$data_cat_id) {
        foreach ($categories as $category) {
            if($data_cat_id==$category->id) { //How to return Category id Here to Compare ($data->category_id Not returning any value here)
                echo $prefix.'
<input type="radio" checked name="parent_id"
                value="'.$category->id.'"> '.$category->name.'

';
            }
        $traverse($category->children, $prefix.'-');
        }
    };

    $traverse($nodes);

    @endphp


text:
Q: Decompile Pyc to py fast I need to know if there is any way to transform a pyc file back into py. I tried decomplyle3 and decompyle6 but they didn't work. Also I was looking for a quick solution.
Thanks for your help.


text:
Q: Read latest file grouped by monthYear in directory in pyspark I have multiple files in a directory.
File name are similar to those added in picture 1.

I want to read only latest file for each month from the directory in pyspark as dataframe.
Expected files to be read as shown in picture 2

A: import os
import glob

path = '/your_path/'
form = 'csv'
os.chdir(path)
files_list = glob.glob('*.{}'.format(form))

dic = {}

prefix = files_list[0][:4]
sufix = files_list[0][-4:]

for i in range(0, len(files_list)):

    ym = files_list[i][4:12][:6]
    d = files_list[i][4:12][6:]

    if ym in dic:
        if d > dic[ym]:
            dic[ym] = d
    else:
        dic[ym] = d

files_to_open = [path+prefix+x+y+sufix for (x,y) in dic.items()]

df = spark.read.format(form).option("header", "true").load(files_to_open)


text:
Q: Ubuntu 22.04 Desktop Installer - Stuck on Active Directory page, doesn't like my domain name value? So, I'm installing 22.04 desktop and I get to the "Who Are You" page, fill in username/password/etc on there, and I check the "use Active Directory" checkbox at the bottom of that page and go to this next page, which I fill out the three fields below and click the Test Connection button and get a green checkmark:
everything looks ok at this point.jpg
But then I click the "Continue" button on that page and it highlights my domain name value as shown below and doesn't let me proceed, and the Back button is disabled, so I appear to be stuck:
stuck on this domain page of the installation.jpg
Any idea what is wrong here, because it's not very helpful, no message or hint of any kind indicating WHY it doesn't like my domain name value.
Thanks in advance.
edit: a couple of additional relevant details:

*

*My domain name is nothing crazy, literally just [a-z] characters (length:14 characters), just all lowercase alpha + ".net"

*This linux machine is a VM on an on-prem HP DL380p Gen8 host running ESXi 6.0

*I pre-staged the computer account in AD for this machine, added an entry in DNS Manager for it, and can ping it from the Windows Domain Controller by both ip address and dns name

A: Not sure you ran into the same issue, but this solved it for me:
As I didn't want to use my domain user name andi as local admin user (the first user with sudo rights), I chose admin. Then continued to Domain setup and got stuck like you.
Hence, I tried to install only with local user and join the domain after install. I also chose admin as first local user, but the installer complained: admin is a reserved user!
Then I remembered, I had the same issue with another box before and looked up my notes. There I used ladmin (local) for the first user and then could join the domain in the installer without an issue!
Obviously this is a but in the input validation, when the join domain checkbox is selected in the user config screen.


text:
Q: Trouble with "extends" can be only used once in Django template I originally thought I would use {% extends ["filename.html"] %} to take html I've written in a template and put it into my main file, but since you can only use "extends" once, how can I have it so that my sidebar.html and slider.html are like snippets that can be put into my main html file, which I've called list.html
Here's an image of what things look like now: http://imgur.com/K5XKAcQ
Here's an image of the error: http://imgur.com/Uqs3iQo

A: Use "extends" like referencing a base class.  Multiple-inheritance isn't supported (directly).  To include snippets of code in your content, use "include":
{% extends "layout.html" %}
{% include "sidebar.html" %}
{% include "slider.html" %}

See: https://docs.djangoproject.com/en/dev/ref/templates/builtins/

A: You can use include in the main template
Rather than adding a tag in the sidebar.html, in filename.html, add:
{% include "sidebar.html" %}

A: You can use an include statement. Also, see here.


text:
Q: How can I debug my tests .Net Core 2.0 in VSCode I'm searching a way to debug my tests (mstest) .Net Core 2.0 in VSCode?
I didn't find nothing.
Thanks!

A: Already posted this answer in another thread. Re-posting as I found this thread earlier and thought there was no easy way.
If you are using the latest version of VS Code (I'm using v1.29.0), debugging (a) unit test is in-built feature.
*Make sure you have built the project so that tests appear correctly with all options.

A:
I set this up by creating a small .bat, defining a VS Code task and a launch definition. Details here: How does one debug an MSTest in VSCode?

A: You can't, use Visual Studio Community Edition 2017, it is free. And will run your tests projects.
Visual Code is awesome, but it is not a full fledged software developer IDE, though it seems close sometimes.
It best to open your .NET Core projects in Visual Studio sometimes and sometimes just use Visual Code, just depends on what you are trying to do.


text:
Q: Скачивание изображения из блока с определённым классом Знатоки, нужен хелп. Суть в том, как реализовать, ссылку на сайте, которая будет скачивать изображение из определённого класса. Допустим есть на сайте  и при нажатии, скачивается изображение, которое находится в div с классом .class . Может есть какая нибудь статья на эту тему, буду благодарен, в гугле ничего не нашел((

A: Я знаток))
Можно воспользоваться fetch(), чтоб отправить запрос и полученный результат записать в Blob, потом с помощью window.URL.createObjectURL() создаешь ссылку на загруженный файл в кеше браузера. Потом с помощью document.createElement('a') создаешь элемент  на странице и в атрибут href помещаешь созданный ранее url через createObjectURL(), и потом с помощью click() нажимаешь на него.
Вот я вырезал из своей программки код, должен работать (использовал JQuery):
$('.image_class').unbind().on('click', function(){
        fetch($(this).attr('src')).then(resp => resp.blob()).then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = 'file_name';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
        });
    });

Если ты делаешь для хрома это, то можно воспользоваться chrome.downloads.download():
  $('.image_class').unbind().on('click', function(){
     chrome.downloads.download({
        url: $(this).attr('src'),
        filename: 'filename',
        saveAs: "если нужно скачивать туда куда выбрал пользователь пишешь true, если в дефолтную папку для загрузок то false"
     });
  });


text:
Q: Diagonalizablity and complex conjugates linear algebra proof problem
Let $A \in M_{n \times n}(\Bbb R)$. Let $T_{\Bbb R}:\Bbb R^n \to \Bbb R^n$ and $T_{\Bbb C}:\Bbb C^n \to \Bbb C^n$ be the corresponding linear mapps(defined by $T_{\Bbb R}(x)=Ax$ and $T_{\Bbb R}(v)=Av$ for $x \in \Bbb R^n$ and $v \in \Bbb R^n)$. Assume $T_{\Bbb C}$ is diagonalizable, and let the distinct eigenvalues of $T_{\Bbb C}$ be $\lambda_1,\ldots,\lambda_r,\ \mu_1, \ \bar{\mu_1},\ldots,\mu_s,\ \bar{\mu_s}$,where $\lambda_1,\ldots,\lambda_r\in\Bbb R$ and $\mu_1,\ldots,\mu_s\notin\Bbb R$. For each $j=1,\ldots,s$, prove that $E_{\mu_j} \cap \Bbb R^n=0$ and $\overline{E_{\mu_j}}=E_{\bar{\mu_j}}$.

Definition: Let $T$ be a linear operator on a vector space $V$, and let $\lambda\in\sigma(T)$.  $E_{\lambda}:=\{x \in V:T(x)= \lambda x\}=\ker(T-\lambda I_V)$. The set $E_{\lambda}$ is called the eigenspace of $T$ corresponding to the eigenvalue $\lambda$.
From the context, since $T_C$ is diagonalizable, it is clear that there exists distinct eigenspaces corresponding to distinct eigenvalues. Since they are of complex conjugates, it is clear that $E_{\mu j} \cap \Bbb R^n=0$. I am not sure what does $\overline{E_{\mu_j}}=E_{\bar{\mu_j}}$ want me to do.

A: I guess $\overline{E_{\mu_j}}=\{\bar x:x\in E_{\mu_j}\}$, where $\bar x=\overline{(x_1,\dots,x_n)}=
 (\overline{x_1},\dots, \overline{x_n})$ for each $x=(x_1,\dots,x_n)\in\Bbb C^n$. Let $x=(x_1,\dots,x_n)\in\Bbb C^n$ be any vector. Using that all entries of  $A$ are real, it is easy to check that $T\bar x=\overline{Tx}$. Thus for each $1\le j\le s$ we have $$x\in E_{\overline{\mu_j}}\Leftrightarrow Ax=\overline{\mu_j}x \Leftrightarrow A\bar x=\overline{Ax}=\overline{\overline{\mu_j}x}=\mu_j\bar{x} \Leftrightarrow \bar{x}\in E_{\mu_j} \Leftrightarrow x\in \overline{ E_{\mu_j}}.$$

A: Note that $\mu_i \notin \mathbb R$ means $\mu_i = a + bi$ with $b \neq 0$.  Now if $c \neq 0$ is real then $c\mu_i = ac + bci$ and $bc \neq 0$ so $c\mu_i \notin \mathbb R$.
Let $x \in E_{\mu_i}$, so $Ax = \mu_ix$.  If $x \in \mathbb R^n$ then $A$ having real entries means $Ax \in \mathbb R^n$.  But that means $\mu_ix \in \mathbb R^n$ so the coordinates of $x$, when multiplied by $\mu_i$ are real.  By what we've said above this means the coordinates of $x$ must be $0$.
Now assume again that $x \in E_{\mu_i}$, so $Ax = \mu_ix$.  Conjugating fixes $A$, so conjugating $Ax = \mu_ix$ gives $A\overline x = \overline{\mu_i}\overline x$, i.e. $x \in E_{\overline{\mu_i}}$.  So $Ax = \mu_ix$ if and only if $A\overline x = \overline{\mu_i}\overline x$.  This proves $\overline{E_{\mu_i}} = E_{\overline{\mu_i}}$.
Finally, note that $E_{\mu_i} \cap \mathbb R^n = 0$ actually follows from $\overline{E_{\mu_i}} = E_{\overline{\mu_i}}$.  This is because $E_{\mu_i} \cap \mathbb R^n$ lies in both $E_{\mu_i}$ and $\overline{E_{\mu_i}}$.  But eigenspaces for distinct eigenvalues have trivial intersection.


text:
Q: Update RTC on STM32F4 when flashing the uC Is there a way to update the RTC with computer information when the program is uploaded on the STM32F4 ? For example, the information of date and hour on the computer is: 12h40 11/09/2018, and when I flash the microcontroler with IAR/AC6, then the RTC is set whith these pieces of information ?

A: My idea is to make a script which you run after flashing (I'm not familiar with IAR, but hope it is possible to run something after FLASH) and this script will set over debugging port RTC registers with current time.
If you use ST-Link/V2 hardware for flashing and you have any experience with python, you can use for that pyswd library. is easy, just in python script get actual time and set appropriate registers in connected MCU.

A: You can modify most port registers through SWD (or JTAG) in the same way as flash and RAM addresses.
Maybe some of the budget-class debug adapters lack a scriptable option, but at least the mainstream range of adapters allows you to write values to any address the CPU can reach through the internal buses (AHB, APBx etc.).
If you read the reference manual carefully, you can at least find out the raw addresses (and bit patterns) of the registers you have to assign.
If you are lucky, the software tools of your debug adapter even provide you a feature where you can do this with lots of syntactic sugar - without having to dive into the manuals.

A: IMO easiest way is to modify openOCD TCL script to upload (after flashing) small program which will update the RTC. 15 mins of work

A: As far as I see it, you have two options:

*

*Bake PC time into your firmware. To do this, you could build your firmware with some area of memory, or indeed the Makefile, dedicated for real-time values, which are populated by a script during the build. When the firmware first runs, it would read from these locations and update the RTC. If you went for this approach, your time would always be out by some amount, depending on how long it takes to build and download the firmware to the device.

*Write the PC time on first power-on. To do this, you would need an interface between the PC and the device, and an application running on the PC. The application would be commanded to get the current PC time and send it to the device over the interface (e.g., a serial cable), and the RTC would then be updated. This is a better approach, since device time will be more tightly coupled to PC time, and you could script this also. The downside here is you have to build the interface.

Also, as an aside, consider whether your application actually needs 'real-time'. Many embedded devices can make do with relative time, e.g., milliseconds elapsed since power-on.


text:
Q: Ionic 3 - Angular when import TestBed get Error : afterAll\nUncaught I'm working on an Ionic 3 App and I have a problem when I want to use TestBed class. I use these commands to create the project.
ionic start myApp tabs
npm install karma-cli -g
npm install karma --save-dev
npm install jasmine --save-dev
npm install karma-jasmine --save-dev
npm install @types/jasmine --save-dev
npm install jasmine-core --save-dev
npm install ts-node --save-dev
npm install angular-cli --save-dev

I use karma to create this karma.conf.js :
module.exports = function(config) {
  config.set({
    basePath: '',

    frameworks: ['jasmine'],

    files: [
      'src/**/*Spec.js'
    ],

    exclude: [
    ],

    preprocessors: {
    },

    reporters: ['progress'],

    port: 9876,

    colors: true,

    logLevel: config.LOG_INFO,

    autoWatch: true,

    browsers: ['Chrome'],

    singleRun: false,

    concurrency: Infinity
  })
}

I create the src/app/pages/home/homeSpec.js file with this content :
import { TestBed } from '@angular/core';

describe("some tests", () => {

  it("True", function () {
    expect(true).toEqual(true);
  });

});

I get the following output when I use karma start :
------------------- without TestBed import ----------------
27 02 2018 23:45:55.793:WARN [karma]: No captured browser, open http://localhost:9876/
27 02 2018 23:45:55.807:INFO [karma]: Karma v2.0.0 server started at http://0.0.0.0:9876/
27 02 2018 23:45:55.808:INFO [launcher]: Launching browser Chrome with unlimited concurrency
27 02 2018 23:45:55.812:INFO [launcher]: Starting browser Chrome
27 02 2018 23:45:57.600:INFO [Chrome 64.0.3282 (Mac OS X 10.13.3)]: Connected on socket ysC5F7d28isYt8oAAAAA with id 47800734
Chrome 64.0.3282 (Mac OS X 10.13.3): Executed 1 of 1 SUCCESS (0.002 secs / 0 secs)

------------------- with TestBed import ----------------
27 02 2018 23:46:04.564:INFO [watcher]: Changed file "/Volumes/JedemaKey/ionic_book/Chapitres/ionic/testtest/myApp/src/pages/home/homeSpec.js".
Chrome 64.0.3282 (Mac OS X 10.13.3) ERROR
  {
    "message": "An error was thrown in afterAll\nUncaught SyntaxError: Unexpected token {",
    "str": "An error was thrown in afterAll\nUncaught SyntaxError: Unexpected token {"
  }
Chrome 64.0.3282 (Mac OS X 10.13.3): Executed 0 of 0 ERROR (0.018 secs / 0 secs)

Why I get this error ?
How can I import TestBed class ?
Edit
I get same error il I can to import another class like in the following code :
import { Component } from '@angular/core';
// This line works in .ts module in same directory.

describe("Test de la page informations", () => {

  it("True", function () {
    expect(true).toEqual(true);
  });

});

I get the same error if I give .ts extension to file...
Do you have a solution ?

A: Finnaly, I found solution in this Github page (https://github.com/ionic-team/ionic-unit-testing-example/issues/79). I downgrade jasmine version to 2.99.0 by using this command :
npm install --save-dev jasmine@^2.99.0


text:
Q: Showing $\gamma < \sqrt{1/3}$ without a computer In 1735 Euler gave the value of $\gamma$ as $0.577218.$ The constant is generally defined as the limit of the difference between the harmonic series and $\log n:~\gamma= \lim_{n\to\infty}\sum_{k=1}^{n}\frac{1}{k}-\log n.$ Euler apparently relished this sort of calculation and must have taken quite a few terms to get such a good approximation.
My question is whether without a computer one can now prove that
$$\gamma <  \sqrt{1/3}$$
with at least some savings in terms of the type of work Euler apparently expended? I don't think there's any point in raising the bar to $\gamma < \ln 2\sqrt{\frac{23}{29}} $  because it seems to be the same sort of question.
My own thought was to compare $\frac{1}{2}\int_0^{1/3}\frac{dx}{\sqrt{x}}$ to something like $(-1)\cdot\int_0^\infty e^{-u}\ln u~du$ but I expect there's a better way.

A: We may exploit an integral representation for $\gamma$ and some trivial bounds.
Since:
$$\begin{eqnarray*}\gamma&=&\lim_{n\to +\infty}(H_n-\log n) = \lim_{n\to +\infty}\left(\int_{0}^{1}\frac{x^n-1}{x-1}\,dx-\int_{1}^{n}\frac{dt}{t}\right)\\&=&\lim_{n\to +\infty}\left(\int_{0}^{+\infty}\frac{1-e^{-nx}}{e^x-1}\,dx-\int_{1}^{n}\int_{0}^{+\infty}e^{-tx}\,dx\,dt\right)\\&=&\lim_{n\to +\infty}\left(\int_{0}^{+\infty}\left(\frac{1}{1-e^{-x}}-\frac{1}{x}\right)e^{-x}\,dx+\int_{0}^{+\infty}\left(\frac{1}{x}-\frac{1}{e^x-1}\right)e^{-nx}\,dx\right)\end{eqnarray*}$$
but $$\frac{1}{x}-\frac{1}{e^x-1}\in\left[0,\frac{1}{2}\right]\quad\forall x\in\mathbb{R}^+,$$
the last integral is $O\left(\frac{1}{n}\right)$ and we simply have:
$$\gamma = \int_{0}^{+\infty}\left(\frac{1}{1-e^{-x}}-\frac{1}{x}\right)e^{-x}\,dx.\tag{1}$$
Since $f(x)=\frac{1}{1-e^{-x}}-\frac{1}{x}$ is concave on $\mathbb{R}^+$, for any $x\in\mathbb{R}^+$ we have $f(x)\leq\frac{1}{2}+\frac{x}{12}$, so:
$$\gamma\leq\int_{0}^{+\infty}\left(\frac{1}{2}+\frac{x}{12}\right)e^{-x}\,dx = \frac{7}{12}.$$
This bound is a bit worse than $\gamma\leq\frac{1}{\sqrt{3}}$, but it can be improved by considering further terms of the Taylor series of $f(x)$ around the origin.

A: Well, you need a hand calculator but only to get $\ln(3)$ or $\ln(4)$.
Using Euler's summation formula for $H_n = \sum(1/n)$, and then isolating $\gamma$ on the left side, you have:
$$
\gamma = H_n - \ln (n) -\frac{1}{2n}+\frac{1}{12n^2} - \frac{1}{120n^4} + \frac{\theta}{256n^6}$$
where $0 < \theta < 1$.
One would think you need to go out a ways in the harmonic series to get an excellent approximation to $\gamma$, but with these three asymptotic terms you need only go to $n=3$.
We get $0.5772197 < \gamma < .5772162 < .57735 < \frac{1}{\sqrt{3}}$  for $n=3$.
For $n=4$ we need only to the $n^2$ term to determine that
$$ \gamma < 0.577247$$
and going to the $n^4$ accuracy we have here, we can see that
$$
0.57721475 < \gamma < 0,57721573 < \frac{1}{\sqrt{3}}
$$
And yes, unless my hand arithmetic is wrong, you have an error in your 6-th decimal place of Euler's constant, which should be 5 or 6, not 8.


text:
Q: CollectionFS cfs:dropbox How get url to image after uploading? I published my whole folder with images, but how generate automatically url in my code for each image?

A: Just use url method. From CollectionFs docs

url
Returns the HTTP file URL for the current FS.File.
Specify a store attribute to get the URL for a specific store. If you
  don't specify the store name, the URL will be for the copy in the
  first defined store.

If you use several stores (for example I'm using file store for thumbs and S3 for full images for one collection), then define store or it returns first store url.


text:
Q: How to fix error "reference to entity "orderby" must end with the ';' delimiter"? I tried to give slider to show recent posts from my blog posts. I have placed the below script but getting:

The reference to entity "orderby" must end with the ';' delimiter

Here is my code:
<script>
document.write(" <script src='\"/feeds/posts/default?max-results=5&orderby=published&alt=json-in-script&callback=showrecentposts6\"'><\/script>");
</script>

A: & is a special character in HTML:

Character references must start with a U+0026 AMPERSAND character (&).

Therefore, when you just want &, you should escape it as
&

However, you should not get that error. The parser should tolerate & instead of & when it's not possible to consume a character reference:

Attempt to consume a character reference, with no additional allowed
  character.
If nothing is returned, emit a U+0026 AMPERSAND character (&) token.

It would really be an error in XML:

The ampersand character (&) and the left angle bracket (<) MUST NOT
  appear in their literal form, except when used as markup delimiters,
  or within a comment, a processing instruction, or a CDATA section.

However, you can't use document.write in XML:

If the method was invoked on an XML document, throw an
  InvalidStateError exception and abort these steps.


text:
Q: Extract data from syslog with rsyslog I'm actually working on Syslog Server in CentOS 7.
I would like to create a dynamic file from the user variable on the message part.
So, in my example, if the message part is :
30-Jan-2022 11:50:10 HOSTNAME ... pri=5 confid=01 slotlevel=2 user="A.Smith" domain="lab.test" ...

I want to dynamically create a file (named A.Smith) and put all logs from the user A.Smith in here. And do this for all the others : 400 users.
My rsyslog.conf is currently configured like this :
 $template ChangeFormatLog,"%$day%-%timegenerated:1:3:date-rfc3164%-%$year% %timegenerated:12:19:date-rfc3339% %HOSTNAME% %syslogtag% %msg%\n"

 $templateDynamicFile,"/var/log/syslogclients/$YEAR-$MONTH-$DAY/%HOSTNAME%.log"

 *.* ?DynamicFile;ChangeFormatLog

I don't know what to write in the rsyslog.conf to retrieve this data .. or if it's possible (?)
Someone can help me plz ?

A: What you're trying to achieve is not possible just using rsyslog. This answer is based on the assumption, that you have multiple users on multiple host machines.

*

*Create a script which creates a username.log files for each user.

*Create a script which writes all needed data to username.log file

*Forward all the username.log files to your syslog server

A: The problem is that i have arround 20 computers for arround 400 users.
It's internet station for clients. They can put their ID on a captive portal into Firefox. They share the same account windows.
I just want to create user.log (user = ID put into the captive portal), in my server syslog.
Actually i retrieve my logs like that :
30-Jan-2022 11:50:10 HOSTNAME ... pri=5 confid=01 slotlevel=2 user="A.Smith" domain="lab.test" ..
I guess it's possible with a script who analyzes the frames ..
Dunno how to do this


text:
Q: Python: Elegant solution to check if any substring is in list? Before you close this, please try to understand the question - it's a bit different, but looks like a lot of downvoted questions.
I'm looking for a simple way to check if any substrings of a string is in a list of strings. The input is like 2018_JAN_BGD, and I want to convert the month info in this to a (year-)quarter info. For example Q1 would be January, February and March. So I'm looking for a way to check if any of the substrings in 2018_JAN_BGD contains JAN, FEB or MAR. I could do this by writing 12 (for the whole year) if-else clauses with or's, but I feel like there's a more elegant solution in Python. I'm trying:
def tellQuarter(month):
    Q1 = ('JAN','FEB','MAR')
    Q2 = ('APR','MAY','JUN')
    Q3 = ('JUL','AUG','SEP')
    Q4 = ('OCT','NOV','DEC')
    if any(for mon in Q1 in month):
        return ("Q1")
    if any(for mon in Q2 in month):
        return ("Q2")

This is of course incorrect (invalid syntax), but I can't figure out how to put this correctly. Basically, I want to loop through Q1, and check if any of the strings is a substring of month.
I mean I can do
for mon in Q1:
    if mon in month:
        return "Q1"

but isn't there a more elegant, single-line solution to this?

A: Cheating, but use a dictionary, mapping the months to quarters:
monthsToQuarters = {
    'JAN': 'Q1','FEB': 'Q1','MAR': 'Q1',
    'APR': 'Q2','MAY': 'Q2','JUN': 'Q2',
    'JUL': 'Q3','AUG': 'Q3','SEP': 'Q3',
    'OCT': 'Q4','NOV': 'Q4','DEC': 'Q4'}

giving you:
>>> monthsToQuarters['JAN']
'Q1'

you could strip out the month using something like:
>>> '2018_JAN_BGD'.split('_')[1]
'JAN'

A: Avoid repeating logic with a dict:
QUARTERS = {
    'Q1': ('JAN', 'FEB', 'MAR'),
    'Q2': ('APR', 'MAY', 'JUN'),
    'Q3': ('JUL', 'AUG', 'SEP'),
    'Q4': ('OCT', 'NOV', 'DEC'),
}

def tellQuarter(month):
    for q, months in QUARTERS.items():
        if any(m for m in months if m in month):
            return q
    raise ValueError("String '{}' does not contain a month.".format(month))

print(tellQuarter('2018_JAN_BGD'))
>>> Q1

A: You had a syntax error in your list comprehension
def tellQuarter(month):
        Q1 = ('JAN','FEB','MAR')
        Q2 = ('APR','MAY','JUN')
        Q3 = ('JUL','AUG','SEP')
        Q4 = ('OCT','NOV','DEC')
        if any(mon in month for mon in Q1):
            return ("Q1")
        if any(mon in month for mon in Q2):
            return ("Q2")

print tellQuarter("2018_JAN_BGD")

Output:
Q1


text:
Q: How to get the CPU usage of iPhone/iPad? I saw in A+ monitor, it can show CPU Idle, CPU usage, CPU System. Which API should be used to get the these information? I have searched and I use the getloadavg function, but it can only return the CPU usage. Also it is not correctly for it will always be more than 90%.
Thanks!

A: Most of these can be retrieved using the appropriate sysctl() selectors.


text:
Q: Implications of changing column from not null to nullable in Entity Framework I have to change the username column in my database to nullable, which means everywhere in my code, I now have to check username.HasValue and change references to username to username.Value.  Is there anything I can do to avoid having to change all the references to username to username.Value?

A: Assuming that username is a string you don't have to change the type in your code since it's a reference type anyway which can be null or not null. .HasValue or .Value don't exist on a reference type. Perhaps you have to make checks like if (username != null) or if (!string.IsNullOrEmpty(username)) sometimes but that's it.


text:
Q: SSL Certificate missing from dropdown in SQL Server Configuration Manager I am trying to configure SQL Server 2014 so that I can connect to it remotely using SSL. A valid, wildcard cert is installed on the server, and the cert's domain name (example.com) matches the server's FQDN (test.windows-server-test.example.com).
The problem is that in SQL Server Configuration Manager, the certificate is not listed, so I cannot select it.

That is, I am stuck on step 2.e.2 from this MS tutorial.

A: I want to add this for future folks that may stumble on a similar issue I encountered with SQL 2016 SP2 and failover cluster. The certificate thumbprint added to the registry had to be all upper case.
Hope this helps the next guy.

A: After communication in comments I can suppose that your main problem is the CN part of the certificate which you use. To have successful TLS communication for IIS Server one have no such strong restrictions like SQL Server has.
Microsoft require (see here) that The name of the certificate must be the fully qualified domain name (FQDN) of the computer. It means that the Subject part of the certificate looks like CN = test.widows-server-test.example.com, where test.widows-server-test.example.com is the FQDN of your computer. It's not enough that you use for example CN = *.example.com and Subject Alternative Name, which contains DNS Name=*.example.com and DNS Name=test.widows-server-test.example.com, DNS Name=test1.widows-server-test.example.com, DNS Name=test.widows-server-test2.example.com and so on. Such certificate will be OK for TLS, but SQL Server will discard it. See the article, which describes close problems.
I recommend you to create self-signed certificate with CN equal to FQDN of the SQL Server and to verify that the certificate will be seen by SQL Server Configuration Manager.
UPDATED: I analysed the problem a little more with respect of Process Monitor and found out that two values in Registry are important for SQL Server Configuration Manager: the values Hostname and Domain under the key
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

If I change Domain and Hostname to the values which corresponds CN of the certificate then the certificate will be already displayed in the SQL Server Configuration Manager. It could be not all problems, but it shows that SQL Server required much more as a web server (IIS for example).
UPDATED 2: I examined the problem once more in details and I think I did found the way how one can configure common SSL certificate which you already have (for example free SSL certificated from Let's Encrypt, StartSSL or some other).
It's important to distinguished what do SQL Server Configuration Manager from the configuration required by SQL Server. The Certificate tab of the properties of the Configuration Manager have more hard restrictions as SQL Server. I describe above only the restrictions of SQL Server Configuration Manager, but one can make configuration directly in the Registry to use more common SSL/TLS Certificate by SQL Server. I describe below how one can do this.
What one need to do one can in the Registry under the key like HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL12.SQL2014\MSSQLServer\SuperSocketNetLib, where the part MSSQL12.SQL2014 can be a little different in your case. The SQL Server Configuration Manager help us to set two values in the registry: ForceEncryption and Certificate:

The Certificate value is SHA1 hash which can be found by examining the properties of the certificate:

or extended properties of the certificate, which you see by usage certutil.exe -store My:

One need just copy the "Cert Hash(sha1)" value, remove all spaces and to place as the value of Certificate value in the Registry. After making the settings and restarting SQL Server windows service one will see in file ERRORLOG in C:\Program Files\Microsoft SQL Server\...\MSSQL\Log directory the line like

2016-04-25 21:44:25.89 Server      The certificate [Cert Hash(sha1)
  "C261A7C38759A5AD96AC258B62A308A26DB525AA"] was successfully loaded
  for encryption.

A: Once I followed steps in Updated 2 section of accepted answer, I can't start the SQL Server service, got those errors in Event Viewer:

Unable to load user-specified certificate [Cert Hash(sha1) "thumbprint of certificate"]. The server will not accept a connection. You should verify that the certificate is correctly installed. See "Configuring Certificate for Use by SSL" in Books Online.
TDSSNIClient initialization failed with error 0x80092004, status code 0x80. Reason: Unable to initialize SSL support. Cannot find object or property.
TDSSNIClient initialization failed with error 0x80092004, status code 0x1. Reason: Initialization failed with an infrastructure error. Check for previous errors. Cannot find object or property.

got error in SQL Server error log:

The server could not load the certificate it needs to initiate an SSL connection. It returned the following error: 0x8009030d. Check certificates to make sure they are valid.

googled it and found out a solution:
Make sure the windows account running SQL Server service (NT Service\MSSQLServer in my case) has full permissions to the following folders/register entry:

*

*C:\Program Files\Microsoft SQL Server[Your Sql Server Instance]\MSSQL\

*C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys

*HKLM\System\CurrentControlSet\Services\WinSock2\Parameters

I checked No.1 NT Service\MSSQLSERVER has already had the permission.
I checked No.2, NT Service\MSSQLSERVER has no permission and I added the permission. It popped up an error saying one of files in that folder was denied the operation, but I just ignored it (nothing else I can do)
I didn't check No.3 and tried starting SQL Server, it worked!!

A: I faced similar issue in SSRS, wherein certificate issued by microsoft active directory CA was not visible in the dropdown in SSRS. After lot of searches, trial and error I could fix it by following this link.
https://learn.microsoft.com/en-us/archive/blogs/sqlserverfaq/can-tls-certificate-be-used-for-sql-server-encryption-on-the-wire
Brief of it is as below:
The Subject property of the certificate must indicate that the common name (CN) is the same as the host name or fully qualified domain name (FQDN) of the server computer.
So in our case we suggested to request the Certificate Authority to change the Subject name to ABC-SQLServer.abc.local (FQDN of SQL Server) instead of abc-corp.abc.com
Once this change was done, we loaded certificate again in MMC and now we could see the certificate loaded in SQL Server Configuration Manager!
Hope it helps someone facing same issue!

A: I was still having problems even after following the above.  This is my fix:
in the certificates mmc right click the certificate All tasks->Manage Pricate Keys.  Give the service account full control.  In my case I am using NT Service\MSSQL$

A: SQL Server 2019
I found that the certificate thumbprint had to be entered into the certificate registry key in lower case for Configuration Manager to see it.
SQL Server will read the registry value and use it whether the registry key is in upper or lower case.
But configuration Manager will only display it if it is in lower case

A: I logged on to the server with SQL Server domain account( had to add the account to local admins temporarily) and imported the certificate in personal folder of the SQL Server service account. rebooted the server, and then SQL Server could see the certificate. Hope it helps someone.

A: An additional failure mode is key length - SQL requires a minimum keylength of 2048.  With DH channel disabled.

A: I have also run into an issue copying out of the MMC as detailed in the article here. Using the certutil and copying that into the registry value worked perfectly.

A: My problem was that the Certificate Store was for WebHosting, but to see the certificate in SSRS it must be Personal.

A: USE UPPER CASE for Certificate in Registry editor LOL
Still not shown in config manager but TLS is working for SQL connections.


text:
Q: MongoDB Schema Design - enable atomicity I have a collection based on the following MongoDB schema, this involves eCommerce transactions and I have purposefully used a single document to achieve atomicity for any updates as can be seen below.
I will have the following three use cases in the report.

*

*Do a sum of all the customerTransactions in all the states.

*Do a sum of all the customerTransactions in each state seperately pending/confirmed/available/redeemed.

*Do a sum of all the customerTransactions in a redeemed state , grouping by the dates.

The use cases 1 & 2 are straight forward to me , however for use case #3 , can I do anything more to the schema to make it more easier to achieve.
    {
      "_id":"id",
      "cuid":"CUIDFromCustomerCollection",
      "customerTransactions":{

        {
        "retailer":"www.walmart.com","purchaseAmount":"123.00","cashbackAmount":"12.00","state":"pending","transactionTimestamp":"timestampValue","updateTimestamp":"timestampValue"
        },
        {
          "retailer":"www.walmart.com","purchaseAmount":"123.00","cashbackAmount":"12.00","state":"confirmed","transactionTimestamp":"timestampValue","updateTimestamp":"timestampValue"
        } ,
        {
          "retailer":"www.walmart.com","purchaseAmount":"123.00","cashbackAmount":"12.00","state":"available","transactionTimestamp":"timestampValue","updateTimestamp":"timestampValue"
        } ,
          {
          "retailer":"www.walmart.com","purchaseAmount":"123.00","cashbackAmount":"12.00","state":"redeemed","transactionTimestamp":"timestampValue","updateTimestamp":"timestampValue"
        }

}

A: The design is good for all the three use cases.
Indexing on "customerTransactions.state" will help in optimization.


text:
Q: What does for(int i = 0; a[i]; i++) mean? I have a string a.
What does the condition a[i] in the for loop for(int i = 0; a[i]; i++) mean?

A: The variable i is initialised to 0, then incremented until a[i] is (or converts to) false, i.e. a[i]==0. Thus, i loops over all characters in the string until the first occurence of \0. For the usual null-terminated string, this is equivalent to
for(auto c:a)

A: for(int i = 0; a[i]; i++) has the same meaning as for(int i = 0; a[i] != 0; i++), which means "enter the loop until the element a[i] gets 0; if a is a string, then this means "enter the loop until a[i] points to the string terminating character \0.
Note, however, that C++ offers other ways of iterating through the characters of a string, like, for example, for (auto c : a) { cout << c << endl; }

A: In this case "for(int i = 0; a[i]; i++)", your loop keeps its execution until one of its elements are a null element. Always when you see this expression, it  is always the same meaning that is checking out whether element is or not null, in order to stop the loop.
However that loop has a undefined behavior, because if the index i will arrive at maximum array's size. It's likely you are going to receive a run-time error of that type:
Error for being out of range array size or you are trying to access a null space of memory.
I hope that my answer, it is suitable for your problem..

A: It is searching chars of a string pointer array one by one. However, because it is defined as string in your code, compile time error occurs.


text:
Q: Using the infinitive or past tense for the verb for a future event A recent article in The New Yorker included this phrase: "...forbade him to represent Israel in bridge for an additional 18 months...". I would have written " forbade him from representing Israel". Which is correct, and why?

A: As it's "to forbid to", here to is fine ; it's just a question of language but you can either prevent from.
Concerning "forbid someone [from ?] doing something" and "forbid him to do it", as the restriction is enacted from above - ie. in the normative order - to the subject, on purpose to prohibit the active behavior of this one on something or to do something, the prohibition does not emanate from what is forbidden itself. So you may find "forbid from" doing something but it's not correct. (& for my part, "forbid from" is worst than "prevent to", which is neither correct.)
Expressions of prevention, prohibition, banning, exclusion or stopping actions take gerund-participle complements in PPs headed by from. The verbs are :

*

*ban,

*hinder,

*keep,

*prevent,

*prohibit &

*stop.

I guess to "forbid from" could derive from such verbs but to forbid isn't in that list (cf. Cambridge Grammar, last ed. p. 835 in fine.)
So it is not to "forbid from" (...) but only in correct AmE to forbid to ; however in InE (idianEnglish) I'd catch the sense :)


text:
Q: Build target MyNotificationService: Framework not found I have a React Native app "MyApp" that has a "MyNotificationService" attached (i.e. NotificationService.appex embedded under the Frameworks, Libraries and Embedded Content in Xcode in target "MyApp").
Up until this point everything fine.
Now I want to add another pod to "MyApp" naming pod 'Google-Mobile-Ads-SDK', which does not have anything to do with MyNotificationService. I just want to install it, so I can access the Google-Mobile-Ads-SDK in "MyApp".
My Podfile looks like this
target 'MyApp' do

  use_unimodules!
  config = use_native_modules!
  use_react_native!(
    :path => config[:reactNativePath],
    :hermes_enabled => false
  )

  # Additional Dependencies
  ...
  pod 'Google-Mobile-Ads-SDK'

  target 'MyNotificationService' do
    use_native_modules!
    inherit! :complete
  end

  post_install do |installer|
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings['APPLICATION_EXTENSION_API_ONLY'] = 'NO'
        # deletes each pods deployment target definition and instead uses the definition of the main project
        config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
      end
    end
  end
end

However, after I ran pod install, I tried to build the debug version of MyApp using XCode, but XCode complains:
Build Target MyNotificationService
Link MyNotificationService (arm64)

Directory not found for option '-F/Users/.../Library/Developer/Xcode/DerivedData/MyApp-abcabcabcabcabc/Build/Products/Debug-iphoneos/XCFrameworkIntermediates/GoogleAppMeasurement'

Directory not found for option '-F/Users/.../Library/Developer/Xcode/DerivedData/MyApp-abcabcabcabcabc/Build/Products/Debug-iphoneos/XCFrameworkIntermediates/GoogleMobileAds'

Directory not found for option '-F/Users/.../Library/Developer/Xcode/DerivedData/MyApp-abcabcabcabcabc/Build/Products/Debug-iphoneos/XCFrameworkIntermediates/UserMessagingPlatform'

But MyNotificationService has nothing to do with these Frameworks GoogleAppMeasurement, GoogleMobileAds and UserMessagingPlatform - those belong to the Google-Mobile-Ads-SDK and only the main target MyApp should need them.
How can I tell MyNotificationService that it should not care about these frameworks?

A: Did solve the problem with an abstract target, that has both "MyApp" and "MyNotificationService" as subtargets defined in it. The abstract target is not an actual Xcode target but rather a placeholder or a folder that defines the pods that both the "MyApp" and "MyNotificationService" should both have shared. To get "MyNotificationService" ignore everything related to the 'Google-Mobile-Ads-SDK', the pod 'Google-Mobile-Ads-SDK' is only defined in the subtarget "MyApp".
abstract_target 'Shared' do

  use_unimodules!
  config = use_native_modules!
  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )

  # Additional Dependencies
  ...

  target 'MyApp' do
    # no inherit statement means that target MyApp has all pods from the parent "Shared" accessible
    pod 'Google-Mobile-Ads-SDK'
  end

  target 'MyNotificationService' do
      # no inherit statement means that target MyNotificationService has all pods from the parent "Shared" accessible
    use_native_modules!
  end

  post_install do |installer|
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings['APPLICATION_EXTENSION_API_ONLY'] = 'NO'
        # deletes each pods deployment target definition and instead uses the definition of the main project
        config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
      end
    end
  end
end


text:
Q: Direct calculation gives other result in MATLAB I'm having a weird thing going on in matlab. I tried to calculate the following simple line:
>> -0.5800^3+2*(-0.5800^2)+70*-0.5800+40

ans =

   -1.4679

However, the result differs when I calculate it with an assigned variable (a):
>> a = -0.5800;
>> c = a^3+2*(a^2)+70*a+40

c =

   -0.1223

I overlooked it many times to make sure I did not made a stupid mistake. Am I missing something MATLAB does different in these situations (calculations with variables)? My calculator gives the upper result. Thanks in advance for the clarification!

A:   -0.5800^3+2*(-0.5800^2)+70*-0.5800+40
= -(0.5800^3)+2*(-(0.5800^2))+70*-0.5800+40
= -1.4679

but with a variable it is read as:
  (-0.5800)^3+2*((-0.5800)^2)+70*-0.5800+40
= -0.1223

Watch your parentheses and operator precedence.

A: Hi the problem is due to
(-0.5800^2)

which is calculated as
-(0.5800^2)


text:
Q: Get mailbox creation date with Microsoft Graph API? Is it possible to get mailbox creation date with Microsoft Graph API?
The most convenient approach that I've found is: https://learn.microsoft.com/en-us/graph/api/reportroot-getmailboxusagedetail?view=graph-rest-1.0. But that is not very helpful, since all data is anonymized by default on server side.

A: That property isn't exposed via the Graph outside of the Reporting endpoint but it sounds like you have anonymization turned on in the tenant so it won't be usable. I would suggest using https://learn.microsoft.com/en-us/powershell/module/exchange/get-exomailbox?view=exchange-ps. This is a REST call under the covers but Microsoft don't support you using the API directly.


text:
Q: Live Validation Mutually exclusive fields I am trying to validate two fields using LiveValidation but I can't seem to find anything on it anywhere.
I am trying to make one or the other of the Email and Mobile fields required so that when one is filled in the other does not need to be, but both may be entered.
Here is my code:
<script type="text/javascript">
var Email = new LiveValidation("Email", {validMessage: "", onlyOnBlur: true});
Email.add(Validate.Presence, {failureMessage:"This field is required"});
Email.add(Validate.Format, {pattern: /^[ ]*([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})[ ]*$/i,    failureMessage: "A valid email address is required"});

var mobile = new LiveValidation("mobile", {validMessage: "", onlyOnBlur:    true});mobile.add(Validate.Presence, {failureMessage:"This field is required"});

var discussion = new LiveValidation("discussion", {validMessage: "", onlyOnBlur: true});discussion.add(Validate.Presence, {failureMessage:"This field is required"});
</script>

A: I think you can do it, but you'd have to hack it a bit. With the LiveValidation library, there's no function under the LiveValidation class that returns a constant or boolean indicating that a field is validated. However, you can check that the validation message has been added to the DOM. For instance, say I have the code, ->
var f1 = new LiveValidation('f1');
f1.add( Validate.Presence );

Now, I want to make sure that f1 is validated. To do this, I would get the parent element of field 'f1', check for elements with the class 'LV_valid', and go from there. My code would look something like, ->
function isValidated (field) {
    var element = document.getElementById (field);
    for (var i in element.parentElement.getElementsByClassName ("LV_valid")) {
        ...
    }
}

The problem is that there's no way of identifying if the LV field that you retrieved was the one that corresponded with your field. You might have to write your own validation code or make a modified version of the library. That's all the input I can provide right now, hopefully it's valid.


text:
Q: Align text below a div on regular width intervals I've created an Angular directive in which a user can change certain settings depending on the time of the day. Below is a picture of what I already have:

I'd like to add kind of "ticks" that accurately represent the time on x-axis of the div to show the user what he's doing, like in the picture below:

These would have to be at exact 1/24ths of the div above it. I can set the div width to a fixed number if it helps. I'd also want the key times shown like in the picture. What would be the best way of accomplishing this?

A: I am just going to list in theory what could work, it's up to you to try it out. I would try the following steps (my solutions are not traditional, but could work):

*

*For the ticks, I could try add 24 spaced letter 'l' or capital I (which ever would create a tick with spaces in between, set the line-height and font to the length you want, bold the relevant ticks and then add text-align:justify.

Or for a more traditional approach you could go for a row with 24 columns each of 1/24th width using css, float the columns and add border.

*For the numbers I would add another row div with the number of columns equal to the number of time you want to show-1, the last column having the extra time to show at the right corner.

*I would add each time as a strong element and add position relative to the parent column, and position absolute to the strong element positioning them left -10 or so which makes them appear like above.
Hope this helps.

A: Flexbox will work here..and the upper div can be any size.
Just add a wrapper and let that determine the width.
Codepen Demo

* {
  box-sizing: border-box;
}
.parent {
  display: flex;
  flex-direction: column;
  margin: 1em auto;
  width: 80%;
}
.object {
  width: 100%;
  height: 150px;
  background: pink;
  display: flex;
}

.block {
  width: 25%;
  background: lightblue;
}
.ticks {
  height: 15px;
  display: flex;
  justify-content: space-between;
}
.tick {
  width: 2px;
  height: 100%;
  background: grey;
  position: relative;
}

.tick.major {
  background:red;
  width:2px;
  }
.time {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  font-size: 80%;
}

00:00

06:00

12:00

18:00

00:00

A: I am providing basic idea of how you can achieve your goal

.time_interval,.line{
   width:100%;
  }
  .line div{
    color:#000;
       float: left;
       height: 5px;
       width: 4%;
       text-align:center;
  }
  .line .b{
   font-weight:bold;
   color:red;
  }
  .timer div{
   float: left;
   text-align:center;
   height: 5px;
   width: 4%;
   padding-top:15px
  }

        <title>Test</title>

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

|

00:00

06:00

12:00

18:00

00:00