text:
Q: Django rest framework create-only serializer field I'm have a Django model that serves as a request description. It is created to issue a request by a REST client, serves to record the tasks current status, and record historical requests received by clients.
This model has a few fields that are used to fine-tune and control the requested task (say, a target object and the type of action). Obviously, I'd like the client to control those fields on object creation but not afterwards (you can't change the object once the task started running).
I was hoping for something similar to serializers.ReadOnlyField, so I could have something similar to this:
class TaskSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    task_id = serializers.ReadOnlyField()
    target_object = serializers.CreateOnlyField()

but couldn't find it in the documentation or google.

A: Just to expand on Wim's answer, this is a way to select a different serialiser based on the incoming request method:
class RequestViewSet(viewsets.ModelViewSet):
    serializer_class = RequestModelSerializer
    model = Request

    def get_serializer_class(self):
        serializer_class = self.serializer_class
        if self.request.method == 'POST':
            serializer_class = SerializerWithoutCertainFields
        return serializer_class

A: The answer of @fabio.sussetto put me on the right track. I think my answer is slightly prettier; I don't specify the serializer on the class directly but only in get_serializer_class(). Also, I do not switch it based on the HTTP type (i.e. POST) but rather on the action, update, which I think is more declarative.
class RequestViewSet(viewsets.ModelViewSet):
    model = Request

    def get_serializer_class(self):
        if self.action == 'update':
            return serializer_class = SerializerWithoutCertainFields
        return RequestModelSerializer

A: This can be achieved with one serializer by using to_internal_value method
class TaskSerializer(serializers.ModelSerializer):
    # Field settings here

    def to_internal_value(self, data):
        data = super().to_internal_value(data)
        # Remove target_object if serializer is updating object
        if self.instance:
            data.pop('target_object', None)
        return data

    class Meta:
        model = Task
        fields = ('owner', 'task_id', 'target_object')

A: could also be done with a combination of required=False and dropping the field value when updating like in this example:
class SectionSerializer(serializers.ModelSerializer):

    # do not require field lesson when updating
    lesson = serializers.PrimaryKeyRelatedField(queryset=Lesson.objects.all(), required=False)

    # do not allow changing the lesson field
    def update(self, instance, validated_data):
        validated_data.pop("lesson", None)
        return super().update(instance, validated_data)


text:
Q: Adding a percentage of group column in python pandas I have a pivot table in a data frame and I'd like calculate group percentages.
for example:

and what I need is:

I've exluded the original data but I'd expect to have that and I know I need to add in these columns.
If I need to add totals to do this that's fine as well, as I will be filtering results out later anyhow.

A: Your example does not really show what is in your index and not.
I made my own dataset:
df = pd.DataFrame({'country':["NL"]*9, 'team':["A"]*3+["B"]*3+["C"]*3, 'outcome':["WIN", "LOSE", "DRAW"] * 3, 'week1':[2,3,4,4,5,2,4,4,2], 'week2':[3,2,5,2,3,4,2,3,4], 'week3':[4,5,2,3,2,5,3,2,5]})
df.set_index(['country', 'team'], inplace=True)

Note that i made a Team C as well. Since two team B does not make sense. I assumed it was a mistake.
By my example, you can simply do:
df_percent = df / df.groupby(level=[0,1]).sum()
df_percent['outcome'] = df['outcome']

             outcome     week1     week2     week3
country team
NL      A        WIN  0.222222  0.300000  0.363636
        A       LOSE  0.333333  0.200000  0.454545
        A       DRAW  0.444444  0.500000  0.181818
        B        WIN  0.363636  0.222222  0.300000
        B       LOSE  0.454545  0.333333  0.200000
        B       DRAW  0.181818  0.444444  0.500000
        C        WIN  0.400000  0.222222  0.300000
        C       LOSE  0.400000  0.333333  0.200000
        C       DRAW  0.200000  0.444444  0.500000

A: Divide the dataframe by sum of the number of games per country and team, obtained using groupby and reshaped using transform.
df = pd.DataFrame({'country': ["NL"] * 9,
                   'team': ["A"] * 3 + ["B"] * 3 + ["C"] * 3,
                   'outcome': ["WIN", "LOSE", "DRAW"] * 3,
                   'week1': [2, 3, 4, 4, 5, 2, 4, 4, 2],
                   'week2': [3, 2, 5, 2, 3, 4, 2, 3, 4],
                   'week3': [4, 5, 2, 3, 2, 5, 3, 2, 5]})
df.set_index(['country', 'team', 'outcome'], inplace=True)

>>> df.divide(df.reset_index().groupby(['country', 'team']).transform(sum).values)
                         week1     week2     week3
country team outcome
NL      A    WIN      0.222222  0.300000  0.363636
             LOSE     0.333333  0.200000  0.454545
             DRAW     0.444444  0.500000  0.181818
        B    WIN      0.363636  0.222222  0.300000
             LOSE     0.454545  0.333333  0.200000
             DRAW     0.181818  0.444444  0.500000
        C    WIN      0.400000  0.222222  0.300000
             LOSE     0.400000  0.333333  0.200000
             DRAW     0.200000  0.444444  0.500000

To make this more clear, you can see what transform is doing.  It returns the results in the same shape as the original dataframe.
>>> df.reset_index().groupby(['country', 'team']).transform(sum).values
array([[ 9, 10, 11],
       [ 9, 10, 11],
       [ 9, 10, 11],
       [11,  9, 10],
       [11,  9, 10],
       [11,  9, 10],
       [10,  9, 10],
       [10,  9, 10],
       [10,  9, 10]])

You can also use transform in the method proposed by @firelynx and skip his last step:
>>> df.divide(df.groupby(level=[0,1]).transform(sum))

                         week1     week2     week3
country team outcome
NL      A    WIN      0.222222  0.300000  0.363636
             LOSE     0.333333  0.200000  0.454545
             DRAW     0.444444  0.500000  0.181818
        B    WIN      0.363636  0.222222  0.300000
             LOSE     0.454545  0.333333  0.200000
             DRAW     0.181818  0.444444  0.500000
        C    WIN      0.400000  0.222222  0.300000
             LOSE     0.400000  0.333333  0.200000
             DRAW     0.200000  0.444444  0.500000

A: i assume that you just wanted to add percentage symbol to all those three columns, considering it a dataframe. if yes you can use the below
df.week1 = df.week1.astype(str).add('%')
df.week2 = df.week2.astype(str).add('%')
df.week3 = df.week3.astype(str).add('%')

redpajama_set_name: RedPajamaStackExchange


text:
Q: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException while sending a request to the server I am trying to connect to a server and sending a HTTPS based request to it using the following code:
// create the URL with the target URL specified
URL url = new URL(vTargetURL);

// create a HTTP connection to the URL specified
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();

// set the timeout for the request
urlConnection.setReadTimeout(30000);

//add request header
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Length", String.valueOf(vRequestXML.length()));
for (HashMap.Entry<String, String> entry : vHttpHeaders.entrySet()) {
    urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
}

// send the request
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(vRequestXML);
dataOutputStream.flush();
dataOutputStream.close();

// read the response
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;

StringBuffer response = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
    response.append(inputLine);
}
bufferedReader.close();

The problem I am facing is that my code is failing at the statement
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());

with the Exception
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

I only understand there is some issue related to the certificate of the server. I am able to bypass this issue by using the following code:
final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
};

urlConnection.setHostnameVerifier(DO_NOT_VERIFY);

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[] {};
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }
}};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
catch (Exception e) {
    e.printStackTrace();
}

Also, when I checked the server address on this website, I got the following error

I know that trusting all host is not a way to solve this problem, but I am not able conclude how should I process about solving these issues. Specifically I want to understand:

*

*What are the possible reasons for such an Exception.

*How can I resolve the issues.

Any leads are appreciated.
Thanks.

A: When you make a HTTPS connection, the server you connect to sends his certificate to prove you got the right server. This certificate is normally signed by another certificate, either by that of a CA (certificate authority), or by just another certificate, which in turn is signed. However long that chain is, on the bottom you find the certificate of a CA.
How do you know that this CA certificate is ok? Java solves this problem by storing the certificates of all trusted CAs in a keystore (cacerts).
The error you are facing is most likely the result of a certificate signed by a CA that is not in the keystore. It is either a self-signed certificate (the certificate itself acting as its own CA), a certificate signed by an in-house CA of some company, or by a small unknown CA.
Yo have to decide whether you want to trust all certificates signed by this CA. In that case take the CA certificate, and put it in your cacerts file.
I have no idea on how to do that on android, though. The standard java tool to do this is keytool.


text:
Q: How to dynamically update a value in a Pandas DataFrame thanks for looking at my question! I am trying to dynamically update some values in a Pandas DataFrame using the values that already exist in the DataFrame.
I know that I can use the loc method to do a look up and update the values I find to something static. For example:
import pandas as pd

customers = pd.DataFrame({'id': [1, 2, 3],
                          'name': ['foo', 'bar', 'foo'],
                          'balance': [100, 200, -300]})

customers.loc[(customers['name']=='foo') & (customers['id']==3), ['balance']] = 300

print(customers)
# {'id': [1, 2, 3], 'name': ['foo', 'bar', 'foo'], 'balance': [100, 200, 300]}

But I am trying to update the value dynamically using values that already exist in the DataFrame, something like:
customers = pd.DataFrame({'id': [1, 2, 3],
                          'name': ['foo', 'bar', 'foo'],
                          'balance': [100, 200, -300]})

customers.loc[(customers['name']=='foo') & (customers['id']==1), ['balance']] = #abs('balance')

I would expect this to update all values from the loc query to be positive integers. Of course, this is a simple example with only one match :)
Is there a way to dynamically access/update values in a Pandas DataFrame like this? Thank you!

A: pandas is index sensitive , so when you assign the value the hidden key is index ,it will match the index , so that you can just apply the condition once.
customers.loc[(customers['name']=='foo') & (customers['id']==1), ['balance']] =customers.balance.abs()
customers
Out[112]:
   balance  id name
0      100   1  foo
1      200   2  bar
2      300   3  foo


text:
Q: Spring Data REST with JSR 303 returns RepositoryConstraintViolationException instead of ConstraintViolationException I'm using Spring Boot 2.2.5, Spring DATA REST, Spring HATEOAS, Hibernate.
I was using validation (JSR 303) since when I was still using Spring 2.1.x. It worked fine. After the migration I've noticed an odd behaviour.
When I use a SDR endpoint (let's say I do a POST or PATCH of an entity) with some validation errors, I get a DataIntegrityViolationException instead of a ConstraintViolationException.
In my pom:
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</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-data-jpa</artifactId>
        </dependency>

I implemented RepositoryRestConfigurer
@Configuration
@Log4j2
public class GlobalRepositoryRestConfigurer implements RepositoryRestConfigurer {

    @Autowired
    private Validator validator;

    @Override
    public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
        validatingListener.addValidator("beforeCreate", validator);
        validatingListener.addValidator("beforeSave", validator);
    }

}

and some other configuration to customize messages:
@Configuration
@EnableRetry
public class CustomConfiguration {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames("classpath:/i18n/messages");
        // messageSource.setDefaultEncoding("UTF-8");
        // set to true only for debugging
        messageSource.setUseCodeAsDefaultMessage(false);
        messageSource.setCacheSeconds((int) TimeUnit.HOURS.toSeconds(1));
        messageSource.setFallbackToSystemLocale(false);
        return messageSource;
    }

    @Bean
    public MessageSourceAccessor messageSourceAccessor() {
        return new MessageSourceAccessor(messageSource());
    }

    /**
     * Enable Spring bean validation https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation
     *
     * @return
     */
    @Bean
    public Validator validator() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        factoryBean.setValidationMessageSource(messageSource());
        return factoryBean;
    }

