text:
Q: sql, не видит строки при условии со знаком = При запросе
SELECT * FROM base_stock_cloth_rol WHERE rol_count='39.8'
получаю ответ MySQL вернула пустой результат (т.е. ноль строк) Screanshort1
А при запросе
SELECT * FROM base_stock_cloth_rol WHERE rol_count>'39'

получаю в ответ уже не пустой запрос Отображение строк 0 - 16 Screanshort2
P.S.   тип столбца rol_count - float
P.S.2  без ' ' тоже пробовал результат всё равно пустой

A: В базе, скорее всего, хранится число только приблизительно равное 39.8. Если тип колонки - четырех-байтный float, число 39.8 просто не может быть выражено абсолютно точно этим типом данных. Вам придется компоновать условие вида:
... WHERE rol_count > 39.799 AND rol_count < 39.801

или
... WHERE ABS(rol_count - 39.8) < 0.001


text:
Q: VerloopSdk integration with React-Native Trying to integrate verloop with react-native using react-native-sdk. Getting undefined when calling function VerloopSdk.showChat();
import React, {Component} from 'react';
import VerloopSdk from 'react-native-verloop-sdk';
export default class VerloopLiveChat extends Component {
async componentDidMount() {
    const clientId = "<YOUR COMPANY ID>"; // it is same as https://<YOUR COMPANY ID>.verloop.io
    await VerloopSdk.createAnonymousUserConfig(clientId);
    //or
    await VerloopSdk.createUserConfig(clientId, userId);

    //optional
    VerloopSdk.putCustomField(key, value);
    //optional
    VerloopSdk.setRecipeId(recipeId);
    //optional
    VerloopSdk.setUserEmail(email);
    //optional
    VerloopSdk.setUserPhone(phoneNumber);
    //optional
    VerloopSdk.setUserName(name);

    VerloopSdk.showChat();
}

render() {
    return null;
}

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Одноименные методы с различными возвращаемыми значениями Есть ли способы использовать одноименные методы с одинаковыми входными параметрами, но различными возвращаемыми значениями?
Допустим есть методы
public string use_reflection (string param)
{
}
public list<string> use_reflection (string param)
{
}

В методе я использую механизм рефлексии для вызова других методов по их имени
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod("тут имя метода");
answer = theMethod.Invoke(this, params_obj)

Соответственно различные методы возвращают различные по типам результаты, так как в C# возвращаемое значение не является сигнатурой метода, то для описанного алгоритма придется создавать методы аналогичные use_reflection для каждого типа возвращаемого результата или есть способы обойти это?

A: Например, так:
class Base
{
    public string use_reflection(string param)
    {
        return "";
    }
}

class Derived : Base
{
    new public List<string> use_reflection(string param)
    {
        return null;
    }
}

Доступ либо через явный каст
var d = new Derived();
List<string> r1 = d.use_reflection(null);
string r2 = ((Base)d).use_reflection(null);

либо через рефлексию:
var methods = typeof(Derived).GetMethods(BindingFlags.Instance | BindingFlags.Public)
                             .Where(mi => mi.Name == "use_reflection");
foreach (var mi in methods)
    Console.WriteLine(mi.ReturnType);

A: Я менее ООПшный вариант предложу. Для возврата значения из метода используем out-параметры. А потом дергаем метод через рефлексию:
class MethodsContainer
{
    public void Method(string param, out string result)
    {
        result = "Hello, world!";
    }
    public void Method(string param, out List<string> result)
    {
        result = new List<string>();
    }
}

static T CallMethodFromContainer<T>(MethodsContainer container, string param)
{
    object[] arguments = new object[] { param, default(T) };

    typeof(MethodsContainer)
        .GetMethod("Method", new Type[] { typeof(string), typeof(T).MakeByRefType() })
        .Invoke(container, arguments);

    return (T)arguments[1];
}

Ну и использование:
var result = CallMethodFromContainer<List<string>>(container, "param");


text:
Q: Live TeXing while taking notes How do you go about taking notes in class? I have a moderate typing speed of about 60 wpm, but I find myself unable to keep up with my class many times getting distracted by the formatting a lot. Is there any editor that quickly allows one to do this? I find it a hassle to type
\begin{equation}
\end{equation}

every time, so is there any way to quicken this process. I know there are some editors that allow you to do this, but I don't know which ones in particular.
Thanks.
EDIT: If it is important, I run the latest version of OS X on an old Mac. Not sure if that is important, but just in-case there are software issues.

A: Typora as mentioned by Erwan Grelier is an excellent choice, and would probably my first choice.
There is also Caret, live previews of math feels a little buggy / can take a while to show sometimes (i.e. Typora feels a little better on that front), but it has a really nice Go To Heading... feature where you can instantly fuzzy search the whole document for any level markdown heading, so navigation is super quick. I sometimes use Caret to search/navigate existing notes for this feature alone.
When that is all said, I would definitely also recommend to use pen and paper in-class and type it up afterwards. Handwriting seems to help both learning and memorization, and seeing the material multiple times, i.e. giving it at least a second pass, is a good idea anyway. Nothing beats handwriting for in-class notes IMO.

A: I know TeXstudio has a lot of keyboards shortcuts both embedded and customizable (ctrl + shift + N for a new equation environment), but personally for typing notes in class I use Typora, a Markdown software enabling the quick formating of documents including LaTeX, with live preview, it also could suits your needs.


text:
Q: declare obj-c class interface that contain c++ class type ivar Currently I am working on a cocos2d+Box2D project so I have deal with some Objective-C++ code.
And I am facing to such situation:
#import "cocos2d.h"
#import "Box2D.h"

@interface BasicNode : CCNode {
@private
    ccColor3B _color;
    b2Body *_body;
    b2Fixture *_shape;
}

b2Body and b2Fixture are C++ class that defined in Box2D.h
It works if the implementation of BasicNode is named BasicNode.mm.
But if I have another file named Game.m that is using BasicNode and import BasicNode.h, it won't compile because .m file is Obj-C file and does not know about C++ code.
So I decided to move #import "Box2D.h" into implementation file and only keep type declaration in head file (this is exactly what header file should contain).
But how do I do it? They are C++ class type but they are actually just a pointer so I wrote some helper macro
#ifdef __cplusplus
#define CLS_DEF(clsname) class clsname
#else
#define CLS_DEF(clsname) struct clsname; typedef struct clsname clsname
#endif

CLS_DEF(b2Body);
CLS_DEF(b2Fixture);

It works, only if CLS_DEF(b2Body) is appear once only. Otherwise compiler will find multiple type declaration for a same name even they are the same. Than I have to change to
#ifdef __cplusplus
#define CLS_DEF(clsname) class clsname
#else
#define CLS_DEF(clsname) @class clsname
#endif

And it is working now.
But I don't think it is a great idea that I declare a C++ class type as an Obj-C class especially I am using ARC.
Is any better way do deal with it? And I don't really want to make something like this
@interface BasicNode : CCNode {
@private
    ccColor3B _color;
#ifdef __cplusplus
    b2Body *_body;
    b2Fixture *_shape;
#else
    void *_body;
    void *_shape;
#endif
}

Edit: Also please tell me will my tweak way introduce any problem?? by making C++ class ivar looks like Obj-C class for other pure Obj-C code.

A: One simple solution is to rename Game.m to Game.mm.

A: There are a couple of ways. If you can rely on using the Objective-C 2.2 runtime's features, you can add ivars in class (category) extensions. This means you can add ivars in your class's .mm file, and keep the .h file clean of any C++ stuff.
If you need to support older versions of the runtime, there are a few ways to do it which are better than #ifdefing. In my opinion, the best way is to use the 'pimpl' idiom which is common in C++ - you forward declare an implementation struct in your header, and add an ivar which is a pointer to such a struct. In your class's implementation (.mm), you actually define that struct with all its C++ members. You then just need to allocate that implementation object in your init... method(s) with new and delete it in dealloc.
I've written up the pimpl idiom as it applies to cleanly mixing Objective-C and C++ in this article - it also shows some other potential solutions which you could consider.

A: With Xcode 5, you don't have to declare instance variables in the header file, you can just declare them in the implementation file. So your BasicNode header file is not "contaminated" with C++.
You can use "struct" instead of "class" in C++. The only difference is that in a class all members are private by default, while in a struct they are public by default. But you can do everything with a struct that you can do with a class. That way you can write for example
struct b2Body;
struct b2Fixture;

outside your interface, and
{ ...
    struct b2Body* _body;
  ...
}

in your interface.


text:
Q: Kafka deployment on minikube Hi i am new to kubernets, i am using minikube single node cluster for local development and testing.
Host: Ubuntu 16.04 LTS.
Minikube: Virtual box running minikube cluster

My requirement is i need to deploy kafka and zookeeper on minikube and should be used to produce or consume messages.
I followed this link and successfully deployed it on minikube its details are below
$ kubectl get services
NAME            CLUSTER-IP   EXTERNAL-IP   PORT(S)                      AGE
kafka-service   10.0.0.15    <pending>     9092:30244/TCP               46m
kubernetes      10.0.0.1     <none>        443/TCP                      53m
zoo1            10.0.0.43    <none>        2181/TCP,2888/TCP,3888/TCP   50m
zoo2            10.0.0.226   <none>        2181/TCP,2888/TCP,3888/TCP   50m
zoo3            10.0.0.6     <none>        2181/TCP,2888/TCP,3888/TCP   50m

$ kubectl get pods
NAME                                      READY     STATUS    RESTARTS   AGE
kafka-deployment-3583985961-f2301         1/1       Running   0          48m
zookeeper-deployment-1-1598963595-vgx1l   1/1       Running   0          52m
zookeeper-deployment-2-2038841231-tdsff   1/1       Running   0          52m
zookeeper-deployment-3-2478718867-5vjcj   1/1       Running   0          52m

$ kubectl describe service kafka-service
Name:           kafka-service
Namespace:      default
Labels:         app=kafka
Annotations:    <none>
Selector:       app=kafka
Type:           LoadBalancer
IP:             10.0.0.15
Port:           kafka-port  9092/TCP
NodePort:       kafka-port  30244/TCP
Endpoints:      172.17.0.7:9092
Session Affinity:   None
Events:         <none>

and i have set KAFKA_ADVERTISED_HOST_NAME to minikube ip(192.168.99.100).
Now for message producer i am using $cat textfile.log | kafkacat -b  $(minikube ip):30244 -t mytopic its not publishing the message giving below message
% Auto-selecting Producer mode (use -P or -C to override)
% Delivery failed for message: Local: Message timed out

can any one help how to publish and consume message.

A: I know that this is quite an old post. Were you able to resolve and run kafka + zookeeper within minikube? I was able to run a simple single cluster kafka and zookeeper deployment successfully using minikube v0.17.1 and produce and consume messages using kafkacat producer and consumer respectively. I was able to run these successfully on uBuntu and Mac OSX. The deployment and service yamls are as below:
zookeeper-deployment.yml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    app: zookeeper
  name: zookeeper
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: zookeeper
    spec:
      containers:
      - image: wurstmeister/zookeeper
        imagePullPolicy: IfNotPresent
        name: zookeeper
        ports:
        - containerPort: 2181

zookeeper-service.yml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: zookeeper-service
  name: zookeeper-service
spec:
  type: NodePort
  ports:
  - name: zookeeper-port
    port: 2181
    nodePort: 30181
    targetPort: 2181
  selector:
    app: zookeeper

kafka-deployment.yml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    app: kafka
  name: kafka
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: kafka
    spec:
      containers:
      - env:
        - name: KAFKA_ADVERTISED_HOST_NAME
          value: "192.168.99.100"
        - name: KAFKA_ADVERTISED_PORT
          value: "30092"
        - name: KAFKA_BROKER_ID
          value: "1"
        - name: KAFKA_ZOOKEEPER_CONNECT
          value: 192.168.99.100:30181
        - name: KAFKA_CREATE_TOPICS
          value: "test-topic:1:1"
        image: wurstmeister/kafka
        imagePullPolicy: IfNotPresent
        name: kafka
        ports:
        - containerPort: 9092

kafka-service.yml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: kafka-service
  name: kafka-service
spec:
  type: NodePort
  ports:
  - name: kafka-port
    port: 9092
    nodePort: 30092
    targetPort: 9092
  selector:
    app: kafka

You can test your deployment by installing kafkacat client and running the following commands on separate terminal windows:
echo "Am I receiving this message?" | kafkacat -P -b 192.168.99.100:30092 -t test-topic
kafkacat -C -b 192.168.99.100:30092 -t test-topic
% Reached end of topic test-topic [0] at offset 0
Am I receiving this message?
I was able to successfully run this on minikube versions v0.17.1 and v0.19.0. If you want to run this on minikube versions v0.21.1 and v0.23.0, please refer to my reply to the post here: Kafka inaccessible once inside Kubernetes/Minikube
Thanks.

A: I followed as shown below.
$ git clone https://github.com/d1egoaz/minikube-kafka-cluster

$ cd minikube-kafka-cluster

$ kubectl apply -f 00-namespace/

$ kubectl apply -f 01-zookeeper/

$ kubectl apply -f 02-kafka/

$ kubectl apply -f 03-yahoo-kafka-manager/

$ kubectl get svc -n kafka-ca1 (get the port of kafka manager like 31445)

$ minikube ip

Put  http://minikube-ip:port in browser to get ui page of kafka manager.
source https://technology.amis.nl/2019/03/24/running-apache-kafka-on-minikube/

A: You used a service with type = LoadBalancer which is used for cloud provider (you can see the service waiting for an external ip address .. pending state ... which will never happen). In your case you should try with NodePort.

A: Going off the previous answer and your comment here is very basic sample code for a Kafka service with type=Nodeport.
apiVersion: v1
kind: Service
metadata:
  name: kafka-service
  labels:
    name: kafka
spec:
  ports:
  - port: 9092
    name: kafka-port
    protocol: TCP
  selector:
    app: kafka
  type: NodePort


text:
Q: How to Change jdbc schema users with mytable in OAuth2 spring boot I have to change the name of default schema users with mytable name.

    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private AuthenticationManager authenticationManager;

        @Autowired
        private PasswordEncoder passwordEncoder;

        @Autowired
        private DataSource dataSource;

        @Bean
        TokenStore jdbcTokenStore() {
            return new JdbcTokenStore(dataSource);
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.tokenStore(jdbcTokenStore());
            endpoints.authenticationManager(authenticationManager);
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.jdbc(dataSource);
        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
            security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
        }

    }

this is my securityConfig class

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public UserDetailsService userDetailsService(DataSource dataSource) {
        JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
        jdbcUserDetailsManager.setUsersByUsernameQuery("select USER_LOGIN_ID,USER_PASSWORD "
                + "from MY_TABLE "
                + "where USER_LOGIN_ID = ?");

        return jdbcUserDetailsManager;
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Bean
    GrantedAuthorityDefaults grantedAuthorityDefaults() {
        return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
    }
}

this is my resouceserver

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/secure").authenticated();
    }

}

and i have create customer table here
which ius here
@Entity
@Table(name = "MY_TABLE")
public class MyTable {

    @Column(name = "USER_LOGIN_ID", nullable = false, unique = true)
    private String userLoginId;
    @Column(name = "USER_PASSWORD", nullable = false)
    private String userPassword;
}

here url which i use.
http://localhost:8081/oauth/token?grant_type=password&username=user&password=user
and it is throwing error
{
"timestamp": 1621689938591,
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/oauth/token"
}

A: To use your own table you have to authenticationmanager to read user from that table like below. It should be able to provide user and authority details.
You can create your own configuration class which extends WebSecurityConfigurerAdapter and override configure method like below.
 @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                   .dataSource(dataSource)
                   .usersByUsernameQuery("select userid,password,enabled "
                     + "from yourtable"
                     + "where userid = ?")
                   .authoritiesByUsernameQuery("select userid,authority "
                    + "from yourauthoritytable"
                    + "where userid= ?");
    }

A: In addition to @berzerk answer, you can use a more modern approach instead of using the AuthenticationManagerBuilder.
You can provide your own UserDetailsService bean with your custom queries.
@Bean
public UserDetailsService userDetailsService(DataSource dataSource) {
    JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
    jdbcUserDetailsManager.setUsersByUsernameQuery("select username,password,enabled "
                + "from mytable "
                + "where username = ?");

    return jdbcUserDetailsManager;
}

Note that if you have changed the authorities table or any other table that JdbcUserDetailsManager uses by default, you should change the queries the same way that was done with setUsersByUsernameQuery
You can also refer to the Spring Security docs for more details about the UserDetailsService custom implementations.


text:
Q: What way can be used to discover discrepancies in a PDO query? I have the following

*

*A multidimensional array encoded as JSON. Each index holds exactly 80 keys

*A CSV file with 80 items representing identical keys in the indexes above since dumping them in the same script will be too cumbersome

First, I mutate the original keys in the JSON array to use underscores since named placeholders don't accept that
foreach ($content as $key => &$bulk) {

    $vals = array_values($bulk);

    $keys = array_map(function ($item) {

    $item = str_replace(' ', '_', $item);

    return ":$item"; // semi-colons are redundant but I tried it also to be on the safe side

    }, array_keys($bulk));

    $bulk = array_combine($keys, $vals);

    // add date to each fixture
    $bulk[':date'] = date('Y-m-d');
}

Then I do the exact same thing for items in the CSV file and convert them to what can be used in the actual query
// swap out spaces
array_walk($validColumns, function (&$val) {

    $val = str_replace(' ', '_', $val);
});

// prepare named placeholders
$transform = array_map(function ($val) {

    return ":$val";
}, $validColumns);

$placeholders = implode(',', $transform);

$validColumns = array_map(function ($val) {

    return "`$val`";
}, $validColumns);

After this, I build the query using the following string
$query = 'INSERT INTO container (' . implode(',', $validColumns) . ") VALUES ($placeholders)";

And attempt to execute with this
try {

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $conn->beginTransaction();

    $transaction = $conn->prepare($query);

    foreach ($content as $key => $bulk) {

        if (!is_array($bulk)) $bulk = [$bulk];

        var_dump(array_diff($transform, array_keys($bulk))); // this returns an empty array even when I swap the arguments

        $transaction->execute($bulk);
    }

But it keeps throwing the dreaded error SQLSTATE[HY093]: Invalid parameter number: parameter was not defined'. My question is how may I know what keys I'm missing, from the nested array_diff in the foreach?
When I var_dump the lengths, they both return 80. Same with the placeholder values. I have also tried using the object keys without adding the semi-colon but the issue persists.
Are there any additional tools I can use to detect why it relentlessly throws the error as per what the inconsistency is--whether it can't find a matching placeholder or if there are more values than placeholders?
I have scoured every single SO thread with this error down to the 16th search result and every time, someone posts his query and bound parameters but in my case where I have 80 length arrays and 80 length cryptic compound-word strings representing keys, that will be an effective way to deter anyone from trying to help.


text:
Q: I need to create the sum of next 7 days values of a column in r.The sum should be grouped by another column which has string values I need to create the sum of next 7 days values of a column in r.The sum should be grouped by another column which has string values
Example
name   value
a       2
a       3
a       3
b       4
b       3
b       2
b       1
b       3

sum by 2 next rows
output
sum
5
6
3
7
5
3
4
3

A: You can use lead() and lag() to reference the next and prior values.
This code sums the current and the next, grouped by the string values:
library(dplyr)

df <- data.frame(stringsAsFactors=FALSE,
          V1 = c("a", "a", "a", "b", "b", "b", "b", "b"),
          V2 = c(2L, 3L, 3L, 4L, 3L, 2L, 1L, 3L)
)

df

df %>%
  group_by(V1) %>%
  mutate(sum_forward = dplyr::lead(V2) + V2)

And this is the output. The NAs are there because on the last day, there is no next day to sum with.
  V1       V2 sum_forward
  <chr> <int>       <int>
1 a         2           5
2 a         3           6
3 a         3          NA
4 b         4           7
5 b         3           5
6 b         2           3
7 b         1           4
8 b         3          NA

A: The zoo package is esp designed for such tasks.
library(zoo)

df1$new <- unlist(tapply(df1$value, factor(df1$name), function(x){ zoo::rollsum(x, 2, align = "left", fill = x[length(x)]) }))

#> df1$new
#[1] 5 6 3 7 5 3 4 3

df1 <- data.frame(stringsAsFactors=FALSE,
                  name = c("a", "a", "a", "b", "b", "b", "b", "b","c","d","d","d"),
                  value = c(2L, 3L, 3L, 4L, 3L, 2L, 1L, 3L, 4L, 1L:3L)
)

windowSize = 3

df1$new <- unlist(
    tapply(df1$value, factor(df1$name),function(x){
        IND <- (length(x)-(windowSize-2)):length(x);IND = IND[IND > 0]
        c(  zoo::rollsum(x, windowSize, align = "left"), rev(cumsum(rev(x[IND])))  )})
    )

This was a little bit tricky to do:
Here is the formula in respect to a given windowSize.


text:
Q: convert ISO_String date (different format) time into epoch time I am getting time in iso_string format, not completely iso_string but something like this : 20180410T11:55:37+0000
I know that there should be two hyphens in the above date but I'm getting this from my Spring service that returns Java toLocaleDate().format(Date.ISO_String)
date.
I tried to convert this format using new Date('20180410T11:55:37+0000').getTime()
But I got NaN
Is there any way to get this date converted into epoch in javascript so that I can easily use it in my front-end service?

A: If you know that the format will be like this then you could fix it before you create the Javascript Date object.
var rawDate = "20180410T11:55:37+0000";
var newRawDate = `${rawDate.slice(0, 4)}-${rawDate.slice(4, 6)}-${rawDate.slice(6)}`;
// ^^ Using ES6 templating - use string concatenation if this isn't going to be available
var date = new Date(newRawDate);
// Tue Apr 10 2018 12:55:37 GMT+0100 (BST)


text:
Q: Working with nested json file visual basic i have a nested json file that i want to deserialize, i keep getting an error " Object reference not set to an instance of an object."
here is my json file
[
{
    "Name": "Junius",
    "LastName": "Lekgwara",
    "CellNo": [
        {
            "CellC": "072685345",
            "Voda": "0728589303"
        }
    ]
},
{
    "Name": "Phuti",
    "LastName": "Gravel",
    "CellNo": [
        {
            "CellC": "08377777777",
            "Voda": "089888888888"
        }
    ]
},
{
    "Name": "Donald",
    "LastName": "Gravel",
    "CellNo": [
        {
            "CellC": "0791408989",
            "Voda": "0117689009"
        }
    ]
  }
]

here is my Person class
Public Class Person
Private _Name As String
Public Property Name() As String
    Get
        Return _Name
    End Get
    Set(ByVal value As String)
        _Name = value
    End Set
End Property
Private _LastName As String
Public Property LastName() As String
    Get
        Return _LastName
    End Get
    Set(ByVal value As String)
        _LastName = value
    End Set
End Property
Public Property cellno As CellNo
End Class

Public Class CellNo
Public Property CellC As String
Public Property Voda As String

End Class

PersonList class
Public Class PersonList
Private _ListPerson As List(Of Person)
Public Property ListPerson() As List(Of Person)
    Get
        Return _ListPerson
    End Get
    Set(ByVal value As List(Of Person))
        _ListPerson = value
    End Set
End Property
Sub New()
    _ListPerson = New List(Of Person)
End Sub
End Class

reading json file, when this sub is called i get an error
 Public Async Sub LoadFromFile()
    Dim reader As String = Await GetFile()
    Dim serializer As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(ObservableCollection(Of Person)))
    Dim ms As MemoryStream = New MemoryStream(Encoding.UTF8.GetBytes(reader))
    Dim listOf As ObservableCollection(Of Person) = New ObservableCollection(Of Person)
    listOf = serializer.ReadObject(ms)
    For Each item In listOf
        list.ListPerson.Add(item)
        Debug.WriteLine(item.Name + " " + item.LastName + " " + item.cellno.CellC + " " + item.cellno.Voda) 'Object reference not set to an instance of an object, on item.cellno.CellC and item.cellno.Voda
    Next