My repository is this one:
@Transactional
@PreAuthorize("isAuthenticated()")
public interface PrinterRepository extends JpaRepository<Printer, Long>, JpaSpecificationExecutor {

    @Query("FROM Printer p JOIN p.store s")
    List<Printer> findAllJoinStore();

    @RestResource(exported = false)
    @Transactional(readOnly = true)
    @Query("SELECT p FROM Printer p WHERE :allFieldSearch IS NULL OR (p.name LIKE CONCAT('%',:allFieldSearch,'%') OR p.remoteAddress LIKE CONCAT('%',:allFieldSearch,'%'))")
    Page<Printer> search(@Param("allFieldSearch") String allFieldSearch, Pageable pageable);

    @Transactional(readOnly = true)
    @Query("SELECT p FROM Printer p WHERE store.id=:storeId")
    Page<Printer> findByStore(@Param("storeId") long storeId, Pageable pageable);
}

The controller does not override POST/PATH methods to save the entity.
The entity is this:
@Entity
@EntityListeners(PrinterListener.class)
@Filter(name = "storeFilter", condition = "store_id = :storeId")
@ScriptAssert.List({
        @ScriptAssert(lang = "javascript", script = "_.serialNumber!=null", alias = "_", reportOn = "serialNumber", message = "{printer.serialnumber.mandatory}"),
        @ScriptAssert(lang = "javascript", script = "_.model!='VIRTUAL' ?_.remoteAddress!=null:true", alias = "_", reportOn = "remoteAddress", message = "{printer.remoteAddress.mandatory}"),
        @ScriptAssert(lang = "javascript", script = "_.zoneId!=null", alias = "_", reportOn = "zoneId", message = "{printer.zoneId.mandatory}"),
        @ScriptAssert(lang = "javascript", script = "_.zoneId!=null?_.isValidTimeZone(_.zoneId):true", alias = "_", reportOn = "zoneId", message = "{printer.zoneId.invalid}")
})
@Data
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
@ToString(callSuper = true)
public class Printer extends AbstractEntity {

    @NotBlank
    @Column(nullable = false)
    private String name;

    // Ip address or hostname
    private String remoteAddress;

    @NotNull
    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 30)
    // @JsonSerialize(using = PrinterModelSerializer.class)
    private PrinterModel model;

This is my RestControllerAdvice:
@RestControllerAdvice
@Log4j2
public class ApplicationExceptionHandler extends ResponseEntityExceptionHandler {

 @ExceptionHandler(DataIntegrityViolationException.class)
    public ResponseEntity<?> handleConflictException(DataIntegrityViolationException ex, HttpServletRequest request, Locale locale) throws Exception {
        /**
         * Keep the default Exception format for Violation exception @see {@link RepositoryRestExceptionHandler}
         */
        if (ex instanceof RepositoryConstraintViolationException) {
            return new ResponseEntity<RepositoryConstraintViolationException>((RepositoryConstraintViolationException) ex, new HttpHeaders(), HttpStatus.BAD_REQUEST);
        }

        /**
         * Custom errors and messages for DataIntegrityViolationException checked against the list of indexes names
         */
        return response(HttpStatus.CONFLICT, new HttpHeaders(), buildIntegrityError(ex, request, HttpStatus.CONFLICT, locale));
    }