End Sub

i want to be able to reference it like
Dim person As Person = New Person()
lblName.Text = person.Name
lblLastName.Text = person.LastName
lblCellCNo.Text= person.cellno.CellC
lblCellVodaNo.Text= person.cellno.Voda

how can i fix this?

A: The JSON shown is a bit different than the class structs you want to use.  Person is a List or Array already in the JSON.  CellNo is also an array even though it appears in that sample to only have one class object per person.
So, you can skip your PersonList entirely:
Public Class CellNo
    Public Property CellC As String
    Public Property Voda As String
End Class

Public Class Person
    Public Property Name As String
    Public Property LastName As String
    Public Property CellNo As List(Of CellNo)
End Class

Deserialize to a List(Of Person):
Dim jstr = ... (wherever it comes from)

Dim jp As List(Of Person)
jp = JsonConvert.DeserializeObject(Of List(Of Person))(jstr)

This is now quite usable as is without further manipulations:
For Each P As Person In jp
    Console.WriteLine("{0}  Cell Voda:{1}", P.Name, P.CellNo(0).Voda)
Next

Junius  Cell Voda: 0728589303
  Phuti  Cell Voda: 089888888888
  Donald  Cell Voda: 0117689009

Optionally, you can deserialize to an array of Person, and define Person.CellNo as an array also.

i'm not using newtonsoft
You get the same results using NET:
Imports System.Web.Script.Serialization

Dim jss As New JavaScriptSerializer
Dim jp As List(Of Person)

jp = jss.Deserialize(Of List(Of Person))(jstr)

A: See.. your problem is that
the item List is not well prepared for what you want.
 item.cellno HAS CHILD !!!

and
 item.cellno.CellC
 item.cellno.Voda

must be iterated..
 For Each item In listOf
    list.ListPerson.Add(item)
    'Debug.WriteLine(item.Name + " " + item.LastName + " " + _

   'you know that you have just 2 items in : CellNo, and play with that.
   For i= 0 to 1
      Item.CellNo(i) ' do something with ..
   End For

Next

also read this : vb.net datatable Serialize to json