 @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<?> handleValidationException(ConstraintViolationException ex, HttpServletRequest request, Locale locale) throws Exception {
        try {
            ResponseEntity<ConstraintViolationException> response = new ResponseEntity<ConstraintViolationException>(ex, new HttpHeaders(), HttpStatus.BAD_REQUEST);
            //return response(HttpStatus.BAD_REQUEST, new HttpHeaders(), ex);
            return response;
        } catch (Exception e) {
            log.error("", e);
        }
        return response(HttpStatus.BAD_REQUEST, new HttpHeaders(), "");
    }

I tried to save a printer without name and I see these logs:
18/03/2020 12:32:35,859 DEBUG http-nio-8082-exec-10 DataSourceUtils:248 - Resetting read-only flag of JDBC Connection [HikariProxyConnection@1578883309 wrapping com.mysql.cj.jdbc.ConnectionImpl@3f194beb]
18/03/2020 12:32:35,896 DEBUG http-nio-8082-exec-10 ValidatingRepositoryEventListener:173 - beforeSave: Printer(super=AbstractEntity(id=2, sid=1374107f-4597-46e5-bc55-3faf98695987, createdBy=9b9ef528-a45e-4ce9-b014-32a157507aef, createdDate=2019-07-17T17:08:15.688Z, lastModifiedDate=2020-03-17T16:05:27.028Z, lastModifiedBy=9b9ef528-a45e-4ce9-b014-32a157507aef, version=18), name=null, remoteAddress=dev1.epson.local, model=RCH_PRINTF, zoneId=Europe/Rome, ssl=true, serialNumber=dfdfdfdf, lotteryCodeSupport=true, url=) with org.springframework.validation.beanvalidation.LocalValidatorFactoryBean@4fe9a396
18/03/2020 12:32:35,896 DEBUG http-nio-8082-exec-10 ValidationUtils:78 - Invoking validator [org.springframework.validation.beanvalidation.LocalValidatorFactoryBean@4fe9a396]
18/03/2020 12:32:35,905 DEBUG http-nio-8082-exec-10 ValidationUtils:94 - Validator found 1 errors
18/03/2020 12:32:35,905 DEBUG http-nio-8082-exec-10 ExceptionHandlerExceptionResolver:398 - Using @ExceptionHandler it.test.server.config.exceptions.ApplicationExceptionHandler#handleConflictException(DataIntegrityViolationException, HttpServletRequest, Locale)
18/03/2020 12:32:35,906 DEBUG http-nio-8082-exec-10 HttpEntityMethodProcessor:265 - Using 'application/json', given [application/json, text/plain, */*] and supported [application/json, application/*+json, application/json, application/*+json, application/x-jackson-smile, application/cbor]
18/03/2020 12:32:35,906 DEBUG http-nio-8082-exec-10 HttpEntityMethodProcessor:91 - Writing [org.springframework.data.rest.core.RepositoryConstraintViolationException: Validation failed]
18/03/2020 12:32:35,906 DEBUG http-nio-8082-exec-10 HstsHeaderWriter:169 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@5fe7b347
18/03/2020 12:32:35,907 DEBUG http-nio-8082-exec-10 HttpSessionSecurityContextRepository:376 - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@4af5538a: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@4af5538a: Principal: User(super=AbstractEntity(id=1, sid=9b9ef528-a45e-4ce9-b014-32a157507aef, createdBy=system, createdDate=2019-07-17T16:52:07.194Z, lastModifiedDate=2020-02-14T09:54:28.869Z, lastModifiedBy=9b9ef528-a45e-4ce9-b014-32a157507aef, version=18), fullName=Brusò Andrea, username=admin, password=$2a$10$GWOzC9clkzUf4YgZ7BmOLeiUm9cSi4zLhvjVXeNLahvxJZ2dIdzLq, lastPasswordUpdate=null, enabled=true); Credentials: [PROTECTED]; Authenticated: true; Details: it.test.server.config.security.CustomWebAuthenticationDetails@67692d4c; Granted Authorities: ROLE_ADMIN' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@2f2b2167
18/03/2020 12:32:35,907 DEBUG http-nio-8082-exec-10 ExceptionHandlerExceptionResolver:145 - Resolved [org.springframework.data.rest.core.RepositoryConstraintViolationException: Validation failed]
18/03/2020 12:32:35,908 DEBUG http-nio-8082-exec-10 DispatcherServlet:1131 - Completed 400 BAD_REQUEST
18/03/2020 12:32:35,908 DEBUG http-nio-8082-exec-10 ExceptionTranslationFilter:120 - Chain processed normally
18/03/2020 12:32:35,908 DEBUG http-nio-8082-exec-10 SecurityContextPersistenceFilter:119 - SecurityContextHolder now cleared, as request processing completed

As you can see, the validation is performed but Spring decide to invoke it.test.server.config.exceptions.ApplicationExceptionHandler#handleConflictException instead of handleValidationException.
What I did notice is that I get the right exception if I override POST/PATH methods using a custom controller. Doing that logs change:
18/03/2020 12:38:01,503 DEBUG http-nio-8082-exec-9 ServletInvocableHandlerMethod:174 - Could not resolve parameter [1] in public org.springframework.http.ResponseEntity<?> it.test.server.rest.controllers.accounts.AgentController.update(java.lang.Long,it.test.server.model.accounts.Agent,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler): lastName: Il campo non può essere vuoto. Inserire un valore valido e ripetere l'operazione.
18/03/2020 12:38:01,504 DEBUG http-nio-8082-exec-9 ExceptionHandlerExceptionResolver:398 - Using @ExceptionHandler it.test.server.config.exceptions.ApplicationExceptionHandler#handleValidationException(ConstraintViolationException, HttpServletRequest, Locale)
18/03/2020 12:38:01,507 DEBUG http-nio-8082-exec-9 HttpEntityMethodProcessor:265 - Using 'application/json', given [application/json, text/plain, */*] and supported [application/json, application/*+json, application/json, application/*+json, application/x-jackson-smile, application/cbor]
18/03/2020 12:38:01,507 DEBUG http-nio-8082-exec-9 HttpEntityMethodProcessor:91 - Writing [javax.validation.ConstraintViolationException: lastName: Il campo non può essere vuoto. Inserire un  (truncated)...]
18/03/2020 12:38:01,508 DEBUG http-nio-8082-exec-9 HstsHeaderWriter:169 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@5fe7b347
18/03/2020 12:38:01,508 DEBUG http-nio-8082-exec-9 HttpSessionSecurityContextRepository:376 - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@4af5538a: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@4af5538a: Principal: User(super=AbstractEntity(id=1, sid=9b9ef528-a45e-4ce9-b014-32a157507aef, createdBy=system, createdDate=2019-07-17T16:52:07.194Z, lastModifiedDate=2020-02-14T09:54:28.869Z, lastModifiedBy=9b9ef528-a45e-4ce9-b014-32a157507aef, version=18), fullName=Brusò Andrea, username=admin, password=$2a$10$GWOzC9clkzUf4YgZ7BmOLeiUm9cSi4zLhvjVXeNLahvxJZ2dIdzLq, lastPasswordUpdate=null, enabled=true); Credentials: [PROTECTED]; Authenticated: true; Details: it.test.server.config.security.CustomWebAuthenticationDetails@67692d4c; Granted Authorities: ROLE_ADMIN' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@2bd24cb7
18/03/2020 12:38:01,509 DEBUG http-nio-8082-exec-9 ExceptionHandlerExceptionResolver:145 - Resolved [javax.validation.ConstraintViolationException: lastName: Il campo non può essere vuoto. Inserire un valore valido e ripetere l'operazione.]
18/03/2020 12:38:01,509 DEBUG http-nio-8082-exec-9 DispatcherServlet:1131 - Completed 400 BAD_REQUEST
18/03/2020 12:38:01,509 DEBUG http-nio-8082-exec-9 ExceptionTranslationFilter:120 - Chain processed normally

So my guess is the problem is the configuration of JSR303 with SDR but unfortunately I did not find any hint on the doc.
Any advice would be really appreciated.

A: RepositoryConstraintViolationException is a subclass of DataIntegrityViolationException.
Look at the source code of ValidatingRepositoryEventListener in Spring Data REST. The method ValidatingRepositoryEventListener.validate() does throw an RepositoryConstraintViolationException.
private Errors validate(String event, Object entity) {

...
    Errors errors = new ValidationErrors(entity, persistentEntitiesFactory.getObject());

    if (errors.hasErrors()) {
        throw new RepositoryConstraintViolationException(errors);
    }
...
}

When you use custom controller, this request has nothing to do with Spring Data REST, so a plain ConstraintViolationException is thrown.

A: A bit late to the game, but you can actually easily adapt any @ErrorHandler you might have provided for ConstraintViolationException to this new exception by taking advantage of the fact that RepositoryConstraintViolationException.errors.allErrors unwrap to ConstraintViolation instances, as long as JSR 303 is enabled for your project.
Example for Problem Spring Web:
public interface RestValidationAdviceTrait extends ValidationAdviceTrait {

    @ExceptionHandler
    default ResponseEntity<Problem> handleConstraintViolation(
            final RepositoryConstraintViolationException exception,
            final NativeWebRequest request) {

        final List<Violation> violations = exception.getErrors().getAllErrors().stream()
                .map(error -> error.unwrap(ConstraintViolation.class))
                .map(this::createViolation)
                .collect(toList());

        return newConstraintViolationProblem(exception, violations, request);

    }

}


text:
Q: how to get my facebook share dialog to display the facebook share button rather than just text? how to get my facebook share dialog to display the facebook share button rather than just text? Furthermore I'd like to ask how to get it to display the actual shares? The generic code at https://developers.facebook.com/docs/reference/plugins/share-links/ does not answer this question. Thanks for any help

A: What you are looking for is the Share Button. Facebook has deprecated this and this will no longer be supported. So, you have to use the Share Dialog instead that you've mentioned.


text:
Q: how to solve this problem in logic expressions problem? z = 1
x1 = 1
y1 = 1

while x1!= 0:
    if y1==0:
        z = 0
        x1 -= 1

while y1!=0:
    if x1 ==0:
        z = 0
        y1 -= 1

while x! = 0:
    while y!= 0:
        z +=1
        x = 0
        y = 0

I know I can use OR/ AND ... but I want to solve it using while loops  when two values are different the result ; z = 0 and when the values are the same then z = 1. These values
(1,0) = 0
(0,1) = 0
(0,0) = 1

except I'm facing this problem with (1,1) because the program is looping and I don't know how to handles it - can some one please help?
the expected output is (1,1) = 1

A: Your first loop will hang when both x1 and y1 are 1, because the if condition will always be false, and so none of the variables change and the while condition will always remain true.
The thing is that you shouldn't use loops at all when dealing with just 0 and 1 values.
The following mapping of (x, y) to z:
 (0, 0) => 1
 (0, 1) => 0
 (1, 0) => 0
 (1, 1) => 1

...can be achieved in many ways in Python. Here are a few
z = int(x == y)
z = x ^ y ^ 1
z = 1 - (x ^ y)

We can imagine the desired outcome of an operation to be represented by a four-digit binary number. In the above case the code would be 1001 (reading the 4 outcomes from top to bottom).
Here is a table of assignments to z you can use for the different "codes":

code
formula

0000
z = 0

0001
z = x & y

0010
z = (x ^ 1) & y

0011
z = y

0100
z = x & (y ^ 1)

0101
z = x

0110
z = x ^ y

0111
z = x | y

1001
z = x ^ y ^ 1

1010
z = x ^ 1

1011
z = (x ^ 1) | y

1100
z = y ^ 1

1101
z = x | (y ^ 1)

1110
z = (x & y) ^ 1

1111
z = 1


text:
Q: Google maps API getting drive time and road I'm trying to achieve something like the following in the image

but Actually I don't have any Idea if it's possible or how and where to start.
so if you can please lead me if it's possible or not, and how to achieve it or where to start
or if anyone knows a similar online working example it would be great
thanks in advance

A: I found the answer myself, yes it's possible thanks to jfvanderwalt for the useful link of google Docs for Direction API which led me to the working example of what I need and how to do it , here is my working demo example
Javascript :

HTML:


text:
Q: How to let the server receive JSON DATA I can't understand why this code doesn't get the JSON data from the Blocktrail Payments API)
$DATA = json_decode(file_get_contents("php://input"), true);

The server keeps saying that everything is good, but I can't get any data and there are no errors, is there any option on the server for enabling php://input?
I've already used other JSON data from other servers, for example, the Google reCaptcha and it works fine.
I use CloudFlare but it's turned off so it can't be causing this problem,


text:
Q: vlookup values displayed month text I am using a VLOOKUP to look at specifically a date column on a separate sheet.
=(VLOOKUP(A:A,'ECRM HISTORIES'!B:N,13,FALSE))

It displays the date as 25/05/12, however i need to display the only the Month & Year, such May-2012.
Is it possible to incorporate the TEXT("mmm") formula?

A: You can wrap the VLOOKUP function in various functions to produce the output you want.
You can also just custom format the result cell with the Date format you want.

A: The answer to your question is Yes, though as implied by @Brad's answer there is often an easier way to achieve a similar result more easily. (ie with formatting, though Date March-01 obviously will not show all four digits for the year [Custom mmm-yyyy will however]).
Formatting changes the presentation but underlying that in Excel there is still a date serial number, so 25/5/12 and 26/5/12 can both be represented as May-2012 without actually being the same, which might give incorrect results if used in calculations (in effect =May-2012=May-2012 could return FALSE).
A way round this is indeed to apply TEXT:


text:
Q: Array problem, can only have one row. I'm not sure what I'm doing wrong, I'm trying to create a line of bits with labels. I'm trying to do this with an array:
$\begin{array}{c|ccccccc}

\mbox{L1} & \mbox{L2} & \mbox{L3} & \mbox{L4} & \mbox{L5} & \mbox{L6} & \mbox{L7} & \mbox{L8}
0 & 0 & 1 & 0 & 1 & 0 & 1 & 1

\end{array}$

However this doesn't work, I get the error:
! Extra alignment tab has been changed to \cr.
<recently read> \endtemplate

l.705 0 &
          0 & 1 & 0 & 1 & 0 & 1 & 1 \end{array}$
?

It does work if I only have one row.
What is going wrong? I'm compiling with pdfLaTeX. Alternatively if there's a better way to do this (I'm trying to label a row of bits so that the distances between the 1s and 0s remains constant) let me know.

A: You have to break line after \mbox{L8}.
The following is compiled without any errors:
\documentclass{article}

\begin{document}

$\begin{array}{c | c c c c c c c}
\mbox{L1} & \mbox{L2} & \mbox{L3} & \mbox{L4} & \mbox{L5} & \mbox{L6} & \mbox{L7} & \mbox{L8}\\
0 & 0 & 1 & 0 & 1 & 0 & 1 & 1
\end{array}$

\end{document}


text:
Q: I need to copy computers from the default active directory "container" to security group using powershell I'm trying to remove all computers from the wk_test security group and then add all the computers in the default 'Computers' container in AD to the (now-empty) wk_test security group.
However, I don't want to export the computers to a list and then import them back into the security group.
I have the first part of the script working properly, and it removes the computers from the wk_test group with no errors. My issue is adding the computers to the wk_test group from the "computers" container.
Remove-ADGroupMember "wk_test" -Members (Get-ADGroupMember "wk_test") -Confirm:$false
Add-ADGroupMember -Identity "wk_test" -Members (Get-ADComputer -SearchBase "CN=computers,DC=ad,dc=org") -filter*

I think the main problem is that I am attempting to copy from the computers container. Most of the advice on the internet refers to copying from an OU and not a container.

A: If you are moving them, why not use Move-ADObject.
So it would be:
Get-ADGroupMember "wk_test" | Move-ADObject -TargetPath <ou path>

A: The Add-ADGroupMember documentation says:

You cannot pass user, computer, or group objects through the pipeline to this cmdlet.

Which I think is what you are trying to do.
I've used this method before to add computers from an OU to a group:
Get-ADComputer -SearchBase "CN=computers,DC=ad,dc=org" -Filter * | foreach {Add-ADGroupMember "wk_test" -Members $_.DistinguishedName }

But I think you could also modify your code like this, but I've not tested this as I'm not on domain at the moment.
$Computers = Get-ADComputer -SearchBase "CN=computers,DC=ad,dc=org" -filter* | select -ExpandProperty DistinguishedName
Add-ADGroupMember -Identity "wk_test" -Members $Computers


text:
Q: Getting the ListView to reload it's Views The situation:
I have an activity with a spinner and a list with a BaseAdapter.
The list is loaded once, and shows correctly... But when I click on the spinner to change the underlying data and call adapter.notifyDataSetChanged(); the list doesn't refresh.
By this I mean that the data is changed and the adapter has the right data, it's just that the listView doesn't change the view.
How to force the listViews to show the right data?

A: Try adapter.notifyDataSetInvalidated(); as well as adapter.notifyDataSetChanged();

EDIT:
Clear your ArrayList or whatever you're using before you add more items with something like .clear(); and then add the new items and call adapter.notifyDataSetChanged();

A: Try
myListView.invalidateViews();


text:
Q: How can I click button and change style in scss? I have scss file where on click of Filter button I want to display   buttons(Present in demos class). As of now I am able to achieve this using :active selector. But for this selector to work I have to longpress the button for sometime. I am trying to achieve this just on click of the button. How can I achieve such functionality (Without Jquery or JS)?
Here is my scss file
.bot {
  &:active {
     .demos {
      .tools {
        background-color: pink;
        display: block;

      }
    }
  }
}

Here is my html file
<button class="bot" (click)="xy()">Filter
    </button>

A: You can either style a checkbox to look like a button and use the :checked selector...
Or, if it's enough to show them once you clicked the button and there is no need to hide the content again, you can use an a-tag as an anchor link to the div you want to show and display it by selecting it with the :target selector:

.demos {
  display: none;
}

.demos:target {
  display: block;
}
Filter

    content ...


text:
Q: Install jsreport in the application server Can jsreport be hosted on the same server where the application is being executed?
jsreport website has this schema to describe how it should work:

I've installed jsreport in the app server, and added the following code to the app:

Code:
var jsreport   = require( 'jsreport' );
jsreport.bootstrapper().start();

And the following two messages are the ones I have doubts about:
2015-11-25T05:39:17.346Z - info: Creating default express app.
2015-11-25T05:39:17.495Z - info: jsreport server successfully started on http port: 61070

First, is it running another express app?(I already have an express app), Second, my app is running under port 3000, Why does it started on other port?
Also, if someone could give an explanation of the correct way to install it and run it, and also an example of how to make an endpoint for a report to be called from the client side of my app, I'll thank you...

A: From the documentation:

Attach to existing express app
If the jsreport contains express extension it will automatically start
  a default express.js based server running on ports specified in
  config. This behavior can be overridden with passing express
  application instance to the options. In this case jsreport express
  extension will just add required routes and middle-wares to the passed
  instance.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello from the main application');
});

var reportingApp = express();
app.use('/reporting', reportingApp);

var server = app.listen(3000);

var jsreport = require('jsreport')({
  express: { app :reportingApp, server: server },
  appPath: "/reporting"
});

jsreport.init().catch(function (e) {
  console.error(e);
});

See the docs for other answers.


text:
Q: Agora cloud recording with Google cloud storage I want to record my voice call with agora cloud recording. I'm using a Postman collection provided by Agora, and I don't change anything except StorageConfig. I'm successful in getting resourceID and sid, but when I stop recording, I receive the error "Failed to find worker." Based on an agora document, they said for Google Clound the region parameter has no effect, whether it is set or not, so I'm setting it to 0. There's a list of solutions I've tried but have had no success with:

*

*Change region

*Both users have different UIDs, and the recording UID is different from them.

*Access key and secret key is correct
I don't know what I did wrong. Please help me. Thanks all.

{
    "resourceId": "nUwUbQf9Zg6tsgtLslGnDg0lk8RYaUE09pqOuSIgwfwi6-n9kITolzw3vvIFHMfm2VZsOrLd9fk9kMzos8Y_D-2Z2fFtUu_1BD2_pKJEZ-jTgXPe--K6Ua7TpSNY0pLd4zzyZV6iXCndqZvHmfsZloox0y-UZgs-r2_zBR2Gor05YCP0HuusWF8Kv1StAYabr1HJykw7RorDYnUIzzry6p6LRfvlq2zJVyVxvzVRVmoeMPYX-cVKyhNDuI2ct9a9aPdi8jCwDUzRbYimVVAnJBRYppTH012Xt6DnnMBkskJsbK0-CK3IaipQA9Gu2RmIJxSowuZbHspwA2lpwpzre-aNG6NlXk95hZgthOfNUVE",
    "sid": "edd35b65ec496e43aa502cad99bbdb27",
    "code": 404,
    "serverResponse": {
        "command": "StopCloudRecorder",
        "payload": {
            "message": "Failed to find worker."
        },
        "subscribeModeBitmask": 1,
        "vid": "1020399"
    }
}


text:
Q: Does the matrix of all arrangements of standard basis vectors have a name? For example, in $\mathbb{R}^2$, we have the standard basis
$$ \beta = \left\{ \begin{pmatrix}1 \\ 0\end{pmatrix}, \begin{pmatrix}0 \\ 1\end{pmatrix} \right\} $$
What I mean by all arrangements of the standard basis vectors is that the first column of the matrix contains one copy of each basis vector. Successive columns have the same vectors but in a different order. The details are more easily shown by example:
$$A_2=\begin{pmatrix}1 & 0 \\ 0 & 1 \\ 0 & 1 \\ 1 & 0\end{pmatrix}$$
So, $\begin{pmatrix}1 \\ 0 \end{pmatrix}$ is in the top left and the bottom right. We can represent these matrices as images with black representing zeros and white representing ones. Here is one for $\mathbb{R}^3$:

And here is one for $\mathbb{R}^4$:

Some properties of them are that every column has $n$ ones (by definition), while every row has $(n-1)!$ ones. The rank is equal to $n^2-2n+2$. The most interesting property I found was that the product $A_nA_n^T$ has a curious simplicity, being writable in terms of the Kroneker product $\otimes$, the identity $I_n$, and the all-ones matrix $J_n$ as:
$$A_nA_n^T=(n-1)!I_n\otimes I_n + (n-2)!(J_n-I_n) \otimes(J_n - I_n)$$
Or, as an image for $n=6$ where white is $(n-1)!$ and grey is $(n-2)!$:

Which is why the rank is what it is. I have determined why this pattern happens, but I don't think it's relevant to this question.
Is there a name for these matrices? Or alternatively, is there an equivalent formulation with a name?


text:
Q: What effects does heat have on an LCD screen? Unfortunately some water got into my LCD screen creating weird dim patches against the bright back light. only the screen seems to be affected, not anything else.
I am thinking of keeping it in the sun so that water could evaporate, or maybe using a hair dryer. What adverse effects may this have on my LCD screen?
EDIT2 : I tried other options to make the water go away, none of them worked. Seems like heat is the only solution, but I'd still like to know of any adverse effects so that I don't damage it further.

A: Rather than a hair drier blowing hot air why not blow unheated air? I do that to my coffee maker's LCD display when it gets water in it. A window fan or desktop fan.


text:
Q: PHP - Simplexml, чтение файла Есть xml файл, который я хочу распарсить. Делаю я это так:
$get = file_get_contents('./1c.xml');
$arr = simplexml_load_string($get);
print_r($arr);

Получаю вот такой вывод:
    SimpleXMLElement Object
(
    [Группа] => Array
        (
            [0] => Первая
        )
)

Хотя у меня файл содержит много элементов, вот чего часть:
<Каталог>
<Группа>Дом
    <Группа>Первая
        <Группа>Классика
            <Группа>Футбол
                <Номенклатура>
                    <Наименование>Футболка</Наименование>
                    <Цена>121</Цена>
                    <ЦенаСоСкидкой>121</ЦенаСоСкидкой>
                    <Цвет>Серый</Цвет>
                    <Размер>44</Размер>
                    <Материал/>
                    <Категория/>
                </Номенклатура>

Т.е. из-за того, что <Группа>Первая вот так записана, скрипт думает, что объект пустой.
Можно ли эту проблему как-то побороть?

A: Вообще у вас точка входа - Каталог.
Что бы получить "дом" необходимо написать так:
$arr->Группа->xpath("parent::*")

или  так $arr[0]
Получить "Первая"
$arr->Группа

Получить далее
$arr->Группа->Группа

И так далее...
$arr->Группа->Группа->Группа


text:
Q: vue-select, buefy CSS not working on production | NUXT.JS I am using buefy autocomplete component with nuxt.js. I have imported the CSS file. and the CSS working properly on the localhost but on the live server is not working. I thought the problem may be with buefy but the same problem I am facing with vue-select autocomplete.
Everything is perfect on the local server but when I move my files to live server and do num run build noting works from buefy and vue-select.
Note: the rest of all CSS working just fine
Localhost

Production

And it's not only autocomplete component, none of the buefy components are working, Radio Buttons, Calender etc.
A little guidance will be appreciated.
Thanks

A: As of today, Buefy has an official support for Nuxt. Instead of importing buefy's css inside nuxt.config.js and creating a new plugin, you can use a nuxt module.
If you create a new Nuxt project using create-nuxt-app, you can choose to add Buefy as your UI framework.
If you have an existing nuxt project, you can simply install the nuxt-buefy module manually:
npm i nuxt-buefy

nuxt.config.js
...,
modules: [
  'nuxt-buefy',
],
...


text:
Q: How to prevent the subgraph cluster alignment order from being reversed? If I have a graphviz dot script like this:
digraph g {
node [style=rounded, shape=box]

    subgraph cluster1 {
        style="invis"
        1 -> 2 -> 3 -> 4 -> 5
    }

    subgraph cluster2 {
        style="invis"
         6 -> 7

         7 -> 8 -> 11
         7 -> 9 -> 11
         7 -> 10 -> 11
    }

    edge[constraint=false];
    splines="ortho"
    5 -> 6 [weight=0]
}

I get an output that looks like this (what I want):

However, if the labels in some of the nodes at the end become too long, the arrangement gets reversed like this:
digraph g {
node [style=rounded, shape=box]

8 [label="very long label"]
9 [label="very long label"]
10 [label="very long label"]

    subgraph cluster1 {
        style="invis"
        1 -> 2 -> 3 -> 4 -> 5
    }

    subgraph cluster2 {
        style="invis"
         6 -> 7

         7 -> 8 -> 11
         7 -> 9 -> 11
         7 -> 10 -> 11
    }

    edge[constraint=false];
    splines="ortho"
    5 -> 6 [weight=0]
}

How can I prevent this and force the original ordering method to occur?

A: You will have to define your long labels after having defined the other; graphviz draws the nodes in the order the are defined.
digraph g {
node [style=rounded, shape=box]

    subgraph cluster1 {
        style="invis"
        1 -> 2 -> 3 -> 4 -> 5
    }

    subgraph cluster2 {
        style="invis"
         6 -> 7

         7 -> 8 -> 11
         7 -> 9 -> 11
         7 -> 10 -> 11
    }

    8 [label="very long label"]
    9 [label="very long label"]
    10 [label="very long label"]

    edge[constraint=false];
    splines="ortho"
    5 -> 6 [weight=0]
}

yields


text:
Q: jQuery: Trouble getting hide() and show() to work I'm new to jquery and I'm practicing with it. I have created two tables which show the pronunciation of the military nato alphabet and phonetic alphabet. Upon selecting "Alfabet" or "Cijfers" in the dropdown box, the corresponding table must be shown. This is not working, and I don't know what I'm doing wrong. I hope someone can help me pinpoint the issue here.
Here's a jsFiddle: http://jsfiddle.net/qGUHy/1/
$(document).ready(function() {
$(".cijfers").hide();
});

$('#dropdown').change(function () {
    if ($('#dropdown option:selected').text() == "Alfabet"){
        $('.cijfers').hide();
        $('.alfabet').show();
    } else if ($('#dropdown option:selected').text() == "Cijfers"){
        $('.alfabet').hide();
        $('.cijfers').show();
    } else {
        $('.cijfers').hide();
    } });

A: You don't bind to your select because your "#dropdown" selector looks for an element by id but you gave your element a name. You could select by name (using "[name=dropdown]") but the best here is to use an id.
Change
    <select name="dropdown">

to
    <select id="dropdown">

Fixed fiddle


text:
Q: Crystal Report Image - Help I'm using the Crystal Reports-2008 included with VisualStudio 2008. I would like to change the image that is displayed on the report at runtime ideally by building a path to the image file and then have that image displayed on the report.
Thanks,
Sr

A: I couldn't find a straight forward way of doing this so I wrote a blog on it
http://paul-j-power.blogspot.com/2011/01/crystal-reports-how-to-insert-logo-into.html


text:
Q: Trouble understanding the alignment of epipoles with an axe This question arose when I was reading this paper. The goal is the estimation of the relative pose of two cameras C1 and C2, given five point correspondences.
The projective planes are considered as unit spheres, and the global coordinate system is chosen such that the ZG axis joins the camera centers. The problem is solved if we can find two matrices R1 and R2, respectively mapping the internal coordinate systems of C1 and C2 to the global system described previously (to me, it sounds that these matrices will just align the Zc_1 and Zc_2 axes of the cameras with the global ZG axis).
These matrices are computed in an iterative manner, and at each iteration, all point correspondences (v1,v2) are updated via a rotation, becoming (R1v1,R2v2).
So far, everything makes sense. But later, the authors state that these rotations change the direction of the epipoles (I assume relative to the camera Z axes), and that "by rotating the unit spheres such that the z-axis ZG is aligned with the epipoles, i.e. ZG=R1e1=R2e2 the rotated point correspondences (v1,v2) become coplanar with the epipoles e1, e2".
To me, the ZG axis, being the baseline, is always aligned with the epipoles, and a rotated epipole Re is no longer an epipole, since it moves away from the baseline. But the quotation above implies that there are configurations in which the epipoles are not aligned... As you can see, I'm completely confused... please help me understand what the author means by that.


text:
Q: UPDATE table on JOIN with duplicate values is only returning first value When I try to import values from one table to another table, I don't get all the results. Example, see code below, where I ask to:
JOIN transaction ON transaction.invoice = invoicing.invoice

Sometimes, I have 2 or 3 invoices with the same invoice number and the UPDATE only happens on the first invoice number, skips the others with same invoice number.
I need all invoices, including duplicates.
UPDATE invoicing
JOIN transaction ON transaction.invoice = invoicing.invoice
SET invoicing.raison = transaction.transaction, invoicing.description =
transaction.description, invoicing.voyage_passenger = transaction.voyage_passenger

What am I missing?
EDIT:
Table Transaction:
|num    |date           |invoice    |type   |transaction    |amount   |description
|886051 |1375381803     |859532     |A      |carte          |7.00     |bla bla desc1
|886052 |1375381809     |859532     |P      |repro          |0.00     |bla bla desc2

Table Invoicing - has approx 8 more columns than table above not noted below.
Again, I just need the info from the 2nd row above to also be included into the table below in a new row.  I also realize now that I should need an INSERT rather than UPDATE to insert these duplicate rows.
|num    |date           |invoice    |type   |raison |amount   |description   |clientID
|951100 |1375381803     |859532     |A      |carte  |7.00     |bla bla desc1 |121212
|951101 |1375401111     |859533     |A      |carte  |7.00     |bla different |222444

Thank you for your help.

A: Don't know what to do with ClientId. According your sample data invoice can be in different dates so I'm not sure if ClientId is the same for the different dates invoice.
insert into invoicing (`num`, `date`, `invoice`, `type`,
                       `raison`, `amount`, `description`)
select `num`, `date`, `invoice`, `type`, `transaction`, `amount`, `description`
from Transaction t
where not exists
( select `num` from invoicing i
  where
       i.`num`=t.`num`
   and i.`date`=t.`date`
   and i.`invoice`=t.`invoice`
   and i.`type`=t.`type`
   and i.`raison`=t.`transaction`
   and i.`amount`=t.`amount`
   and i.`description`=t.`description`

 )

SQLFiddle demo

A: The invoice number in the first table in the join probably doesn't exist in the second table.Why not a LEFT JOIN?


text:
Q: Numpy Array Change indices I have an numpy-array with 32 x 32 x 3 pictures with X_train.shape: (32, 32, 3, 73257). However, I would like to have the following array-shape: (73257, 32, 32, 3).
How can I accomplish this?

A: There are two ways to archive this either np.reshape(x, ndims) or np.transpose(x, dims).
For pictures I propose np.transpose(x, dims) which can be applied using
X_train = np.transpose(X_train, (3,0,1,2)).

A: I think you want to do a transpose
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> a.transpose()
array([[1, 3],
       [2, 4]])
>>> a.transpose((1, 0))
array([[1, 3],
       [2, 4]])
>>> a.transpose(1, 0)
array([[1, 3],
       [2, 4]])

A: np.reshape(X_train, (73257, 32, 32, 3))

https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.reshape.html


text:
Q: Closure in Java 7 What is closure? It is supposed to be included in Java 7. (Closures were discussed for inclusion in  Java 7, but in the end were not included. -ed) Can anyone please provide me with some reliable references from where I can learn stuff about closures?

A: A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.
Since Java 1.1, anonymous inner class have provided this facility in a highly verbose manner. They also have a restriction of only being able to use final (and definitely assigned) local variables. (Note, even non-final local variables are in scope, but cannot be used.)
Java SE 8 is intended to have a more concise version of this for single-method interfaces*, called "lambdas". Lambdas have much the same restrictions as anonymous inner classes, although some details vary randomly.
Lambdas are being developed under Project Lambda and JSR 335.
*Originally the design was more flexible allowing Single Abstract Methods (SAM) types. Unfortunately the new design is less flexible, but does attempt to justify allowing implementation within interfaces.

A: According to Tom Hawtin

A closure is a block of code that can be referenced (and passed
  around) with access to the variables of the enclosing scope.

Now I'm trying to emulate the JavaScript closure example on Wikipedia, with a "straigth" translation to Java, in the hope to be useful:
//ECMAScript
var f, g;
function foo() {
  var x = 0;
  f = function() { return ++x; };
  g = function() { return --x; };
  x = 1;
  print('inside foo, call to f(): ' + f()); // "2"
}
foo();
print('call to g(): ' + g()); // "1"
print('call to f(): ' + f()); // "2"

Now the java part: Function1 is "Functor" interface with arity 1 (one argument).  Closure is the class implementing the Function1, a concrete Functor that acts as function (int -> int).
In the main() method I just instantiate foo as a Closure object, replicating the calls from the JavaScript example. The IntBox class is just a simple container, it behave like an array of 1 int: int a[1] = {0}
interface Function1   {
    public final IntBag value = new IntBag();
    public int apply();
}

class Closure implements Function1 {
   private IntBag x = value;
   Function1 f;
   Function1 g;

   @Override
   public int apply()  {
    // print('inside foo, call to f(): ' + f()); // "2"
    // inside apply, call to f.apply()
       System.out.println("inside foo, call to f.apply(): " + f.apply());
       return 0;
   }

   public Closure() {
       f = new Function1() {
           @Override
           public int apply()  {
               x.add(1);
                return x.get();
           }
       };
       g = new Function1() {
           @Override
           public int apply()  {
               x.add(-1);
               return x.get();
           }
       };
    // x = 1;
       x.set(1);
   }
}
public class ClosureTest {
    public static void main(String[] args) {
        // foo()
        Closure foo = new Closure();
        foo.apply();
        // print('call to g(): ' + g()); // "1"
        System.out.println("call to foo.g.apply(): " + foo.g.apply());
        // print('call to f(): ' + f()); // "2"
        System.out.println("call to foo.f.apply(): " + foo.f.apply());

    }
}

It prints:
inside foo, call to f.apply(): 2
call to foo.g.apply(): 1
call to foo.f.apply(): 2

A: Here is Neal Gafter's blog one of the pioneers introducing closures in Java. His post on closures from January 28, 2007 is named A Definition of Closures On his blog there is lots of information to get you started as well as videos. An here is an excellent Google talk - Advanced Topics In Programming Languages - Closures For Java with Neal Gafter, as well.

A: Please see this wiki page for definition of closure.
And this page for closure in Java 8: http://mail.openjdk.java.net/pipermail/lambda-dev/2011-September/003936.html
Also look at this Q&A: Closures in Java 7

A: Java Closures are going to be a part of J2SE 8 and is set to be released by the end of 2012.
Java 8's closures support include the concept of Lambda Expressions, Method Reference, Constructor Reference and the Default Methods.
For more information and working examples for this please visit: http://amitrp.blogspot.in/2012/08/at-first-sight-with-closures-in-java.html

A: Yes,Closure (Lambda Expressions) is the new feature with the upcoming Java SE 8 release.
You can get more info about this from the below link:
http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

A: A closure implementation for Java 5, 6, and 7
http://mseifed.blogspot.se/2012/09/bringing-closures-to-java-5-6-and-7.html
It contains all one could ask for...


text:
Q: Вывод денег из аккаунтов Google Play и AdMob Дано:
Накоплена минимально возможная для вывода сумма денег в аккаунтах магазина приложений и AdMob.
Есть гражданство РФ, паспорт РФ, бумажная открытка от AdMob-a, доставленная почтой России из Калифорнии (с пинкодом), подтверждающая, что я реальный человек, вот это всё.
В Интернетах множество разной степени устарелости инфы на счёт вывода доходов. Начиная с чеков, доставляемых почтой России и кончая договорами с фирмами-резидентами США, кои получают, берут процент и отправляют разработчику остаток.
Возможное решение:
Вот сейчас посмотрел в настройках аккаунтов - вроде как в обоих есть опция указать реквизиты долларового банковского счёта, коий позволяет получать деньги по SWIFT. Звучит просто - идёшь в банк (я спрашивал в СберБанке про открытие счёта - говорят только паспорт нужен), открываешь счёт => отсылаешь гуглу реквизиты => получаешь честно нажитые...
Возможные проблемы:
Изначально то ли напутал, то ли опции такой не было - в Play Market я указан как юридическое лицо и поменять (как я понял по отсутствию соответствующей кнопки в настройках аккаунта и как на хабре читал) уже ничего нельзя (т.е. указать себя физическим лицом). В AdMob-e значусь физическим лицом.
Вопрос:
Стоит ли мне считать достаточным открытие долларового счёта и отсыл его реквизитов гуглу для получения денег с обоих аккаунтов? Какие могут быть подводные камни? Что там с налогами (подоходный там, НДС, etc)? Когда-то на хабре видел статейку с переводом на русский договора гуглового маркета с разработчиком, коий, якобы, какой-то банк у кого-то требовал. Неужто тоже надо? Ну и разные мелочи типа дат, по коим "з/п" приходить будет, интересуют)

A: Я решил это так:

*

*Получаем ИНН в родной налоговой. Это довольно просто, кстати. Можно подать заяву через сайт налоговой - назначат время и получаешь бумажку с ИНН

*Получаем карту банка Tinkoff (не реклама!) - можно оформить в онлайне, сами приедут и привезут в офис/домой

*Карта этого банка (в отличие от сберовской) автоматически привязана к забугорному счету (что-то типа Chase Manhattan) - со всеми нужными SWIFT'ами и проч.

*Идем в гуглевский аккаунт и забиваем туда реквизиты + ИНН

*Опля, и через некоторое время смска из банка известит о поступлении тугриков на счет карты. Тугрики поступают раз в месяц в начале месяца.

*Далее, самое важное - надо раз в год подавать декларацию о доходах в своей налоговой и отнять 13% от кровно заработанных - иначе жди беды!

P.S. По-поводу юр/физ лица на маркете - напишите в поддержку гугла и они исправят это.


text:
Q: Create array of struct instances, then call function inside other struct passing array of objects (pointers) I've already posted a question in relation to a problem similar to what I can expect on my college exam and now this is another concrete issue I'm facing, probably due to lacking crucial understanding of pointers.
The problem has several structs defined.
One of them is struct Question{}, which has pointer attributes, and also an array which is to hold all the answers given for that particular question. At the destination, I should be able to iterate over all the questions in order to display them one by one to the user.
When I'm instantiating the exam (this is a simulation of an admission exam), I need to pass the student's citizen ID number, and the exam Questions.
// pi._prijavljeniKandidati[1]->_JMBG is the ID number in question
// 'questions' is supposed to carry all the questions I've hard-coded
// to save myself from entering manually

pi.StartExam(pi._prijavljeniKandidati[1]->_JMBG, questions);

This is how I tried it:
Question* questions = new Question;

// this initializes a single question
// 'answers' is the attribute that is holding all the answers
// the correct answer is BTW determined by an integer that is also
// sent in the below function

char* answers1[4];
answers1[0] = "London";
answers1[1] = "Berlin";
answers1[2] = "Helsinki";
answers1[3] = "Rome";

questions[0].Create("What is the capital of Finland?", answers1, 2);

// another question
char* answers2[3];
answers2[0] = "Ljubljana";
answers2[1] = "Paris";
answers2[2] = "Prague";

questions[0].Create("What is the capital of France?", answers2, 1);

And this is how the StartExam function actually looks like, nothing special here though, except that it shows how I tried getting some values of certain questions (based on the index thereof):
// I also tried void PokreniIspit(char* ID, Question* questions[])
void StartExam(char* ID, Question* questions)
{
    // this is just some dummy code line, to make sure it works
    cout << questions[1]._txtOfQuestion << endl;
}

When I run the app, the console crashes. Is there anything obvious that would make it crash?
For the sake of completeness, here's the whole Question structure:
// THIS IS HOW I IMAGING THIS STRUCT 'VISUALLY'
//= _txtOfQuestion ["Koji je glavni grad Njemacke?"]
//= _answers[10] //max 10 answers
//==== [0] Peking
//==== [1] London
//==== [2] Berlin
//==== [3] Seattle
//==== [4] Ljubljana
//= _posOfCorrect [2]
//= _points [4]

struct Question{

    char* _txtOfQuestion;
    char* _answers[4];
    int _posOfCorrect;
    int _points;

    void Unos(char* txt, char* answers[], int posCorrect, int points)
    {
        _txtOfQuestion= new char[strlen(txt) + 1];
        strcpy_s(_txtOfQuestion, strlen(txt) + 1, txt);

        for(int i = 0; i < 4; i++){
            _answers[i] = new char;
            strcpy_s(_answers[i], strlen(_answers[i]) + 1, _answers[i]);
        }

        _posOfCorrect = posCorrect;
        _points = points;

}

A: Thank you all for trying to help. Posting this question and going through all this code in order to translate from Bosnian to English helped me notice what was wrong.
Also, since I did initially try initializing Question like this:
Question* questions = new Question[2];

I'm back to using that because I do need array of questions.
But the real culprit (and cause for console to break) was the fact I had this for loop with the 4 hardcoded in it.
As soon as I made my second question contain 4 options/answers, just like the first one - it worked.
for (int i = 0; i < 4; i++){
    _odgovori[i] = new char;
    strcpy_s(_odgovori[i], strlen(odgovori[i]) + 1, odgovori[i]);
}

A: void Unos(const char* txt, const char* answers[], int posCorrect, int points)
{
    if (points < 4)
        points = 4; //max 4 answer possibilities

    _txtOfQuestion= new char[strlen(txt) + 1];
    strcpy_s(_txtOfQuestion, strlen(txt) + 1, txt);

    for(int i = 0; i < points; i++){
        _answers[i] = new char[strlen(answers[i]) + 1];
        strcpy_s(_answers[i], strlen(answers[i]) + 1, answers[i]);
    }
    _posOfCorrect = posCorrect;
    _points = points;
}

I changed a little bit:
Since you call the function with string literals, the type of this parameters should be const char*.
You should limit the points parameter (What happens if someone call it with 5 answers?).
The for loop should run from 0 to points. It would be undefined behaviour if it runs till 4 and there are only 3 answers.
You need an array of chars, not only 1 char to save the answer.
There were some typos in the for loop (answers is not the same as _answers).
I suggest to use std::string instead of char* and a std::vector or similar instead of the array.
You should call the function like:
questions[0].Create("What is the capital of Finland?", answers1, 2, 3);

there are only 3 answers, so you pass a 3 as last parameter.


text:
Q: How to create a new dataframe with values based on existing data frame and range from numeric vectors in R. I have a 96 x 48 dataframe df. The first column is an identifying field (char), columns 2 - 48 are numeric values. I also have two numeric vectors with 96 elements each, consisting of upper and lower bounds that correspond to each row.
I would like to create a new dataframe with an identical column 1, but for columns 2-48 I would like to see if the value is between the values in the two vectors for each row. Then I'd like to have 1 in the new data frame if it is, 0 if it is not (a boolean of sorts).
example:
df:

    1  2  3  4 .. 48
    a  7  11 15   58
    b  6  9  13   46
    c  8  14 20   73

vectors:

    upper: 24, 35, 22, 63
    lower: 10, 11, 12, 11

return:

    1  2  3  4 .. 48
    a  0  1  1    0   (between upper[1] and lower[1])
    b  0  0  1    0   (between upper[2] and lower[2])
    c  0  1  1    0   ...

I'd like to do this without a loop since I'm pretty sure there's a way to do this, but I can't seem to find it.

A: One method using dplyr:
# Data
df <- data.frame(id=letters[1:3], col2=c(7,6,8), col3=c(11,9,14), col4=c(15,13,20), col48=c(58,46,73))

# chain of operations
library(dplyr)
df %>%
  mutate(upper = c(24, 35, 22), lower = c(10, 11, 12)) %>%
  mutate_at(paste0("col", c(2:4, 48)), funs(.>=lower & .<=upper)) %>%
  mutate_at(paste0("col", c(2:4, 48)), as.integer) %>%
  select(-lower, -upper)

Output:
  col1 col2 col3 col4 col48
1    a    0    1    1     0
2    b    0    0    1     0
3    c    0    1    1     0

A: since you said that the other variables are numeric, then we can do:
ifelse(t(upper.bounds-t(df[-1])>0&lower.bounds-t(df[-1])<0),1,0)
     c2 c3 c4 c48
[1,]  0  0  1   0
[2,]  0  0  1   0
[3,]  0  1  1   0

There is no need of lapply or forloop
where the data:
df=read.table(text=" c1  c2  c3  c4 c48
    a  7  11 15   58
            b  6  9  13   46
            c  8  14 20   73
            ",h=T)

A: You can avoid an explicit for loop by using an implicit loop via lappy that loops over all columns. I think that loop is not critical from a performance point-of-view if you loop over the columns but only if you loop over the rows (since R stores the elements of a column as vector in continuous memory locations so that the performance is optimal but the elements of each row are spreaded over the memory locations which causes a performance penalty to loop over rows 1 by 1):
df <- data.frame(c1 = c(7, 6, 8), c2 = c(11, 9, 14), c3 = c(15, 13, 20), c48 = c(58, 46, 73))
df

lower.bounds <- c(10, 11, 12) # , 11)
upper.bounds <- c(24, 35, 22) # , 63)

res <- lapply(df, function(col) {ifelse(col >= lower.bounds & col <= upper.bounds, 1, 0)})
as.data.frame(res)
# c1 c2 c3 c48
# 1  0  1  1   0
# 2  0  0  1   0
# 3  0  1  1   0

A: Another option is to just use apply over columns. I think it is pretty simple and clean.
df <- data.frame(V2=c(7,6,8), V3=c(11,9,14), V4=c(15,13,20), V48=c(58,46,73))

upper <- c(24, 35, 22)
lower <- c(10, 11, 12)

data.frame(apply(df,2,function(x)((upper>=x)*(x>=lower))))
  V2 V3 V4 V48
  1  0  1  1   0
  2  0  0  1   0
  3  0  1  1   0

EDIT: After MKR comment, I became curious and had to test performance. If there is any suggestion on how to measure it in a different way, please comment.
df <- data.frame(V2=c(7,6,8), V3=c(11,9,14), V4=c(15,13,20), V48=c(58,46,73))

upper <- c(24, 35, 22)
lower <- c(10, 11, 12)

 start.time <- Sys.time()
 data.frame(apply(df,2,function(x)((upper>=x)*(x>=lower))))
  #V2 V3 V4 V48
  #1  0  1  1   0
  #2  0  0  1   0
  #3  0  1  1   0
 Sys.time()-start.time
  #Time difference of 0.0146079 secs

 start.time <- Sys.time()
 data.frame(apply(df,2,function(x)(as.numeric((upper>=x)&(x>=lower)))))
  #V2 V3 V4 V48
  #1  0  1  1   0
  #2  0  0  1   0
  #3  0  1  1   0
 Sys.time()-start.time
  #Time difference of 0.0124476 secs

 start.time <- Sys.time()
 data.frame(ifelse(upper > df[] & lower < df[], 1, 0))
  #V2 V3 V4 V48
  #1  0  1  1   0
  #2  0  0  1   0
  #3  0  1  1   0
 Sys.time()-start.time
  #Time difference of 0.008914948 secs

A: Another possible simpler solution could be:
    df <- data.frame(c1 = c(7, 6, 8),
                     c2 = c(11, 9, 14),
                     c3 = c(15, 13, 20),
                     c48 = c(58, 46, 73))

    lower.bounds <- c(10, 11, 12)
    upper.bounds <- c(24, 35, 22)

    ifelse(upper.bounds > df[] & lower.bounds < df[], 1, 0)
  # Result:
  #       c1 c2 c3 c48
  #  [1,]  0  1  1   0
  #  [2,]  0  0  1   0
  #  [3,]  0  1  1   0

OR
    as.data.frame(ifelse(upper.bounds > df[] & lower.bounds < df[], 1, 0))
  # Result:
  #
  #    c1 c2 c3 c48
  #  1  0  1  1   0
  #  2  0  0  1   0
  #  3  0  1  1   0


text:
Q: Random ActionView::Template::Error ( isn't precompiled): Randomly my app is giving the error: ActionView::Template::Error ( isn't precompiled): on one of my controller actions.
It was working fine earlier and then just stopped working. I haven't pushed to heroku or anything..
Any ideas on how to fix it?
Ive tried running heroku run rake assets:precompile with no luck.
I did however have this issue the other day, could it be related?
Full Error:
2013-11-19T04:44:35.306982+00:00 app[web.1]:     18:

2013-11-19T04:44:35.306982+00:00 app[web.1]:     19: <% @accounts.each do |a| %>
2013-11-19T04:44:35.306982+00:00 app[web.1]:     20:

2013-11-19T04:44:35.306982+00:00 app[web.1]:     21:        <%= image_tag a.image %> <%= a.name %> <% if a.verified == true %> <% end %>
2013-11-19T04:44:35.306982+00:00 app[web.1]:     22:
 <%= link_to "Purchase", "/#{a.permalink}" %> | <%= link_to "Visit twitter", a.url, :rel => 'nofollow', :target => "new" %>
2013-11-19T04:44:35.306982+00:00 app[web.1]:     23:        $<%= number_with_delimiter(a.price, :delimiter => ',') %>
2013-11-19T04:44:35.306982+00:00 app[web.1]:
2013-11-19T04:44:35.306982+00:00 app[web.1]: ActionView::Template::Error ( isn't precompiled):
2013-11-19T04:44:35.306982+00:00 app[web.1]:     24:        <% if a.retweets %>
2013-11-19T04:44:35.307215+00:00 app[web.1]:   app/views/market/_list.html.erb:19:in `_app_views_market__list_html_erb___3570010844875364888_70106042012700'
2013-11-19T04:44:35.307215+00:00 app[web.1]:
2013-11-19T04:44:35.307215+00:00 app[web.1]:   app/views/market/index.html.erb:1:in `_app_views_market_index_html_erb___4051548369069171146_70106041975580'

A: It looks like a.image is coming back nil or blank, so it is trying to find the asset "" and failing.


text:
Q: why is itunes not acknowledging my gift card credit? I have $50 of store credit to iTunes from gift cards for my birthday and when I go to buy anything it's trying to charge my debit card, not my iTunes gift cards.  is there something I have to do to change that or what?

A: https://support.apple.com/en-us/HT201209
That should answer your question. ;)


text:
Q: Xindy doesn't sort keywords properly I am preparing an index with entries that  use the International Phonetic Alphabet (which largely consists of lowercase Latin letters, but with additions. I have specified my desired sort order in an .xdy file. When xindy prepares the index, the groupings appear in my specified order. For instance, the 'ʌ' entries appear before the 'a' entries. But when sorting keys, the default sorting order occurs: aʌ appears after aa instead of before. (I've duplicated the sort order that appears in the code below.) Do I need to specify some further sorting rule?
xelatex
xindy -I latex -o xindy-ipa-sorting.ind -M ipa-alphabet xindy-ipa-sorting.idx
xelatex

xindy-ipa-sorting.tex:
\documentclass{book}
\usepackage{polyglossia}
\setmainfont{Times New Roman}
\usepackage{makeidx,lipsum}
\makeindex
\begin{document}
\lipsum[1]

\index{ʌa}
\index{ʌʌ}

\index{aa}
\index{aʌ}

\printindex
\end{document}

ipa.xdy (base on this answer):
;; xindy style file for an index with extended alphabet

(define-attributes (("default" "textbf" "textit" "hyperpage")))

;; "see" and "see also"

(define-crossref-class "see")
(markup-crossref-list :class "see" :open "\see{" :sep "; " :close "}{}")
(define-crossref-class "seealso")
(markup-crossref-list :class "seealso" :open "\seealso{" :sep "; " :close "}{}")

(markup-crossref-layer-list :sep ", ")

(require "base/numeric-sort.xdy")

(define-location-class "arabic-page-numbers" ("arabic-numbers"))
(define-location-class "roman-page-numbers"  ("roman-numbers-lowercase"))
(define-location-class "Roman-page-numbers"  ("roman-numbers-uppercase"))
(define-location-class "alpha-page-numbers"  ("alpha"))
(define-location-class "Alpha-page-numbers"  ("ALPHA"))

(define-location-class-order ("roman-page-numbers"
                  "Roman-page-numbers"
                  "arabic-page-numbers"
                  "alpha-page-numbers"
                  "Alpha-page-numbers"
                  "see"
                  "seealso"))

(require "lang/english/utf8.xdy")

(define-alphabet "latin-ipa"
("ʌ" "a" "b" "d" "dʒ" "e" "ɛ" "f" "ɡ" "ɣ" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "ʃ" "t" "tʃ" "u" "ʊ" "w" "x" "z" "ʒ" "ʔ"))
(define-letter-groups
("ʌ" "a" "b" "d" "dʒ" "e" "ɛ" "f" "ɡ" "ɣ" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "ʃ" "t" "tʃ" "u" "ʊ" "w" "x" "z" "ʒ" "ʔ"))

(define-letter-group "ʌ" :before "a")
(define-letter-group "dʒ" :after "d" :before "e")
(define-letter-group "ɛ" :after "e" :before "f")
(define-letter-group "ɣ" :after "ɡ" :before "h")
(define-letter-group "ʃ" :after "s" :before "t")
(define-letter-group "tʃ" :after "t" :before "u")
(define-letter-group "ʊ" :after "u" :before "w")
(define-letter-group "ʒ" :after "z" :before "ʔ")
(define-letter-group "ʔ" :after "ʒ" )

;; =======================
;; merge rules
;; =======================

;; LaTeX and TeX conventions

(merge-rule "\\LaTeXe *" "LaTeX2e" :eregexp :again)
(merge-rule "\\BibTeX *" "BibTeX" :eregexp :again)
(merge-rule "\\AmSTeX *" "AmSTeX" :eregexp :again)
(merge-rule "\\AmSLaTeX *" "AmSLaTeX" :eregexp :again)
(merge-rule "\\XeT *" "XeT" :eregexp :again)

(require "base/tex.xdy")

(markup-locref :open "\textbf{" :close "}" :attr "textbf")
(markup-locref :open "\textit{" :close "}" :attr "textit")
(markup-locref :open "\hyperpage{" :close "}" :attr "hyperpage")

;; =======================
;; sort rules
;; =======================

;; list pali capitals under pali lowercase

(sort-rule "g" "ɡ")

;;(sort-rule "Ā" "ā")
;;(sort-rule "Ṃ" "ṃ")
;;(sort-rule "Ī" "ī")
;;(sort-rule "Ñ" "ñ")

;; list latin capitals under latin lowercase

;;(sort-rule "A" "a")
;;(sort-rule "B" "b")
;;(sort-rule "C" "c")
;;(sort-rule "D" "d")
;;(sort-rule "E" "e")
;;(sort-rule "F" "f")
;;(sort-rule "G" "g")
;;(sort-rule "H" "h")
;;(sort-rule "I" "i")
;;(sort-rule "J" "j")
;;(sort-rule "K" "k")
;;(sort-rule "L" "l")
;;(sort-rule "M" "m")
;;(sort-rule "N" "n")
;;(sort-rule "O" "o")
;;(sort-rule "P" "p")
;;(sort-rule "Q" "q")
;;(sort-rule "R" "r")
;;(sort-rule "S" "s")
;;(sort-rule "T" "t")
;;(sort-rule "U" "u")
;;(sort-rule "V" "v")
;;(sort-rule "W" "w")
;;(sort-rule "X" "x")
;;(sort-rule "Y" "y")
;;(sort-rule "Z" "z")

;; ======================
;; markup rules
;; ======================

(require "base/page-ranges.xdy")

(markup-index :open
"\begin{theindex}
  \providecommand*\lettergroupDefault[1]{}
  \providecommand*\lettergroup[1]{%
      \par\textbf{#1}\par
      \nopagebreak
  }
"
          :close "~n~n\end{theindex}~n"
          :tree)

(markup-indexentry :open "~n  \item "           :depth 0)
(markup-indexentry :open "~n    \subitem "      :depth 1)
(markup-indexentry :open "~n      \subsubitem " :depth 2)

(markup-locclass-list :open ", " :sep ", ")
(markup-locref-list   :sep ", ")

;; letter group markup

(markup-letter-group-list :sep "~n~n  \indexspace~n")

(markup-letter-group :open-head "~n  \lettergroupDefault{" :close-head "}" :group "default")
(markup-letter-group :open-head "~n  \lettergroup{" :close-head "}")

A: It turns out that changing the keyword sorting order involves defining a new language. It's not sufficient to define new letter groups in a .xdy file. (Once you define the new language, however, you get the letter groupings for free, so that's something.)
I followed the procedure outlined in this answer, for Vietnamese. I'm going to include my code here, however, since it might be a little easier to follow than the Vietnamese diacritics, and the step of adding utf8-lang.xdy was new. Starting from the point in the answer where xindy-make-rules-0.2 has been downloaded and extracted...
In the xindy-make-rules-0.2/alphabets directory I created a new folder called ipa and then created utf8.pl.in with this content:
#!/usr/bin/perl

$language = "IPA";
$prefix = "ipa";
$script = "latin";

$alphabet = [
['ʌ',  ['ʌ']],
['a',  ['a']],
['b',  ['b']],
['d',  ['d']],
['dʒ',  ['dʒ']],
['e',  ['e']],
['ɛ',  ['ɛ']],
['f',  ['f']],
['ɡ',  ['ɡ', 'g']],
['ɣ',  ['ɣ']],
['h',  ['h']],
['i',  ['i']],
['j',  ['j']],
['k',  ['k']],
['l',  ['l']],
['m',  ['m']],
['n',  ['n']],
['o',  ['o']],
['p',  ['p']],
['q',  ['q']],
['r',  ['r']],
['s',  ['s']],
['ʃ',  ['ʃ']],
['t',  ['t']],
['tʃ',  ['tʃ']],
['u',  ['u']],
['ʊ',  ['ʊ']],
['w',  ['w']],
['x',  ['x']],
['z',  ['z']],
['ʒ',  ['ʒ']],
['ʔ',  ['ʔ']],
];

$sortcase = 'Aa';
#$sortcase = 'aA';

@special = ('?', '!', '.', 'letters', '-', '\'', '{', '}');

do 'make-rules.pl';

(This goes beyond the scope of my MWE above, but I think in a comprehensible way.)
I edited xindy-make-rules-0.2/alphabets/Makefile so that INSTDIR (line 7) reflected the location of my xindy installation (in my case "D:\Program Files (x86)\MiKTeX 2.9\xindy\modules\lang").
Then in the xindy-make-rules-0.2/alphabets directory I executed these commands:
make utf8
make install

Note: Although this worked at the time, when I tried the same commands recently, it would not build my file until I included myalphabet/utf8.xdy \ under the XDYSUTF8 list in xindy-make-rules-0.2/alphabets/Makefile (line 66 of my copy).
(Since I am a Windows user, I executed these commands using msys. Using mingw32-make did not work for me.)
For whatever reason, the script does not create a file that I found to be crucial. So, in the xindy/modules/lang/ipa directory, I had to create the file utf8-lang.xdy:
(require "lang/ipa/utf8.xdy")
(define-sort-rule-orientations (forward backward forward forward))
(use-rule-set :run 0
          :rule-set ("ipa-alphabetize" "ipa-ignore-special"))
(use-rule-set :run 1
          :rule-set ("ipa-resolve-diacritics" "ipa-ignore-special"))
(use-rule-set :run 2
          :rule-set ("ipa-resolve-case" "ipa-ignore-special"))
(use-rule-set :run 3
          :rule-set ("ipa-resolve-special"))

Note that this file requires ipa.xdy, which is the file provided in the question above.
So to recap, there should now be a subfolder called ipa in the xindy modules/lang folder (in my case "D:\Program Files (x86)\MiKTeX 2.9\xindy\modules\lang"), and that folder should contain three files: utf8.pl.in, utf8.xdy, and utf8-lang.xdy.
With that done, I am able to invoke xindy as follows:
xindy -L IPA -I latex -o example.ind -M ipa example.idx

ipa.xdy is a stripped-down version from my MWE above. The file now really just provides the basic options and the markup commands. There's nothing specific to the IPA alphabet.
;; xindy style file for an index with extended alphabet

(define-attributes (("default" "textbf" "textit" "hyperpage")))

;; "see" and "see also"

(define-crossref-class "see")
(markup-crossref-list :class "see" :open "\see{" :sep "; " :close "}{}")
(define-crossref-class "seealso")
(markup-crossref-list :class "seealso" :open "\seealso{" :sep "; " :close "}{}")

(markup-crossref-layer-list :sep ", ")

(require "base/numeric-sort.xdy")

(define-location-class "arabic-page-numbers" ("arabic-numbers"))
(define-location-class "roman-page-numbers"  ("roman-numbers-lowercase"))
(define-location-class "Roman-page-numbers"  ("roman-numbers-uppercase"))
(define-location-class "alpha-page-numbers"  ("alpha"))
(define-location-class "Alpha-page-numbers"  ("ALPHA"))

(define-location-class-order ("roman-page-numbers"
                  "Roman-page-numbers"
                  "arabic-page-numbers"
                  "alpha-page-numbers"
                  "Alpha-page-numbers"
                  "see"
                  "seealso"))

;; =======================
;; merge rules
;; =======================

;; LaTeX and TeX conventions

(merge-rule "\\LaTeXe *" "LaTeX2e" :eregexp :again)
(merge-rule "\\BibTeX *" "BibTeX" :eregexp :again)
(merge-rule "\\AmSTeX *" "AmSTeX" :eregexp :again)
(merge-rule "\\AmSLaTeX *" "AmSLaTeX" :eregexp :again)
(merge-rule "\\XeT *" "XeT" :eregexp :again)

(require "base/tex.xdy")

(markup-locref :open "\textbf{" :close "}" :attr "textbf")
(markup-locref :open "\textit{" :close "}" :attr "textit")
(markup-locref :open "\hyperpage{" :close "}" :attr "hyperpage")

;; ======================
;; markup rules
;; ======================

(require "base/page-ranges.xdy")

(markup-index :open
"\begin{theindex}
  \providecommand*\lettergroupDefault[1]{}
  \providecommand*\lettergroup[1]{%
      \par\textbf{#1}\par
      \nopagebreak
  }
"
          :close "~n~n\end{theindex}~n"
          :tree)

(markup-indexentry :open "~n  \item "           :depth 0)
(markup-indexentry :open "~n    \subitem "      :depth 1)
(markup-indexentry :open "~n      \subsubitem " :depth 2)

(markup-locclass-list :open ", " :sep ", ")
(markup-locref-list   :sep ", ")

;; letter group markup

(markup-letter-group-list :sep "~n~n  \indexspace~n")

(markup-letter-group :open-head "~n  \lettergroupDefault{" :close-head "}" :group "default")
(markup-letter-group :open-head "~n  \lettergroup{" :close-head "}")


text:
Q: Principal Value of $\iint_{-\infty}^{\infty}\text{Re} \Bigl( \frac{1}{\sqrt{(y_2+iy_1)^2-b^2}}\Bigr) e^{i(k_1y_1+k_2y_2)}\mathrm{d}y_1\mathrm{d}y_2$ Does the integral
\begin{align}
I = \iint_{-\infty}^{\infty}Re \left( \frac{1}{\sqrt{(y_2+iy_1)^2-b^2}} \right ) e^{i(k_1y_1+k_2y_2)}\mathrm{d}y_1\mathrm{d}y_2
\end{align}
with $b,y_1,y_2, k_1, k_2$ all real, have an analytical solution? I would also be interested in solutions involving generalised functions if the integral does not converge.
Using the fact that $Re(z) = \frac{z+\bar{z}}{2}$ and attempting to evaluate the $y_2$ integral first we have to solve an integral of the form
\begin{align}
I = \int_{-\infty}^{\infty} \frac{\cos{k_2y_2}}{\sqrt{y_2^2+(i2y_1)y_2-y_1^2-b^2}}  \mathrm{d}y_2
\end{align}
And consulting "Table of Integrals, Series, an Products" by Gradshteyn and Ryzhik the closest tabulated integral that comes close to helping me is a solution to
\begin{align}
I = \int_{0}^{\infty} (x^2+2\beta x)^{\nu-1/2}\cos(ax)  \mathrm{d}x
\end{align}
which has an analytical solution in terms of bessel and gamma functions. However this is as far as I get because of the missing constant under the square root sign...


text:
Q: Where can you find a list of unsubscribes? Once someone unsubscribes from a SFMC email where does that information go? I know I can go to All Subscribers and look for the particular individual but how can I just get a list of all the unsubscribes? We have a huge list of contacts (400k +). If I export all our subscribers and then sort it by subscriber status I can extract our unsubscribes, but like I said we have a huge list of contacts. Just exporting all our subscribers takes 20 minutes. Is there any fast, quick way to just look at the unsubscribes?
I have a vendor that needs our unsubscribes weekly. Is there a way to automate this?

A: The answer by Adam Spriggs on this post is most likely what you're looking for: ExactTarget list of unsubscribes this year


text:
Q: how to make a json on a json hi I have a question I want to create a bot that has luck wheel and the prizes is in a json file but the problem is that the bot will be in many servers.. so i wanted to know how to make like this :
{
  "example_of_server_id":{
                           "legandary luck":["first leg prize","second leg prize", "third leg prize],
                           "epic luck":["first epic prize", "second epic prize", "third epic prize"],
                           "normal luck":["first normal prize", "second normal prize", "third normal prize],
                           "bad luck":["first bad prize", "second bad prize", "third bad prize"]
}

and the bot do this all times that he enter in servers  but without the "first normal prize" and all things like he will do like: a [] after the bad and normal and epic and leg luck thx ! :D

A: I assume you use Python.
You can use the json library (beginner friendly version).
It will be something like this
import json

object_a = {"legandary luck": ["first leg prize", "second leg prize", "third leg prize"],
            "epic luck": ["first epic prize", "second epic prize", "third epic prize"],
            "normal luck": ["first normal prize", "second normal prize", "third normal prize"],
            "bad luck": ["first bad prize", "second bad prize", "third bad prize"]}
json_a = json.dumps(object_a)

object_b = {"server_id": json_a}
json_b = json.dumps(object_b)
print(json_b)

However, the better approach is to simply just put object_a into object_b directly so that you do not have to dumps them twice.
object_b = {"server_id": object_a}
json_b = json.dumps(object_b)


text:
Q: Why are the files not found I get ERR_FILE_NOT_FOUND Can anyone tell me why do the link tag not working? when i load it to the browser the console gives me an error saying

GET file:///C:/Users/hp/Desktop/template%201/index.html/css/leon.css net::ERR_FILE_NOT_FOUND??

<head>
<meta charset="UTF-8"/>
<title>leon template</title>
<!--main template css file-->
<link rel="styleSheet" href="css/leon.css">
<!-- render all elements normally -->
<link rel="stylesheet" href="css/normalize.css">
<!--font-->
<link rel="preconnect"  href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Work+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,200&display=swap" rel="stylesheet">
<!--css min file -->
<link rel="stylesheet" href="css/all.min.css" />

</head>

A: You provide wrong path, I don't know your structure but I guess your css folder is one above so it should be "../css/leon.css"


text:
Q: How can prove undefined type has only one value? After reading JavaScript Garden, I took notes as below but is it possible prove number 2. Please validate & correct my other proofs also.

*

*undefined is a type.

*undefined type has only one
value. that values is undefined.

*There is a global variable called
undefined

*global undefined variable has
default value undefined

*global undefined variable is not
a constant

*undefined is not a keyword

Proof (tested in firebug console)
1. typeof undefined \\undefined
 2. Need proof
 3. var name = undefined;  \\ global
    variable undefined is assigned to
    name
 4. alert(name); \\ undefined, that
    means undefined global variable has
    value undefined
 5. undefined = 'rajakvk';  \\ we can
    change value
 6. var undefined = 'rajakvk';  \\ no
    syntax error

var if = 'rajakvk';  \\ SyntaxError: missing variable name

Thanks http://w3fools.com/#what-should-be-done

A: You can prove it by looking at the language spec.  There is no test that you can run in an interpreter that will prove it.  Such a test would only be evidence that the interpreter is or is not conforming with the spec.  The spec is what defines "undefined."
Section 8.1 of the language spec says

8.1 The Undefined Type
The Undefined type has exactly one value, called
  undefined. Any variable that has not
  been assigned a value has the value
  undefined.

And there is exactly one tyoe for which typeof will return "undefined".  From section 11.4.3 of the spec:
Table 20 — typeof Operator Results
Type of val                                          Result
Undefined                                            "undefined"
Null                                                 "object"
Boolean                                              "boolean"
Number                                               "number"
String                                               "string"
Object (native and does not implement [[Call]])      "object"
Object (native or host and does implement [[Call]])  "function"
Object (host and does not implement [[Call]])        Implementation-defined except may not be "undefined", "boolean", "number", or "string".

A: The correct proof is:
undefined = 1;
alert(typeof undefined !== 'undefined'); // need to be true

It need to be true, because you've changed the undefined variable value to anything different from undefined type.


text:
Q: How to export my domain cert from AWS Certificate Manager for import into Java keystore? I purchased the domain name 'jimtough.org' directly from Amazon so I could use it with a Cloudfront distribution. Now I have a very simple vanity site at https://jimtough.org/ that uses the certificate. I also played around with AWS API Gateway and confirmed that I can use the same certificate to provide HTTPS secured URLs to work with API Gateway.
I am also running a Java/Spring Boot web application on an EC2 server. I have already associated a Route53 DNS name with the EC2 server that hosts my Spring Boot application, like this: http://instance-b.jimtough.org/. This works, but it is using unsecured HTTP. I get a bunch of warnings when I try to do basic authentication in the application, since it would be sending my username/password via an insecure connection. Fair enough.
So my next step is to enable HTTPS in Spring Security and force secure connections to the application. In order to do this, I first need to provide a certificate for the Java runtime on the EC2 host to use. I found examples of how to do so with a self-signed certificate:

*

*https://mkyong.com/spring-boot/spring-boot-ssl-https-examples/

*https://www.baeldung.com/spring-boot-https-self-signed-certificate
Unfortunately, using a self-signed certificate is not what I'm looking for. I want the user to be able to browse my static content vanity site first (https://jimtough.org/), and then follow a link to my web app and keep using the same site certificate (my AWS-issued cert) for my Spring web app.
QUESTION: How can I use my AWS-issued certificate with my Java-based web application?
Inside the AWS Certificate Manager (https://console.aws.amazon.com/acm/home?region=us-east-1#/), I don't see any way to 'export' or save my certificate. Am I missing something? Maybe Amazon doesn't want me to use this certificate outside of their own services?
Note that I did originally set up the certificate with the domain name as 'jimtough.org' and the Additional Names field set to '*.jimtough.org' so I can use the certificate on sub-domains as I'm trying to do here.

EDIT
The accepted answer from julien-b is correct. I did some more research and found that SSL certificates aren't cheap, and come in different flavors. The cheapest is the 'DV' (Domain Validation) type, which only verifies that the SSL certificate is controlled by someone who also controls the DNS record for the associated domain (such as 'mydomain.com'). There are much more thorough (and expensive) certificate types that can be issued, where the issuer has to do background checks on the owning organization. Those are meant for sites that handle e-commerce, financial transactions, etc. Not at all what I need.
There are also multiple types of multi-site certificates to choose from. The very cheapest single-domain certificates only cover your primary domain and the 'www' subdomain (mysite.com and www.mysite.com). If you want all the subdomains of your primary domain covered (app.mysite.com, ftp.mysite.com, etc), then you'll need a 'wildcard' certificate. Those are significantly more expensive. The more exotic certificate types can cover multiple different domains. These seem to be aimed at making certificate management easier for organizations that manage a lot of different domains and don't need a different certificate for each. Not what I need, so I didn't investigate further.
I decided to go with a 'single-domain with subdomain wildcard' certificate from Comodo (recently renamed to Sectigo?), who appears to be the most affordable certificate vendor right now.
REFERENCE: https://www.techradar.com/news/best-ssl-certificate-provider
It seems like a missed opportunity for Amazon that they don't get in on this game and issue their own SSL certificates for a fee. AWS already has all the infrastructure in place to do so, at least for the DV-level certificates.

A: You cannot export the private key of a publicly trusted ACM certificate. You can use ACM certificates with some managed services, but it doesn't work for all use cases.
https://docs.aws.amazon.com/acm/latest/userguide/export-private.html

AWS Certificate Manager is integrated with other AWS services, so you
can provision an SSL/TLS certificate and deploy it with your Elastic
Load Balancer, Amazon CloudFront distribution or API in Amazon API
Gateway. AWS Certificate Manager also works with AWS Elastic Beanstalk
and AWS CloudFormation for public email-validated certificates to help
you manage public certificates and use them with your applications in
the AWS Cloud.

https://aws.amazon.com/certificate-manager/features/?nc=sn&loc=2
Should you want to use a certificate on a service that is not integrated with ACM or even on-premise, you should get your certificate from another source.
As for the ACM Private CA, it is meant to be used within an organization thus not matching your use case.
https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaWelcome.html


text:
Q: How to use Google Ad Manager in Ionic 6 I'm developing a project with ionic 6 Angular and I'm trying to integrate ad manager.
My client needs it to be able to place personalized advertisements.
Is there any solution?
I only found the AdMob plugin for ionic native but i can't figure out if this tool allows me to do that.
AdMob Plugin