A: Solved the problem by using CellNo as an array
 `"CellNo":[
             "072685345",
             "0728589303"
           ]

   For Each item In listOf
        list.ListPerson.Add(item)
        Debug.WriteLine(item.Name + " " + item.LastName)
        For Each i In item.CellNo
            Debug.WriteLine(i)
        Next
    Next

display

Junius Lekgwara
  Cell No: 072685345
  Cell No: 0728589303
Phuti Gravel
  Cell No: 08377777777
  Cell No: 089888888888
Donald Gravel
  Cell No: 0791408989
  Cell No: 0117689009


text:
Q: Rails 3 Routing Constraint and Regex I'm looking to match the pattern state/city in the path, unless the state variable equals "auth"
match '/:state/:city' => 'cities#index', :as => :state_cities, :constraints => {:state => /(?!auth)/ }

For example, mydomain.com/fl/miami is good. mydomain.com/auth/twitter is bad.
I am using omniauth and it requires that you go to /auth/twitter for authentication, however it is nowhere to be found when I type rake routes.

A: Based on mu is too short's comments, here is the answer I've come up with:
match '/:state/:city' => 'cities#index', :as => :state_cities, :constraints => OmniauthPassThru.new

lib/omniauth_pass_thru.rb
class OmniauthPassThru
    def initialize
        @passthru = ["/auth/facebook", "/auth/twitter"]
    end

    def matches?(request)
        return false if @passthru.include?(request.fullpath)
        true
    end
end

A: You should be able to define your /auth route before your state/city routes:

Route priority
Not all routes are created equally. Routes have priority defined by the order of appearance of the routes in the config/routes.rb file. The priority goes from top to bottom.

So this order should do the right thing:
match '/auth/twitter' => ...
match '/:state/:city' => ...

You might want to avoid the problem altogether by putting your state/city routes into their own namespace:
match '/place/:state/:city' => ...

That leaves the top level clear for other future uses.


text:
Q: Existence of higher order weak derivative implies existence of lower order if integrable (1 dim). Proof? I am learning for a pde exam and found the following statement without proof in some old lecture notes:
If for some $u \in L^1_{loc}(a,b)$ and some $n \in \mathbb{N}$ there exists a weak derivative of order n $u^n \in L^1(a,b)$, i.e., for all test functions $\Phi \in \mathcal{C}^\infty_c(a,b)$ it holds that $$\int_a^b u(x) \Phi^n(x) \mathrm{d}x=(-1)^n \int_a^b u^n(x) \Phi(x) \mathrm{d}x$$ then all lower order weak derivatives exist and are absolutely continuous.
I know that this is not true if we do not require the integrability of the n-th weak derivative.
I tried to proof the statement, my idea was to construct the lower order derivatives inductively as integrals (like $u^{k-1}(x)=\int_a^x u^k(y) \mathrm{d}y$) but I didn't know how to proceed from there and am not sure if this is the right approach at all. Any ideas?
Also, can we generalize this for the multidimensional setting (maybe assume that all weak derivatives with multiindex $\alpha$ s.t. $|\alpha|=n$ exist and are integrable?)?

A: As I said in the comment: I figured it out and here is the proof in case somebody else has the same problem in the future.
Proof:
For $1 \leq k \leq n$ we define $v_k$ inductively:
Set $v_n:=u^n$. A theorem which was proven earlier in my lecture states that there exists a function $\Phi_1 \in \mathcal{C}^\infty_c(a,b)$ with $\int_a^b \Phi_1(x) \mathrm{d}x=1$.
For all $ 1 \leq k <n$ and $x \in (a,b)$ we define
$$v_k(x):=\int_a^x v_{k+1}(y) \mathrm{d}y+\underbrace{(-1)^k \int_a^b u(z)\Phi_1^k(z) \mathrm{d}z-\int_a^b (\int_a^z v_{k+1}(y) \mathrm{d}y)\Phi_1(z)\mathrm{d}z.}_{=:c} $$
We claim that for all $1 \leq k <n$: $v_k \in L^1(a,b)$ is well defined, a weak derivative of order k of u, and differentiable almost everywhere, i.e., absolutely continuous, with $v_k^\prime=v_{k+1}$.
We prove this by induction over $n-k$:
Assume that $v_{k+1} \in L^1(a,b)$ is well defined and a weak derivative of order k+1 of u.
Firstly, we will show that $x \mapsto \int_a^x v_{k+1}(y) \mathrm{d}y \in L^1(a,b)$:
$$\int_a^b |\int_a^x v_{k+1}(y) \mathrm{d}y|\mathrm{d}x \leq \int_a^b \int_a^x |v_{k+1}(y)| \mathrm{d}y \mathrm{d}x\leq \int_a^b \underbrace{\int_a^b |v_{k+1}(y)| \mathrm{d}y}_{<\infty,\ v_{k+1} \in L^1(a,b)} \mathrm{d}x<\infty.$$
This implies that $v_k$ is well defined and that $v_k \in L^1(a,b)$. By the fundamental theorem of calculus we know that $v_k$ is differentiable almost everywhere with weak derivative $v_k^\prime=v_{k+1}$.
Let $\Phi \in \mathcal{C}^\infty_c(a,b)$. There is a theorem that states that there exist $d \in \mathbb{R}$ and $\Phi_0 \in \mathcal{C}^\infty_c(a,b)$ s.t. $\Phi=\Phi_0^\prime + d\Phi_1$. This implies
$$(-1)^k \int_a^b v_k(x)\Phi(x)\mathrm{d}x=(-1)^k \int_a^b v_k(x) (\Phi_0^\prime(x)+d\Phi_1(x)) \mathrm{d}x=(-1)^k \int_a^b v_k(x)\Phi_0^\prime(x) \mathrm{d}x+(-1)^k d \int_a^b v_k(x) \Phi_1(x)\mathrm{d}x \underset{v_k^\prime=v_{k+1}}{=} (-1)^{k+1} \int_a^b v_{k+1}(x)\Phi_0(x) \mathrm{d}x+(-1)^k d \int_a^b (\int_a^x v_{k+1}(y) \mathrm{d}y +c)\Phi_1(x) \mathrm{d}x \underset{\text{def. of c and }\int \Phi_1=1}{=} (-1)^{k+1} \int_a^b v_{k+1}(x)\Phi_0(x) \mathrm{d}x + (-1)^k d (-1)^k \int_a^b u(x)\Phi_1^k(x)\mathrm{d}x \underset{v_{k+1} \text{ weak deriv. of order k+1}}{=}\int_a^b u(x)\Phi_0^{k+1}(x) \mathrm{d}x+\int_a^b u(x)d\Phi_1^k(x)\mathrm{d}x=\int_a^b u(x) \underbrace{(\Phi_0^\prime+d\Phi_1)^k}_{=\Phi^k}(x) \mathrm{d}x.$$
This means that $v_k$ is a weak derivative of order k of u and thereby finishes the proof.


text:
Q: 3TB HDD detected as 746GB, then CHKDSK severely corrupted the file system So I have two 3TB HDDs, one being the backup of the other, almost full (containing mostly videos, TV documentaries and whatnot), with no hardware issues (SMART parameters are all fine). I plugged one of them through an Akasa Integral external enclosure, in USB 2.0, to my laptop PC running on Windows Vista. The HDD was erroneously detected as being 746GB, and a CHKDSK analysis was recommanded, supposedly to avoid data corruption ; I didn't think twice and let it run... but then, I quickly discovered that it had severely corrupted the file system : a comparison with WinMerge showed that more than 100GB of files were damaged to a varying degree (for some of them only a cluster had been replaced or overwritten, some were entirely wrong and unreadable, for some of them the begining was in fact the begining of another file of any other type – for instance a MP4 file appeared to have a MHT header, or a TXT file appeared to be a directory index, etc.). Doing another CHKDSK analysis on my desktop PC running on Windows 7 with the HDD directly connected in SATA did not repair those files. Luckily I did not lose any important file as I had a virtually complete backup, but still, I'd like to understand what happened and why.
Now, what happened here ? Is it a known issue ? Could it be due to a limitation of the USB controler of that external case ? Normally Windows Vista is supposed to deal with 3GB HDDs just fine (as opposed to anterior versions). I think (but I'm not sure) that I previously used that same external case to plug a 3TB HDD to that same laptop in eSATA with no such issue.
And can someone help me understand how CHKDSK could corrupt the file system, although it's precisely supposed to ensure that it stays consistent and perfectly operational ? What did it do to the MFT to get that result ? Did it consider that any cluster beyond 2TB, was invalid and had to be un-allocated ? Yet I couldn't find any particular pattern with regards to the location of the affected files : most of them had been added recently, but some of them were older, having been copied in bulk when migrating from a smaller capacity HDD ; some of them appeared to be at the end, some at the begining, way before the 2TB mark (I used WinHex and R-Studio to find out the locations).
Any hint would be appreciated, thanks !


text:
Q: retrieve Datatables value for CSS formatting I'm building a table using Datatables picking up values from a database and would like to display rows that have unread=true in the database in bold text. I haven't found a way to retrieve any value (i.e unread column) from the table using Jquery/JS in order to apply a specific class.
Can this be done in any way? This is my current code, which obviously doesn't fix the problem.
$('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
   $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
} );
var table = $('table.table').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
     "dataSrc": "Data",
     "url": "logsController/getDataTable",
     "data": { string: $("input.form-control").val() },
     "type": "POST"
       },
       "columns": [
          { "data": "datetime" },
          { "data": "type" },
          { "data": "data" }
       ]
} );

$('#myTableLogs').DataTable();

console.log(data.unread) or console.log(data.datetime) both return "data is undefined"
UPDATE:
I solved my problem by removing the serverSide and changing my code. See answer below.

A: I figured out the serverSide wasn't required and inspired myself from this page and using createdRow.
$.ajax({
    url: "logsController/getDataTable",
    method: 'post',
    dataType: 'json',
    success: function (data) {
        var table = $('#myTableLogs').DataTable({
            paging: true,
            sort: true,
            searching: true,
            data: data,
            ordering: true,
            columns: [
                 { "data": "datetime" },
                 { "data": "type" },
                 { "data": "data" },
                 { "data": "unread" }
            ],
             "createdRow": function ( row, data, index ) {
                 if ( data.unread == 1 ) {
                      $('td', row).addClass('unread_class');
                 }
             }
        });
});

A: You can use the createdRow callback option to test the row data for a value and dynamically add a class to the row
var table = $('table.table').DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
        "dataSrc": "Data",
        "url": "logsController/getDataTable",
        "data": { string: $("input.form-control").val() },
        "type": "POST"
    },
    "columns": [
        { "data": "datetime" },
        { "data": "type" },
        { "data": "data" }
    ],
    "createdRow": function(row, data) {
        // replace with appropriate reference to your data structure
        // and CSS class to change font weight
        if (data.unread) $(row).addClass('text-bold');
    }
});


text:
Q: GetHashCode With Generic Collection Returns Different Values It looks like hash code issues and implementing your own equality logic have been beaten to death, but I cannot seem to find a definitive answer to this.
I have a custom object (Step) that overrides Equals, GetHashCode, ==, and != as suggested by the MSDN documentation.  This object by itself works fine; When comparing a Step to a Step, the equality operators work as expected.  Note that by equality I'm referring to the values of the Step's properties, not reference equality.
I have a second object (Steps) that stores the Step object in a generic list.  Now I want to see if a list of Step objects is equal to another list of Step objects.  In the Steps object I overrode the various methods and operators as I had done in Step.  For the GetHashCode override, I iterate through the Step list and combine the hash codes:
foreach(var step in steplist.Steps)
{
    hash += step.GetHashCode()
}
return hash

Simple.  But it does not work.  The hash codes for two separate lists with equal Step objects values return different hash codes.  I'm assuming I'm not implementing the hash code override correctly.
I'm about ready to hard code the returning hash code to zero and call it a day.  Any insight is appreciated.
Edit:
Sorry, I was trying to be brief so as to avoid a wall of text.  Here is the hash code generation for the Step object.   Taken from What is the best algorithm for an overridden System.Object.GetHashCode?:
public override int GetHashCode()
{
     return new { StepType, Color, Trigger, Delay, Index       }.GetHashCode();
}

Note that all these properties, aside from Delay and Index, are reference types, not value types if that makes a difference.  And to answer someone's question: no the two list I'm comparing are definitely not the same references.  They are two separate lists.  Perhaps therein lies my issue.

A: You need to show the code for GetHashCode() for StepType, Color and Trigger too to know for sure, but if they are not the same references and you are using the default implementation of GetHashCode() for those types then having different references causes different hash-codes to be generated.


text:
Q: How to prep scratch org with currencies When creating my Scratch org, I've added the MultiCurrency feature, and that works, but I still need to go in manually to add the currencies and set the company currency. Is it possible to to this via CLI, so scratch orgs can be more scripted?

A: Yes, you can insert currencies and change the corporate currency via the API. A quick way of doing this is
sfdx force:data:tree:import -f CurrencyTypes.json
where CurrencyTypes.json contains the following:
{
  "records": [
    {
      "attributes": {
        "type": "CurrencyType",
        "referenceId": "ref1"
      },
      "IsoCode": "INR",
      "DecimalPlaces": 2,
      "ConversionRate": 1.5,
      "IsActive":true,
      "IsCorporate": true
    }
  ]
}

Importing this into my scratch org, which was created with a default currency of GBP, (my scratch definition has a country of "GB"), resulted in my corporate currency becoming INR, and GBP being updated with an appropriate conversion rate to the corporate currency.

A: The metadata API doesn't support currency exchange rates, so you can't automatically set up multiple currencies. This is still, unfortunately, a manual process.


text:
Q: Can the scalars of a vector space be of a different field than the entries of the vector space? When denoting a particular vector space can the field that denotes the entries in the vectors of a vector space be different than the field that denotes the scalars that can be used on that vector space. For example if $V$ is a vector space denoted by $M_{m\times n}(R)$ do the scalars $c$ that act on that vector space have to be elements of $R$? I was reviewing the text "Linear Algebra" by Friedberg, Insel and Spence, and was a little confused by the following question:
Let $V$ denote the set of all $m\times n$ matrices with real entries; so $V$ is a vector space over  $R$ by example 2 (note this was the general definition of matrices over $R$). Let $F$ be the field of rational numbers. Is $V$ a vector space over $F$ with the usual definitions of matrix addition and scalar multiplication?
If $c\in R$ then no because you could do scalar multiplication with an irrational number and that would take you out of the vector space over $Q$ because an irrational number times a rational number is an irrational number. Now if $c$ is in $Q$ then yes it is a vector space. Without $c$ being explicitly denoted do I assume it belongs to the field that was defined with the vector space? Also, can $c$ and $V$ be different fields when denoting a vector space?

A: Yes, it is a vector space over F.
A vector space over F is a set V (in your case $m\times n$ matrices with real entries) with operations $+:V\times V \to V$ and $\cdot:F\times V \to V$ satisfying certain axioms, as found for example on the wikipedia vector space page.
That these axioms are satisfied is easily verified. The first four amount to V being an abelian group, and that last four must be satisfied by F since it is subfield of R.
It also follows easily from these observations that if V is a vector space over a field K, then it is a vector space over any subfield F of K (i.e., the example above generalizes).
It is important to note, though, that V is NOT a finite dimensional vector space over F. The dimensional isn't even countable, in fact.

A: First, note that a vector space is not necessarily a field. For example, $V$ (as you defined above) is not a field because not every matrix is invertible. However $V$ is certainly a vector space over $R$ AND over $Q$. If you accept the fact that $V$ is a vector space over $R$, then the same is true over $Q$. This is simply because $Q$ is a field with $Q \subset R$. Nothing else has to be verified. Note that if you take matrices with entries from $Q$, then this will be a vector space over $Q$ but not over $R$. This is because of the reason you stated above: if you multiply an irrational by a rational the result is an irrational (unless the rational is zero). Thus if you multiply an irrational scalar by a matrix with entries from $Q$, you will not in general get a matrix with entries from $Q$, hence it is not a vector space over $Q$
There is a little abuse of notation in books. Usually when talking about general vector spaces they will say let V be a vector space without mentioning the field. Always keep in mind that if V is a vector space, then it must be a vector space over some field (perhaps more than one, as in your example).

A: Yes, the scalars can be from a different field than the entries of the vectors. This is simply because we know how to define, in this case, rational numbers acting on real numbers by multiplication, and this satisfies the vector space axioms. If you review the axioms, you'll see there's nothing there about entries of vectors at all-so there's no way they could rule this out.

A: I think you're misinterpreting the question. Let's take a look at it:

Let $V$ denote the set of all $m\times n$ matrices with real entries; so $V$ is a vector space over  $R$ by example 2 (note this was the general definition of matrices over $R$). Let $F$ be the field of rational numbers. Is $V$ a vector space over $F$ with the usual definitions of matrix addition and scalar multiplication?

Recall that a vector space is a set of indexed arrays (vectors) whose entries come from a field (scalars) that satisfy the vector space axioms. The field is required in the definition of the vector space just as much as the operations. It should not be taken for granted that addition is generally just to mean addition in the elementary sense. Certain fields can be paired with very odd operations that still satisfy the vector space axioms, and so we call the operation "addition" in the context of discussion of the vector space. Really, one might consider a vector space itself as a tuple of three elements($\mathbb{F},[\;]^{m \times n},+)$ with three entries that are first a field of scalars, an array structure to hold the scalars, and third an operation to combine the arrays that behaves like addition in certain ways.
In the first sentence of the question, the author is establishing that the set of $m \times n$ arrays of real entries with Euclidean vector addition satisfies the axioms of a vector space. In the tuple notation, $(\mathbb{R},[\;]^{m \times n},+)$ is a vector space.
In asking "Is V a vector space over F?", the author cannot possibly mean "Is the set of $m \times n$ matrices with real entries a vector space over $F$?" because to say "a vector space over $F$" means that the entries come from $F$, so the answer is a trivial no. It is trivial that $\mathbb{R}^{m \times n}$ is not a vector space over $F$, because by it's very definition it has as its field of scalars the real numbers.
I don't believe that the author intended to ask a trivial question. Instead, the task is to determine if in the definition of $V$ one were to replace "real" with "rational", would the resulting $V$ given $(F,[\;]^{m \times n},+)$ also be a vector space. The question is non-trivial because $F$ is a subset of $\mathbb{R}$, so in this case if $(F,[\;]^{m \times n},+)$ is a vector space, then it is a subspace of $(\mathbb{R},[\;]^{m \times n},+)$ so the result can be demonstrated by showing that the set is closed under linear combinations.


text:
Q: How to implement an impersonation feature? If you have used Gitlab - it has an impersonsation feature where if your user has the 'owner' role the can 'impersonate' any user that has been created on the system by clicking a button and see what they see.
I would like to understand how can one implement a feature like that? what is the software design / architecture for it.
I am planning to design and implement this functionality in Java, Spring and Tomcat using server side sessions and would prefer to roll-out my own impersonation feature instead of using a library

A: If you want a specific solution that GitLab implemented in Ruby, you could take a look at the commit that introduced the feature: Commit 3bb626f9 - refactor login as to be impersonation with better login/logout
Please note that the security issue introduced on this commit was later fixed later: GitLab Blog Post - Critical Security Release for GitLab 8.2 through 8.7
Otherwise, I think this question is too broad.
I need some more details - Framework, Current Authentication mechanism, etc.
EDIT:
I do not know Java Spring framework too well, but these links may help you:

*

*spring security (3.0.x) and user impersonation

*How to do impersonation in spring


text:
Q: Finding and replacing with if then else statement in field calculator of ArcGIS Pro? I have a column of strings that always start with the first two characters being numbers, like 39 or 07, etc.  In a new column I want to process the original column so that I replace any of those first two numbers that are not 39 with a 39, but making sure the remaining trailing string characters are still there. So a find and replace but index on the first two characters.  I want to use the .replace() command but not sure how to tie in the index, replace command and an If Than Else statements to make it work.
In field calculator it would be like this:
replace(!Permit_num!)

code block:
import re
def replace(val):
    if (val[0:1] == "07"):
        return re.sub ('07','39'+val[2:], val)
    elif (val[0:1] == "10"):
        return re.sub ('10','39'+val[2:], val)
    elif (val[0:1] == "11"):
        return re.sub ('11','39'+val[2:], val)
    elif (val[0:1] == "19"):
        return re.sub ('19','39'+val[2:], val)
    elif (val[0:1] == "24"):
        return re.sub ('24','39'+val[2:], val)
    elif (val[0:1] == "27"):
        return re.sub ('27','39'+val[2:], val)
    elif (val[0:1] == "34"):
        return re.sub ('34','39'+val[2:], val)
    elif (val[0:1] == "35"):
        return re.sub ('35','39'+val[2:], val)
    elif (val[0:1] == "39"):
        return re.sub ('39','39'+val[2:], val)
    elif (val[0:1] == "50"):
        return re.sub ('50','39'+val[2:], val)
    elif (val[0:1] == "54"):
        return re.sub ('54','39'+val[2:], val)
    elif (val[0:1] == "56"):
        return re.sub ('56','39'+val[2:], val)
    elif (val[0:1] == "99"):
        return re.sub ('99','39'+val[2:], val)

I tried the above, but does not work, get a 99999 error and says my field I am calculating into is not nullable.  The new field is also a string.

A: You can use a list comprehension to index and replace the first characters for each item in a list. For example:
test = ["3901","1420","2270","3985"]

def replace(val):
    new = ["39" + i[2:] if i[:2] != "39" else i for i in test]
    print (new)

replace(test)

A: I finally figured out the problem. Was my index position.  So this type of code works as well.
permit_fix =
replace(!permit_num!)

Code Block
import re

def replace(val):

    if (val[0:2] == "07"):

        return re.sub ('07','39', val)

    elif (val[0:2] == "10"):

        return re.sub ('10','39', val)

    elif (val[0:2] == "11"):

        return re.sub ('11','39', val)

    elif (val[0:2] == "19"):

        return re.sub ('19','39', val)

    elif (val[0:2] == "24"):

        return re.sub ('24','39', val)

    elif (val[0:2] == "27"):

        return re.sub ('27','39', val)

    elif (val[0:2] == "34"):

        return re.sub ('34','39', val)

    elif (val[0:2] == "35"):

        return re.sub ('35','39', val)

    elif (val[0:2] == "39"):

        return re.sub ('39','39', val)

    elif (val[0:2] == "50"):

        return re.sub ('50','39', val)

    elif (val[0:2] == "54"):

        return re.sub ('54','39', val)

    elif (val[0:2] == "56"):

        return re.sub ('56','39', val)

    elif (val[0:2] == "99"):

        return re.sub ('99','39', val)


text:
Q: Internet Connection Detector using while loop I am trying to build a small program that checks for internet connection using while loop, quite new to C#, if possible could you help me figure out the problem with this program thanks.
var client = new WebClient();
while (true)
{
     var stream =client.OpenRead("http://www.google.com").ToString();
     Console.Write("You are in");
     Console.ReadLine();
     if (stream == "false")
     {
         Console.WriteLine("You are out");
         break;
     }
}

A: You may just send a Ping as following:
PingReply pingReply = new Ping().Send("http://www.google.com");

if (pingReply != null && pingReply.Status == IPStatus.Success)
{
    // Internet is ok
}

A: This is sample code to check the internet connection. May be this will help you.
 public static bool CheckInternetConnection()
 {
   try
   {
    using (var client = new WebClient())
    {
        using (var stream = client.OpenRead("http://www.google.com"))
        {
            return true;
        }
    }
  }
 catch
 {
    return false;
  }
}

From the main call like this:
while (true)
 {
 if(CheckInternetConnection()==true){
   Console.Write("You are in");
}
else{
   Console.Write("You are out");
}

}


text:
Q: Compare object property to validate json schema in same object I have a very simple object like so:
{
  "title": "A registration form",
  "description": "A simple form example.",
  "type": "object",
  "required": [
    "firstName",
    "lastName"
  ],
  "properties": {
    "firstName": {
      "type": "string",
      "title": "First name"
    },
    "lastName": {
      "type": "string",
      "title": "Last name",
      "minLength": "{'$ref': '/properties/firstName'}"
    },
}

On the property of LastName I would like to compare a value with a value of the property next to it. I am actually comparing integers so in actuality my real world example is even easier, just minimum and maximum.
I looked at the json schema spec here and it seemed like this should be doable, and have tried using relative paths and the $ref object.
Is this not possible?
The reference is here: https://www.rfc-editor.org/rfc/rfc6901
I am using react-jsonschema-form but I don't see where that would effect this.

A: There are a few of reasons why this doesn't work.  The primary reason is that $ref refers to the schema, not the data being validated.  There was talk of adding a $data keyword to JSON Schema that would allow referencing the instance data, but I don't think that will even happen.


text:
Q: How to Run Apex Scheduler 6days of job schedule? please give me one example of above scenario.how to run the schedule apex job in developer console.please give some ideas.

A: Well in this case you need to generate a cron expression. More on cron here - https://developer.salesforce.com/docs/atlas.en-us.192.0.apexcode.meta/apexcode/apex_scheduler.htm. Also go through this great utility that generates cron expression on the basis of options selected on UI - http://www.cronmaker.com/ The answer to your question is -
System.schedule('BatchNotification', '0 0 9 1/6 * ? *', new BatchSxhedule());

here BatchSxhedule is your schedule class. 9 denotes the time of the day (9AM). 1/6 Denotes starting today every 6 days. 2/6 denotes starting tomorrow every six days. and so on!

A: global class MySchedulableClass implements Schedulable {
global void execute(SchedulableContext ctx) {
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime
FROM CronTrigger WHERE Id = :ctx.getTriggerId()];
System.debug(ct.CronExpression);
System.debug(ct.TimesTriggered);
Merchandise__c m = new Merchandise__c(
Name='Scheduled Job Item',
Description__c='Created by the scheduler',
Price__c=1,
Total_Inventory__c=1000);
insert m;
}
}
Execute devaloper console....
MySchedulableClass  myJob = new MySchedulableClass ();
String sch = '0 0 0,2,4,6,8,10,12,14,16,18,20,22 ? * *';
System.schedule('My Job', sch, myJob);


text:
Q: For performance, Spring webservices or pure restful jersey even if i use MVC? im using spring MVC and webflow to create a game server and serve some web pages to the users. Thing is, the javascript game will also make multiple ajax calls to restful services on the same server for some game logic. While the web page serving performance is not critical, the restful service calls need to be as efficient as possible (efficient as in response time).
For performance of the services, would it be better to use pure JAX-RS (jersey) web service calls without the spring ws overhead (since i understand the spring layer could affect performances negatively) or would it be the same if i used the spring webservices framework instead and maintain integration with the rest of the spring family?
thanks!

A: There aren't many clear benchmarks out there, but take a look here:
http://www.techempower.com/benchmarks/
It clearly shows the overhead of using Spring. Compared to Servlets that serve JSON manually Spring is "slower". Personally, I don't think that Spring cuts development time, unless you are very much familiar with it. Creating a simple servlet that will act as a REST API is very simple. Take a look at the servlet code from the benchmark:
Servlet benchmark

A: I don't think Spring per se will affect performance negatively.  Where did you hear that?
Spring web services are "contract first" SOAP services.  If you're saying that you don't want to pay the overhead of SOAP, XML, marshalling and unmarshalling, then you have a valid point.  That's true whether you use Spring to implement the services or not.
REST is HTTP, so it's a natural for AJAX calls.
I believe Spring 3.0 supports REST, so it's not a "Spring or not Spring" choice:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/new-in-3.html#d0e1188


text:
Q: Finite subgroups of orthogonal transformations in $\mathbb{R}^3$ The group of orthogonal transformations of $\mathbb{R}^3$ is direct product of the group of rotations and the group $Z=\langle x\mapsto -x\rangle\cong \mathbb{Z}/2$. The finite subgroups of group of rotations are well known: rotational symmetries of regular polyhedrons.
These subgroups, along with their direct product with $Z$ will give some (families) of finite groups of orthogonal transformations.
It looks that some finite groups of orthogonal transformations need not be of this form (see Shafarevich- Algebra I; I couldn't understand arguments there).
How do we cover all finite subgroups of orthogonal transformations?
A more general question in this context may be: How to get subgroups of $H\times K$ knowing subgroups of $H$ and $K$?

A: The well-known Goursat's lemma is a classification of subdirect products of two groups. If all the subgroups of the factors are known (as it is in your case), then the lemma actually gives you a description of all the subgroups of the direct product. This question was also discussed on MO.

A: For an enumeration of all finite subgroups of orthogonal transformations in dimensions 1 through 4, see the book "On Quaternions and Octonions" by Conway and Smith, Chapters 1-4.  The enumeration for dimension $i$ is in Chapter $i$.
The enumeration of subgroups of a direct product plays a role, and is discussed in Chapter 4, Section 4.3.


text:
Q: How to reanimate combination of mathtext (T2) with UTF-8 in pdflatex stopped working after recent updates? A minimal example:
\documentclass[a4paper,12pt,notitlepage]{article}

\usepackage[warn]{mathtext}
\usepackage[T1,T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[russian,english]{babel}

\begin{document}
Например $А_б$.
\end{document}

Log file, first run with example after clear Basic MiKTeX installation, no any user formats, etc.:
This is pdfTeX, Version 3.14159265-2.6-1.40.19 (MiKTeX 2.9.6630 64-bit) (preloaded format=pdflatex 2018.6.1)  1 JUN 2018 11:44
entering extended mode
**./test18.tex
(test18.tex
LaTeX2e <2017-04-15>
Babel <3.18> and hyphenation patterns for 75 language(s) loaded.
("C:\Program Files\MiKTeX 2.9\tex\latex\base\article.cls"
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
("C:\Program Files\MiKTeX 2.9\tex\latex\base\size12.clo"
File: size12.clo 2014/09/29 v1.4h Standard LaTeX file (size option)
)
\c@part=\count79
\c@section=\count80
\c@subsection=\count81
\c@subsubsection=\count82
\c@paragraph=\count83
\c@subparagraph=\count84
\c@figure=\count85
\c@table=\count86
\abovecaptionskip=\skip41
\belowcaptionskip=\skip42
\bibindent=\dimen102
)
(C:\Users\vfkom\AppData\Roaming\MiKTeX\2.9\tex\latex\t2\mathtext.sty
Package: mathtext 2018/04/13 v1.1 transparent text-and-math defs
LaTeX Info: Redefining \halign on input line 119.
)
("C:\Program Files\MiKTeX 2.9\tex\latex\base\fontenc.sty"
Package: fontenc 2017/04/05 v2.0i Standard LaTeX package
 ("C:\Program Files\MiKTeX 2.9\tex\latex\base\t1enc.def"
File: t1enc.def 2017/04/05 v2.0i Standard LaTeX file
LaTeX Font Info:    Redeclaring font encoding T1 on input line 48.
\symT1letters=\mathgroup4
)
("C:\Program Files\MiKTeX 2.9\tex\latex\cyrillic\t2aenc.def"
File: t2aenc.def 2005/09/27 v1.0i Cyrillic encoding definition file
Now handling font encoding T2A ...
... processing UTF-8 mapping file for font encoding T2A
 ("C:\Program Files\MiKTeX 2.9\tex\latex\base\t2aenc.dfu"
File: t2aenc.dfu 2017/01/28 v1.1t UTF-8 support for inputenc

! Undefined control sequence.
l.46 \DeclareUnicodeCharacter
                             {00A4}{\textcurrency}
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

! LaTeX Error: Missing \begin{document}.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.46 \DeclareUnicodeCharacter{0
                               0A4}{\textcurrency}
You're in trouble here.  Try typing  <return>  to proceed.
If that doesn't work, type  X <return>  to quit.

! Undefined control sequence.
l.46 \DeclareUnicodeCharacter{00A4}{\textcurrency
                                                 }
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

! Undefined control sequence.
l.47 \DeclareUnicodeCharacter
                             {00A7}{\textsection}
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

! TeX capacity exceeded, sorry [input stack size=5000].
\textsection ->\T1-tmcmd \textsection
                                      \T1\textsection \T1math\textsection
l.47 \DeclareUnicodeCharacter{00A7}{\textsection
                                                }
If you really absolutely need more capacity,
you can ask a wizard to enlarge me.

Here is how much of TeX's memory you used:
 495 strings out of 493305
 5269 string characters out of 3138875
 54363 words of memory out of 3000000
 4120 multiletter control sequences out of 15000+200000
 3938 words of font info for 15 fonts, out of 3000000 for 9000
 1141 hyphenation exceptions out of 8191
 5000i,0n,27p,163b,36s stack positions out of 5000i,500n,10000p,200000b,50000s
!  ==> Fatal error occurred, no output PDF file produced!

A: The issue is resolved after yet another launch of (redesigned) MiKTeX console with updates and refreshing again (the cause of the problem was not understood). Thanks to everyone who paid attention.


text:
Q: ulong not declared in the scope in Android I am trying to compile the following code with cross compiler for the Android API version 14:
#include <iostream>

using namespace std;
int main (int argc, char ** argv)
{
    printf ("Size of ulong %d ", sizeof(ulong));
}

I am getting the following error:

test1.cpp: In function 'int main(int, char**)':
test1.cpp:6: error: 'ulong' was not declared in this scope

How can I resolve this issue ? I'm new to the Android environment. :)

A: ulong is not typedefed in iostream. Use unsigned long instead. Or typedef it yourself like
typedef unsigned long ulong


text:
Q: Tortoise SVN timestamp should sync with server's date instead of client's date We have implemented Tortoise SVN. I am facing a problem with date and time that when someone update the SVN it take date and time of client PC instead of taking server's time. So how can I get the server time ? Please suggest me the solution.

A: *

*You can't

*You must not rely on timestamp for anything: you have more reliable and correct metrics


text:
Q: Unable to intersect polygons in R even though CRS matches? I am trying to use areal interpolation to distribute the values from a source polygons layer into smaller, differently-shaped polygons from a target layer, and have been unable to do so. I have been using the sf package in in R, and specifically the aw_interpolate() function within the areal package. After encountering issues where the values of interest just were not showing up in the target layer after running the areal interpolation, all appearing as "NA", I noticed that I was not even able to intersect the polygons to begin with, leading me to speculate that these polygons layer are not even overlapping to begin with as they should be. I will explain further below.
I have the following grid of the US with varying-sized cells, each containing emissions values, which is my source layer:

I want to then take the values from this source layer and distribute them amongst the block group polygons in this target layer (yes, taking the data layer of the whole US and "downscaling" the data to the polygons for a specific county):

Of course, this means that only the grid cells that actually overlap with my county block group polygons are needed, and the rest of the grid cells in this state, and the rest of the US, are ignored.
However, running the areal interpolation yields all NA values in my target block group polygons for my field of interest. I wanted to break apart the process, as I was suspicious about the layers somehow not overlapping, and tried to run a simple intersection in R, just to make sure this actually worked.
Here is my R code:
install.packages("sf")
install.packages("areal")
library(sf)
library(areal)

US_emissions <- st_read("C:/Users/Name/Desktop/Map/US_Output/US_Output_.shp")

County_blockgroups <- st_read("C:/Users/Name/Desktop/Map/County_Blockgroups/County_Blockgroups.shp")

#Get these two layers in the same CRS
st_crs(US_emissions) <- st_crs(County_blockgroups)
US_emissions <- st_transform(US_emissions, crs = st_crs(County_blockgroups))

And then just to make sure my two layers are in the same CRS, I then run:
US_emissions

and receive:
Simple feature collection with 46998 features and 20 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: -2736000 ymin: -2088000 xmax: 2448000 ymax: 1944000
Projected CRS: NAD83 / California zone 4 (ftUS)
First 10 features:

and then run:
County_blockgroups

and receive:
Simple feature collection with 589 features and 16 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: 5999505 ymin: 1851910 xmax: 6749006 ymax: 2460485
Projected CRS: NAD83 / California zone 4 (ftUS)
First 10 features:

Great, it looks like these two layers are in the same CRS and should overlap fine!
So then I try to intersect the two layers, running the following:
intersect <- st_intersection(County_blockgroups, US_emissions)
intersect

and receive:
Warning: attribute variables are assumed to be spatially constant throughout all geometries
Simple feature collection with 0 features and 36 fields
Bounding box:  xmin: NA ymin: NA xmax: NA ymax: NA
Projected CRS: NAD83 / California zone 4 (ftUS)
 [1] AWATER10   TRACTCE10  STLength   STArea     ALAND10    BLKGRPCE10 FUNCSTAT10
 [8] ID         NAMELSAD10 COF_Census COUNTYFP10 STATEFP10  MTFCC10    GEOID10
[15] INTPTLAT10 INTPTLON10 AsianD     BasePM25   BlackD     LatinoD    NH3
[22] NOx        NativeD    PNH4       PNO3       PSO4       PrimPM25   SOA
[29] SOx        TotalPM25  TotalPop   TotalPopD  WhitNoLatD WindSpeed  PolygonID
[36] Area_Sourc geometry
<0 rows> (or 0-length row.names)

It looks like the intersection "worked", but then again, it looks like nothing actually intersected, seeing that there are 0 features and 0 rows produced. If the intersection does not work, then I would think that this is the reason the areal interpolation did not work, since to my understanding, intersection is a needed step in areal interpolation. Though I do not understand why the intersection did not work if my source layer and target layer are both successfully read into R, and both appear to be in the same CRS. Where might I be going wrong here?

A: This bit is possibly wrong:
#Get these two layers in the same CRS
st_crs(US_emissions) <- st_crs(County_blockgroups)
US_emissions <- st_transform(US_emissions, crs = st_crs(County_blockgroups))

When you first create US_emissions using st_read it should get a CRS from the shapefile. It should be the correct CRS of the data. That first line above - st_crs(US_emissions) <- st_crs(County_blockgroups) will overwrite the CRS of US_emissions with - possibly - the wrong CRS!
Only the second of those lines should be necessary - it computes the transformed coordinate numbers of US_emissions into the CRS of County_blockgroups and returnes an object with that CRS code assigned to it.
You should always check that the bounding box and the st_crs of spatial objects are correct when you read them, and you should also show this for data read into questions here (especially if you cant supply the data).


text:
Q: Bash and Tab Auto-complete I recently put Fedora Core 15 on my system, and I've had a behaviour change that I can't figure out. Using Tab-Complete in the BASH shell works fine except when I use the $HOME variable.
If I type cd $HOME/dTAB, it will auto-complete to the proper directory (doc), but it also inserts a preceding \, so the result is cd \$HOME/doc. This then fails, as such a path does not exist.
The error is

bash: cd: $HOME/doc: No such file or directory

If I don't use Tab-Complete it works, as $HOME still points to the proper directory. Where did this extra \ come from, and how do I make it go away?

A: By issuing the command complete you'll get the list of all completion definitions. Then you can search the offending definition somewhere in /etc/bash_completion and /etc/bash_completion.d. There can be also some .bash_completion in your home directory. On my system the $HOME variable is completed properly, but then fails to complete anything.
Did you try to use ~ instead of $HOME? It's easier to type and it works as expected...

A: There is an option for it
shopt -s direxpand

It didn't work on Bash 4.1 (this incompatible feature was added in BASH 4.2), so I used it as
[[ $BASH_VERSION =~ ^4.[2-9] ]] && shopt -s direxpand


text:
Q: SyntaxError: 'with' statements are not valid in strict mode I'm getting this error in safari console when I try to do anything from a breakpoint. Bug report here: https://bugs.webkit.org/show_bug.cgi?id=83267
Does anyone have a workaround? For reasons that I am assuming are related to this javascript has ceased to run on my site in safari.
edit: the bug report also contains repro steps.
another edit: I'm not using a "with" statement. This is a bug from the safari console.

A: The with(obj) {} statement is deprecated, and as such, is not valid in strict mode.
To solve this, either disable strict mode, or stop using with statements!

A: Strict mode in ECMAScript 5 bans eg. with statement. You have two choices:

*

*disable strict mode (remove "strict mode"; line from the file / function), or

*(preferred) avoid using with statements - they are harmful and totally unreadable.

More on strict mode from John Resig: ECMAScript 5 Strict Mode, JSON, and More.
You can read in the article, that strict mode:

*

*makes you unable to delete variable (like in delete foo;),

*limits usage of eval,

*adds some limitations to functions (eg. accessing caller and callee),

*removes with statements,


text:
Q: Call a function of external js file in angular 5 component Under index.html I have delcared an external js file like
<script data-siteid="XXXXXX" src="https://api.cartstack.com/js/customer-tracking/website.com_c7ee604471301b0bd028e8f19a535557.js" type="text/javascript">
  </script>
I have to call a function named cartstack_updatecart() from a component. (That function is generating from above link). How to do that?

A: Follow below steps in your component:-
1) First add a reference of your external JS file for importing it to the component.
   Import * as abcJS from '/YourExternalJS.js';

2) Now declare a "var" of the same name that your function has inside external JS.
   declare var cartstack_updatecart: any;

3) ngOninit(){
 cartstack_updatecart();
 }

4) Do remember that your JQuery should be loaded first than your external JS file.

I have called that function on ngoninit lifecycleHook.
Also instead of declaring external JS file inside Index.html, I would rather suggest you to declare it in angular-cli.json file in scripts array.
All the best.


text:
Q: How to compare my string to the return in python I have this code
log_in = f'SELECT user_name,fname FROM users;'
cursor = connection.cursor()
cursor.execute(log_in)
result = cursor.fetchall()
cursor.close()
print(type(result))
print(result)
print('bfuqua' in result)
if 'bfuqua' in result:
    unique = False
    print('That user name already exists. Please try again.')

When I print the type I get <class 'list'> as the return type, [('bfuqua',)] as the data from the result variable. My problem is that it should be entering into the if statement but the return from the third print statement says False. It comes back as True when I put result[0], but I need to be able to scan the whole list for the string. I don't know what is going on.
If there are any other ways I can check to see if the string is in the return from the query, I am more than open to hear it!

A: Well if you would like to use your code you can iterate over result to achieve what you want:
for i in result:
    if 'bfuqua' in i:
        unique = False
        print('That user name already exists. Please try again.')

But if you want to do it in a way suggested by @iuvbio I'd do it like:
def check_if_user_exists(username):
    #by using "with" you dont need to worry about closing the connection
    with connection.cursor() as cursor:
        log_in = "SELECT user_name, fname FROM users WHERE user_name = %s"
        cursor.execute(log_in, (username,))
        result = cursor.fetchall()
    # If there is no user, the result will be a tuple with 0 length
    if len(result) == 0:
        print("No user named {}".format(username))
        # So here you can create user
    else:
        print("User {} already exists".format(username))
        # Here you can create a notification for a client that the username already exists
check_if_user_exists("bfuqua")

I'm also a beginner so dont treat it like the one and only good solution but it works for me. Hope I was able to help :)


text:
Q: Why are all my foreign keys null? I've been playing around with Entity Framework for a while now. For some reason however the foreign keys all seem to be null untill I explicitely use the Include method to include them.
According to what I've read here:
Entity Framework 4.1 Virtual Properties
by making them virtual they should be lazy loaded (and not null).
This is my model:
class AltiGoalInfo
{
    public int AltiGoalInfoId { get; set; }
    public int ShotTime { get; set; } //Time it took from shooting till scoring
    public virtual AltiPlayerInfo AltiPlayerInfo { get; set; }
    public virtual AltiTeamEnum Team { get; set; }

    public override string ToString()
    {
        double shotTime = ShotTime;
        shotTime /= 1000;
        shotTime = Math.Round(shotTime, 2);
        return shotTime + " by " + AltiPlayerInfo;
    }
}

class AltiPlayerInfo
{
    public int AltiPlayerInfoId { get; set; }
    public String VaporId { get; set; }

    public String LastKnownNickname { get; set; }
    public int LastKnownLevel { get; set; }
    public int LastKnownAceRank { get; set; }
    public Boolean LastKnownDemo { get; set; }

    private IList<String> _knownIps = new List<String>();
    public IList<String> KnownIps
    {
        get
        {
            return _knownIps;
        }
        set
        {
            _knownIps = value;
        }
    }

    public string KnownIpsString
    {
        get
        {
            return String.Join(";", _knownIps);
        }
        set
        {
            _knownIps = value.Split(';').ToList();
        }
    }

    public int Goals { get; set; }
    public int MatchesPlayed { get; set; }
    public int MatchesWon { get; set; }

    public double CalcWinRate()
    {
        double mwon = MatchesWon;
        double mplay = MatchesPlayed;
        double result = mwon / mplay * 100.0;
        return Math.Round(result, 0);
    }

    public DateTime FirstSeen { get; set; }
    public DateTime LastSeen { get; set; }

    public override string ToString()
    {
        return LastKnownNickname;
    }
}

class AltiDbContext : DbContext
{
    public DbSet<AltiPlayerInfo> AltiPlayerInfos { get; set; }
    public DbSet<AltiGoalInfo> AltiGoalInfos { get; set; }
}

When I use the following code to acces the data the brrr variable is null:
var test = altiDbContext.AltiGoalInfos.First();
var brrr = test.AltiPlayerInfo;

When I however include in manually first, it does work:
var test = altiDbContext.AltiGoalInfos.Include(t => t.AltiPlayerInfo).First();
var brrr = test.AltiPlayerInfo;

Edit:
I've also verified the configuration of the DbContext, by default all settings in the configuration are set to true (which should enable lazy loading).

A: I found the solution, I had to make the model classes public


text:
Q: How do I concatenate a variable in angular.element? I currently have this, but I am unable to say concatenate a variable in the middle.
var popoverElement = angular.element('
  [need my variable here]
');

A: String concatenation:
var popoverElement = angular.element('
' + var + '
');


text:
Q: Node thread-1 transactions.TransactionBuilder [ERROR] 17:33:56+0800 [Node thread-1] transactions.TransactionBuilder. - The transaction currently built will not validate because of an unknown error most likely caused by a
missing dependency in the transaction attachments.


text:
Q: Write spark dataFrame as a single CSV file (no folders) to S3? My requirement is simple, I need to write my spark DataFrame to S3 as a single csv file of a specified name
Write now I am using .coalesce(1) which puts all the data in a single CSV but still creates a folder with some additional files and the name of the main csv file is some id.
[I'm using java/scala]
dataFrame.coalesce(1).write.mode(SaveMode.Overwrite).option("header", "true").csv("s3a://<mypath>")

this is how the data is being saved

A: I think you can just collect the records and save it through the driver, since you are coalescing 1, you need to transfer all records to one node in all cases.
But before you collect it to local, i think it's better to transform your dataframe to a dataset.
Just do something like:
dataframe.as[TypeToDefine].collect()

then you get an Array of TypeToDefine, and you can write your csv using any popular java/scala csv library you like with the name you want.

A: I think this is what you're asking.
import org.apache.hadoop.fs.Path

val s3Path: String = ???      // full S3 path & file name
val textToWrite: String = ??? // collect your dataframe and convert to a single String

val path = new Path(s3Path)
val fs = path.getFileSystem(spark.sparkContext.hadoopConfiguration)
val out = fs.create(path, true)
out.write( textToWrite.getBytes )
out.close()


text:
Q: Google rejects OAuth 2 Javax.Mail API with bad credentials java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8  https://support.google.com/mail/?p=BadCredentials v7-20020a4a8607000000b0041bdf977c6dsm58061ooh.31 - gsmtp
I am receiving this error when attempting to use javax.mail API to send emails over my GMail account. I attempted to check my settings to verify it allows less secure apps to use my GMail account but the Google website says
To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.

Does anyone know where I can find a current guide on how to build hooks to send/receive mail messages with my GMail account that gets around these new requirements?

A: *

*Access the page with your Gmail/Google Account -> https://myaccount.google.com/security

*In the Signing in to Google section, enable the 2-Step Verification

*After enabling 2-Step Verification, return to Signing in to Google section

*Click on App passwords

*Select app as Mail and select device as Other - choose a name

*Done! Copy the password and use it with the username account


text:
Q: Why do JSF properties files not accept non-ASCII characters in Eclipse? I wonder, why do JSF properties files not accept non-ASCII characters in Eclipse?
I have some properties file named "messages.properties", I've to write in unicode escapped characters for non-ASCII characters, example:
title=\u01af\u0020\u0a3f0
header=\u0ff0\u0020\u0ab1

This means that customers cannot edit these properties files using regular text editors.
Is there any solution?

A: This stems in the fact that java.util.Properties.load(InputStream) uses ISO-8859-1.

The load(InputStream)  /  store(OutputStream, String)  methods work the same way as the load(Reader)/store(Writer, String) pair, except the input/output stream is encoded in ISO 8859-1 character encoding. Characters that cannot be directly represented in this encoding can be written using Unicode escapes  ; only a single 'u' character is allowed in an escape sequence. The native2ascii tool can be used to convert property files to and from other character encodings.

It has been a problem for ages. I've solved it with struts by implementing custom tags that make encoding transformations, but it is generally a pain.
Java 6 introduces the Properties.load(Writer), which works fine with UTF-8, but it seems it isn't widely adopted yet.
I'd suggest using AnyEdit tools to convert to and from the unicode notation.
As for the end-users - if they are to edit properties files (which sounds strange), then you can let them write in whatever characters they like and later convert the files using native2acii (or a wrapper of it)

A: This is not necessary anymore since Eclipse 4.2 (Juno, 2012). Eclipse will take care of this transparently when you use the builtin properties file editor. It will present and accept the values in UTF-8, but it will under the covers silently convert to \uXXXX format. Noted should be that this has some strange side effects in combination with Git plugin (e.g. old lines deleted during merge), it works best if you close all properties files before pulling/pushing.
If you're not on Eclipse 4.x yet, consider using native2ascii tool found in /bin folder of the JDK installation directory to convert UTF-8 properties files to ASCII properties files, as described in javadoc of java.util.Properties class.
You can keep the "original" properties files (give them for example an .utf8 extension) and use a batch/shell file to convert them like this:

cd c:\path\to\properties\files
c:\path\to\jdk\bin\native2ascii.exe -encoding UTF-8 text_cs.properties.utf8 text_cs.properties
c:\path\to\jdk\bin\native2ascii.exe -encoding UTF-8 text_ja.properties.utf8 text_ja.properties
c:\path\to\jdk\bin\native2ascii.exe -encoding UTF-8 text_zh.properties.utf8 text_zh.properties
# You can add more properties files here.

This way you can just edit the .utf8 files and run the batch/shell script once to do the conversion of native characters to \uXXXX. Also see this blog entry.
See also:

*

*How to use UTF-8 in resource properties with ResourceBundle

A: just save the .properties file as UTF-8 format and it works for me.


text:
Q: Re-mapping keyboard keys I am using a keyboard with the Fn key. This is on a laptop.
So my Fn + Up/Down/Left/Right keys are mapped to brightness/volume. I would much rather them be mounted to Page Up/Page Down and Home/End. And map the other 4 keys to these 2. The page Page Up/Page Down has Fn + them for Home/End. Its a shitty keyboard layout but I want to make it work.
Anyone knows how to figure out what the keycodes are and how to remap them?
Version: 10.04  x32
So here are some experiments:
Using xmodmap -pke I discovered that keycodes 122 = vol down, 123 = vol up. And I got all the info for Home/End/Page Up (next), Page Down (prior).
Now when using the vol up keys, there are no events being fired that xev can detect.
I can remap the volume keys to XF86AudioLowerVolume or XF86AudioRaiseVolume, but once I map those two to Home/End (respectively) they don't do anything. xev still does not pick up these events after a remap.
Remap: xmodmap -e "keycode 122 = Home"

A: Some laptop Fn key combinations are multimedia keys (appearing to the OS as ordinary keys with nonstandard codes), while others trigger ACPI events that eventually reach the OS, and some are just handled by the BIOS and never seen by the OS. The information paths are explained on the Hotkeys/Architecture page on the Ubuntu wiki, complete with diagrams.
The KeyTouch program should handle anything that is seen by the OS, and has a friendly GUI for describing your model and configuring what the keys should do (install the keytouch-editor package as well as keytouch).
If the OS can't see anything when you press the brightness keys, it could be because they're handled directly by the BIOS. The battle is not completely lost — it is in principle possible to hack the BIOS — but the difficulty level is considerably raised.

A: There is a program called xev that does what you require. I liked the tutorial on setting it up.

A: The Fn key combinations is not defined in software and can therefor not be redefined, so you need a soldering iron and some electronics knowhow!


text:
Q: how to create a sp that inserts values from one table to another Hi I want to create a stored procedure that takes specific values from one table and inserts them into another if a specific table been 'DateAquired ' is null I have this stored procedure below but it doesn't seem as expected please help.
 Thanks in advance
this is my code
USE [MediaPlayer]
GO
/****** Object:  StoredProcedure [dbo].[sp_Wishlists]    Script Date: 11/26/2013 11:43:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[sp_Wishlists]
    -- Add the parameters for the stored procedure here
    @Name nvarchar (250),
    @FileName nvarchar (250),
    @FilePath  nvarchar (50),
    @FileSize float,
    @DateAdded date,
    @MediaLength nvarchar (50),
    @MediaSubType nvarchar(50),
    @MediaType nvarchar(50),
    @Thumbnail image,
    @DateAquired nvarchar (50),
    @WishList int output ,
    @CName nvarchar  (50)output ,
    @Media nvarchar (50)output,
    @WishListID int output

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
Select GeneralID, Name, FileName, FilePath,FileSize,DateAdded,MediaLength,MediaSubType,MediaType, Thumbnail,DateAquired As Wishlist
From General where NULLIF(DateAquired,'')IS Null

insert into Wishlists (generalID ,MediaType, Name)
values ((IDENT_CURRENT('dbo.General')),(IDENT_CURRENT('dbo.General')),(IDENT_CURRENT('dbo.General')))
SET @WishListID = @@IDENTITY
select GeneralID, MediaSubType, Name

From General where NOT EXISTS (Select Name from WishLists Where Name =@Name);
END

A: try below insert statement
insert into Wishlists (generalID ,MediaType, Name)
select GeneralID, MediaSubType, Name
From General where NOT EXISTS (Select Name from WishLists Where Name =@Name);


text:
Q: How to model Mixture of Bernoullis in pymc3 I'm trying to use Dirichlet Processes to identify clusters in my binary data. I'm using the tutorial as a starting point, but the tutorial is framed where the outcome is a mixture of 1D normal or poisson distributed variables.
I have multiple binary variables per observation, 5 in the example code below, and cannot work out how to frame the final mixture step. From the mathematical description in this report I can see the overall likelihood is simply the product of the likelihoods across all the assigned clusters.
I haven't explicitly formed cluster labels (using Categorical(w)) as the pm.Mixture distribution handles this, but can't work out how to formulate the likelihood as a probability model that pymc3 understands.
import numpy as np
import pandas as pd
import pymc3 as pm
from matplotlib import pyplot as plt
import seaborn as sns
from theano import tensor as tt

N = 100
P = 5
K_ACT = 3

# Simulate 5 variables with 100 observations of each that fit into 3 groups
mu_actual = np.array([[0.7, 0.8, 0.2, 0.1, 0.5],
                      [0.3, 0.4, 0.9, 0.8, 0.6],
                      [0.1, 0.2, 0.3, 0.2, 0.3]])
cluster_ratios = [0.6, 0.2, 0.2]

df = np.concatenate([np.random.binomial(1, mu_actual[0, :], size=(int(N*cluster_ratios[0]), P)),
                     np.random.binomial(1, mu_actual[1, :], size=(int(N*cluster_ratios[1]), P)),
                     np.random.binomial(1, mu_actual[2, :], size=(int(N*cluster_ratios[2]), P))])

# Deterministic function for stick breaking
def stick_breaking(beta):
    portion_remaining = tt.concatenate([[1], tt.extra_ops.cumprod(1 - beta)[:-1]])
    return beta * portion_remaining

K_THRESH = 20

with pm.Model() as model:
    # The DP priors to obtain w, the cluster weights
    alpha = pm.Gamma('alpha', 1., 1.)
    beta = pm.Beta('beta', 1, alpha, shape=K_THRESH)
    w = pm.Deterministic('w', stick_breaking(beta))

    # Each variable should have a probability parameter for each cluster
    mu = pm.Beta('mu', 1, 1, shape=(K_THRESH, P))

    obs = pm.Mixture('obs', w, pm.Bernoulli.dist(mu), observed=df)

with model:
    step = pm.Metropolis()
    trace = pm.sample(100, step=step, random_seed=17)

pm.traceplot(trace, varnames=['alpha', 'w'])

EDIT 28/01/2019
I've provided a custom likelihood function that simply calculates the Bernoulli mixture likelihood after drawing component labels from a Categorical distribution. However, while the model is now doing something, it can't identify the 3 groups, instead only finding 2. I can't tell if it just needs more sampling / more efficient parameterisation, or whether the model definition is flawed.
import numpy as np
import pandas as pd
import pymc3 as pm
from matplotlib import pyplot as plt
import seaborn as sns
from theano import tensor as tt

N = 1000
P = 5

# Simulate 5 variables with 1000 observations of each that fit into 3 groups
mu_actual = np.array([[0.7, 0.8, 0.2, 0.1, 0.5],
                      [0.3, 0.4, 0.9, 0.8, 0.6],
                      [0.1, 0.2, 0.3, 0.2, 0.3]])
cluster_ratios = [0.4, 0.3, 0.3]

df = np.concatenate([np.random.binomial(1, mu_actual[0, :], size=(int(N*cluster_ratios[0]), P)),
                     np.random.binomial(1, mu_actual[1, :], size=(int(N*cluster_ratios[1]), P)),
                     np.random.binomial(1, mu_actual[2, :], size=(int(N*cluster_ratios[2]), P))])

# Deterministic function for stick breaking
def stick_breaking(beta):
    portion_remaining = tt.concatenate([[1], tt.extra_ops.cumprod(1 - beta)[:-1]])
    return beta * portion_remaining

K_THRESH = 20

def bernoulli_mixture_loglh(comp, mus):
    # K = maximum number clusters
    # N = number observations (1000 here)
    # P = number predictors (5 here)
    # Shape of tensors:
    #   comp: K
    #   mus: K, P
    #   value (data): N, P
    def loglh_(value):
        mus_comp = mus[comp, :]
        # These are (NxK) matrices giving likelihood contributions
        # from each observation according to each component's probability
        # parameter (mu)
        pos = value * tt.log(mus_comp)
        neg = (1-value) * tt.log((1-mus_comp))
        comb = pos + neg
        overall_sum = tt.sum(comb)
        return overall_sum
    return loglh_

with pm.Model() as model:
    # The DP priors to obtain w, the cluster weights
    alpha = pm.Gamma('alpha', 1., 1.)
    beta = pm.Beta('beta', 1, alpha, shape=K_THRESH)
    w = pm.Deterministic('w', stick_breaking(beta))
    component = pm.Categorical('component', w, shape=N)

    # Each variable should have a probability parameter for each cluster
    mu = pm.Beta('mu', 1, 1, shape=(K_THRESH, P))
    obs = pm.DensityDist('obs', bernoulli_mixture_loglh(component, mu), observed=df)

n_samples = 5000
burn = 500
thin = 10

with model:
    step1 = pm.Metropolis(vars=[alpha, beta, w, mu])
    step2 = pm.ElemwiseCategorical([component], np.arange(K_THRESH))
    trace_ = pm.sample(n_samples, [step1, step2], sample=17)

trace = trace_[burn::thin]

pm.traceplot(trace)
plt.show()

Should the w trace be stationary?

# Plot weights per component
fig, ax = plt.subplots(figsize=(8, 6))

plot_w = np.arange(K_THRESH) + 1

ax.bar(plot_w - 0.5, trace['w'].mean(axis=0), width=1., lw=0);

ax.set_xlim(0.5, K_THRESH);
ax.set_xlabel('Component');
ax.set_ylabel('Posterior expected mixture weight');

Why aren't the components ordered? In other examples I've seen they are typically arranged in descending size order

The code below displays the mu Bernoulli parameter values for the 2 main components, but these are far from the actual values
# Posterior values of mu for the non-zero components
mean_w = np.mean(trace['w'], axis=0)
nonzero_component = np.where(mean_w > 0.3)[0]

mean_mu = np.mean(trace['mu'], axis=0)
print(mean_mu[nonzero_component, :])

[[0.47587256 0.50065195 0.51081395 0.57693177 0.40762681]
 [0.42596485 0.69626519 0.5629946  0.30185575 0.64322441]]

Actual parameters used to simulate data:
[[0.7, 0.8, 0.2, 0.1, 0.5],
 [0.3, 0.4, 0.9, 0.8, 0.6],
 [0.1, 0.2, 0.3, 0.2, 0.3]]