text:
Q: JsonMappingException: could not initialize proxy - no Session I am building a RESTful Web Service that consumes and returns JSON. I am encountering the following stack trace when I try to fetch an ESRBRating object from the database through the service layer. However when I inject the Spring Data JPA repository directly to the controller and use that to fetch the ESRBRating by ID it works fine. However when calling through the service layer it does not work. I have provided the stack trace and code below. Can someone explain to me why this is happening when going through a service layer but not when going through the Spring Data JPA repository directly? How do I resolve this issue?
Stack Trace
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at net.jkratz.igdb.model.ESRBRating_$$_jvst319_0.getId(ESRBRating_$$_jvst319_0.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:466)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:639)
    ... 76 more

Controller
@RestController
@RequestMapping(produces = "application/json", value="/esrbrating")
public class ESRBRatingController {

    @Inject
    ESRBRatingService esrbRatingService;

    @Inject
    ESRBRatingRepository esrbRatingRepository;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Returns all ESRB ratings in database
     *
     * @return List of ESRBRating objects
     * @see ESRBRating
     */
    @RequestMapping(value = {"","/"}, method = RequestMethod.GET)
    public ResponseEntity<List<ESRBRating>> getESRBRatings() {
        List<ESRBRating> esrbRatings = esrbRatingService.getESRBRatings();
        return new ResponseEntity<>(esrbRatings, HttpStatus.OK);
    }

    /**
     * Returns a single ESRB rating object if exists, otherwise returns HTTP status code 404
     *
     * @param id ID of the ESRB Rating
     * @return ESRB Rating when found
     * @see ESRBRating
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<?> getUser(@PathVariable("id") Long id) {
        logger.debug("Attempting to fetch ESRB rating with ID: {}", id);
        ESRBRating esrbRating = esrbRatingService.getESRBRating(id);
        //ESRBRating esrbRating = esrbRatingRepository.findOne(id);

        if (esrbRating == null) {
            return new ResponseEntity<>("ESRB Rating not found", HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(esrbRating, HttpStatus.OK);
        }
    }

}

Service
@Service
@Transactional
public class ESRBRatingServiceImpl implements ESRBRatingService {

    @Value("#{paging.games.maxPageSize}")
    private static int DEFAULT_PAGE_SIZE;

    @Value("#{paging.games.maxPageSize}")
    private static int MAX_PAGE_SIZE;

    @Inject
    private ESRBRatingRepository esrbRatingRepository;

    @Override
    public List<ESRBRating> getESRBRatings() {
        List<ESRBRating> ratings =  esrbRatingRepository.findAll();
        return ratings;
    }

    @Override
    public ESRBRating getESRBRating(Long id) {
        return esrbRatingRepository.getOne(id);
    }

    @Override
    public ESRBRating saveESRBRating(ESRBRating esrbRating) {
        return esrbRatingRepository.saveAndFlush(esrbRating);
    }

    @Override
    public boolean deleteESRBRating(Long id) {
        esrbRatingRepository.delete(id);
        return true;
    }
}

Repository
package net.jkratz.igdb.repository;

import net.jkratz.igdb.model.ESRBRating;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ESRBRatingRepository extends JpaRepository<ESRBRating, Long> {

}

Model
@Entity
@Table(name = "esrb_rating", schema = "igdb")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ESRBRating implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @NotNull
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Long id;

    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "title", nullable = false, length = 255)
    private String title;

    @Size(max = 65535)
    @Column(length = 65535)
    private String description;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "esrbRating")
    private List<Game> games;

    public ESRBRating() {
    }

    public ESRBRating(Long id, String title, String description) {
        this.id = id;
        this.title = title;
        this.description = description;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ESRBRating that = (ESRBRating) o;

        return Objects.equal(this.id, that.id) &&
                Objects.equal(this.title, that.title) &&
                Objects.equal(this.description, that.description);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id, title, description);
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("id", id)
                .add("title", title)
                .add("description", description)
                .toString();
    }
}

This controller code works fine, going through the repository directly.
@RestController
@RequestMapping(produces = "application/json", value="/esrbrating")
public class ESRBRatingController {

@Inject
ESRBRatingService esrbRatingService;

@Inject
ESRBRatingRepository esrbRatingRepository;

private Logger logger = LoggerFactory.getLogger(getClass());

/**
 * Returns all ESRB ratings in database
 *
 * @return List of ESRBRating objects
 * @see ESRBRating
 */
@RequestMapping(value = {"","/"}, method = RequestMethod.GET)
public ResponseEntity<List<ESRBRating>> getESRBRatings() {
    List<ESRBRating> esrbRatings = esrbRatingService.getESRBRatings();
    return new ResponseEntity<>(esrbRatings, HttpStatus.OK);
}

/**
 * Returns a single ESRB rating object if exists, otherwise returns HTTP status code 404
 *
 * @param id ID of the ESRB Rating
 * @return ESRB Rating when found
 * @see ESRBRating
 */
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getUser(@PathVariable("id") Long id) {
    logger.debug("Attempting to fetch ESRB rating with ID: {}", id);
    ESRBRating esrbRating = esrbRatingRepository.findOne(id);

    if (esrbRating == null) {
        return new ResponseEntity<>("ESRB Rating not found", HttpStatus.NOT_FOUND);
    } else {
        return new ResponseEntity<>(esrbRating, HttpStatus.OK);
    }
}

}
UPDATE:
I followed Randall Harleigh advice and set the reverse collection with @JsonIgnore. However now I am getting an entirely different stack trace. It seems now Jackson / Spring doesn't know how to serialize ESRBRating. Any tips on this one?
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: net.jkratz.igdb.model.ESRBRating_$$_jvstb5c_0["handler"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: net.jkratz.igdb.model.ESRBRating_$$_jvstb5c_0["handler"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:238)
    at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:158)
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:138)
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:155)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: net.jkratz.igdb.model.ESRBRating_$$_jvstb5c_0["handler"])
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59)
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:26)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:505)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:639)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1887)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
    ... 72 more

Update 2:
I ended up putting @Proxy(lazy = false) on the ESRBRating class and now it works fine. However I'm curious what kind of performance impacts this could have?
@Entity
@Table(name = "esrb_rating", schema = "igdb")
@JsonIgnoreProperties(ignoreUnknown = false)
@Proxy(lazy = false)
public class ESRBRating implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @NotNull
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Long id;

    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "title", nullable = false, length = 255)
    private String title;

    @Size(max = 65535)
    @Column(length = 65535)
    private String description;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "esrbRating")
    private List<Game> games;

    public ESRBRating() {
    }

    public ESRBRating(Long id, String title, String description) {
        this.id = id;
        this.title = title;
        this.description = description;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @JsonIgnore
    public List<Game> getGames() {
        return games;
    }

    public void setGames(List<Game> games) {
        this.games = games;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ESRBRating that = (ESRBRating) o;

        return Objects.equal(this.id, that.id) &&
                Objects.equal(this.title, that.title) &&
                Objects.equal(this.description, that.description);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id, title, description);
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("id", id)
                .add("title", title)
                .add("description", description)
                .toString();
    }
}

As requested here is the Game class
@Entity
@Table(name = "game", schema = "igdb",
        indexes = {@Index(name = "idx_game_title", columnList = ("title"), unique = false),
                @Index(name = "idx_game_developer", columnList = ("developer"), unique = false),
                @Index(name = "idx_game_publisher", columnList = ("publisher"), unique = false)})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Game implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @NotNull
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Long id;

    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "title", nullable = false, length = 255)
    private String title;

    @Size(max = 65535)
    @Column(name = "description", length = 65535)
    private String description;

    @Size(max = 255)
    @Column(name = "developer", length = 255)
    private String developer;

    @Size(max = 255)
    @Column(name = "publisher", length = 255)
    private String publisher;

    @NotNull
    @Size(max = 4)
    @Column(name = "players", nullable = false)
    private short players;

    @NotNull
    @Column(name = "cooperative", nullable = false)
    private boolean cooperative;

    @NotNull
    @Column(name = "release_date", nullable = false)
    @Temporal(TemporalType.DATE)
    private Date releaseDate;

    @Size(max = 255)
    @Column(name = "image", length = 255)
    private String image;

    @JoinColumn(name = "esrb_rating_id", referencedColumnName = "id", nullable = false)
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    private ESRBRating esrbRating;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "game")
    private List<GamePlatformMap> gamePlatformMap;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "game")
    private List<GameGenreMap> gameGenreMap;

    public Game() {

    }

    public Game(Long id, String title, String description, String developer,
            String publisher, short players, boolean cooperative,
            Date releaseDate, String image, ESRBRating esrbRating) {
        super();
        this.id = id;
        this.title = title;
        this.description = description;
        this.developer = developer;
        this.publisher = publisher;
        this.players = players;
        this.cooperative = cooperative;
        this.releaseDate = releaseDate;
        this.image = image;
        this.esrbRating = esrbRating;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDeveloper() {
        return developer;
    }

    public void setDeveloper(String developer) {
        this.developer = developer;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public short getPlayers() {
        return players;
    }

    public void setPlayers(short players) {
        this.players = players;
    }

    public boolean isCooperative() {
        return cooperative;
    }

    public void setCooperative(boolean cooperative) {
        this.cooperative = cooperative;
    }

    public Date getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(Date releaseDate) {
        this.releaseDate = releaseDate;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public ESRBRating getEsrbRating() {
        return esrbRating;
    }

    public void setEsrbRating(ESRBRating esrbRating) {
        this.esrbRating = esrbRating;
    }

    @JsonIgnore
    public List<GamePlatformMap> getGamePlatformMap() {
        return gamePlatformMap;
    }

    public void setGamePlatformMap(List<GamePlatformMap> gamePlatformMap) {
        this.gamePlatformMap = gamePlatformMap;
    }

    @JsonIgnore
    public List<GameGenreMap> getGameGenreMap() {
        return gameGenreMap;
    }

    public void setGameGenreMap(List<GameGenreMap> gameGenreMap) {
        this.gameGenreMap = gameGenreMap;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Game that = (Game) o;

        return Objects.equal(this.id, that.id) &&
                Objects.equal(this.title, that.title) &&
                Objects.equal(this.description, that.description) &&
                Objects.equal(this.developer, that.developer) &&
                Objects.equal(this.publisher, that.publisher) &&
                Objects.equal(this.players, that.players) &&
                Objects.equal(this.cooperative, that.cooperative) &&
                Objects.equal(this.releaseDate, that.releaseDate) &&
                Objects.equal(this.image, that.image) &&
                Objects.equal(this.esrbRating, that.esrbRating);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id, title, description, developer, publisher, players,
                cooperative, releaseDate, image, esrbRating);
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("id", id)
                .add("title", title)
                .add("description", description)
                .add("developer", developer)
                .add("publisher", publisher)
                .add("players", players)
                .add("cooperative", cooperative)
                .add("releaseDate", releaseDate)
                .add("image", image)
                .add("esrbRating", esrbRating)
                .toString();
    }
}

A: This typically happens when you are returning an object via @Responsebody (or in your case response body by way of @RestController) and an object is being serialized but has children in a LAZY collection that have not been referenced. By the time you are in your controller there is no longer a transaction active that will facilitate them being fetched (like the one your started in your @Service). You can either make your fetch strategy EAGER, bring in your collections by reference while still in your transaction or make your LAZY collections JSON Transient.

A: @JsonIgnore annotation might solve your problem, but it causes that particular field that you initially set as FetchType.LAZY to be completely ignored. A better alternative is given here
https://stackoverflow.com/a/21760361/3609067

A: I've met the same error, but no answer helped me.
It appeared that the problem was in jpa.open-in-view=false. I've removed it and now everything works as expected.

A: First download jackson-datatype-hibernate4-2.2.3.jar or higher version according to jackson-core version. Then use this code in config file and you can use fetch strategy LAZY without any error.
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;

public class ApplicationConfig extends WebMvcConfigurerAdapter
{
public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
    MappingJackson2HttpMessageConverter messageConverter = new  MappingJackson2HttpMessageConverter();

    ObjectMapper mapper = new ObjectMapper();
    //Registering Hibernate4Module to support lazy objects
    mapper.registerModule(new Hibernate4Module());

    messageConverter.setObjectMapper(mapper);
    return messageConverter;

}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    //Here we add our custom-configured HttpMessageConverter
    converters.add(jacksonMessageConverter());
    super.configureMessageConverters(converters);
}

A: Solved for Spring Boot 2.3.0 by adding to gradle.build:

implementation 'com.fasterxml.jackson.datatype:jackson-datatype-hibernate5:2.11.3'

And declaring one more bean:
@Bean
public Module datatypeHibernateModule() {
    return new Hibernate5Module();
}

A: In my case I just needed to add
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

in my application.properties file


text:
Q: How to filter a dataframe for a given time range? I have a dataframe that update every week and I want to drop the data older than 6 months
For example:
I have a dataframe from January until now.
Now it's September 14 and I want to drop the old data, in this case from January until March 14.
In the case we are in December, it´ll have from June until December, and so on.
Thank you

A: *

*Months are an arbitrary time period, since the length changes

*Use Boolean Indexing and filter against the current date minus 182 days

*Alternative, use relativedelta from the python dateutil module, which can do months
from datetime import datetime
import pandas as pd
from dateutil.relativedelta import relativedelta as rd

# This line is just for creating test data
df = pd.DataFrame({'datetime': pd.date_range(start='2020-01-01', end=datetime.today(), freq='1d').to_pydatetime().tolist()})

# filter out the everything greater than 182 days
df_updated = df[df.datetime > datetime.today() - pd.Timedelta(days=182)]

# alternatively, use the relativedelta
df_updated = df[df.datetime > datetime.today() - rd(months=6)]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Merging isn't working as expected for a column of dtype float64
I am working with two dataframes which looks like below ; just small chunk of the whole data frame. The problem is if i do an inner

join using Merge function i am getting an empty result.
DF1

COURSE_KEY   CORP_ID
2.97E+11        23096
2.97E+11        23097
2.97E+11        10987
2.97E+11        560989
2.97E+11        34678

DF2
COURSE_KEY      COURSE_UNIQUE_KEY      COURSE_ID        CERTIFICATION_ID
2.97E+11             4077               WW_13456        WFT-CK-027
2.97E+11             5789               ww_13456        NL-WFT-12121

df3 = pd.merge(Df1,Df2, on='COURSE_KEY' how='inner')

A: Merging on float values may not be the best option as float values are theoretically infinite.
For practical usage we can use int:
n = 100
df1['COURSE_KEY'] = np.round(df1.COURSE_KEY*n).astype(int)
df2['COURSE_KEY'] = np.round(df2.COURSE_KEY*n).astype(int)

df = pd.merge(df1, df2, how = 'inner', on = 'COURSE_KEY')
df['COURSE_KEY'] = df.COURSE_KEY/n
df

Output
    COURSE_KEY  CORP_ID COURSE_UNIQUE_KEY   COURSE_ID   CERTIFICATION_ID
0   2.970000e+11    23096   4077    WW_13456    WFT-CK-027
1   2.970000e+11    23096   5789    ww_13456    NL-WFT-12121
2   2.970000e+11    23097   4077    WW_13456    WFT-CK-027
3   2.970000e+11    23097   5789    ww_13456    NL-WFT-12121
4   2.970000e+11    10987   4077    WW_13456    WFT-CK-027
5   2.970000e+11    10987   5789    ww_13456    NL-WFT-12121
6   2.970000e+11    560989  4077    WW_13456    WFT-CK-027
7   2.970000e+11    560989  5789    ww_13456    NL-WFT-12121
8   2.970000e+11    34678   4077    WW_13456    WFT-CK-027
9   2.970000e+11    34678   5789    ww_13456    NL-WFT-12121

A: It is not exactly clear what the exact issue might be, but a good guess is perhaps that there are differences in the float values. Float comparisons should be done by checking closeness and not sameness because there are often decimal variations.
Depending on the context, you might need to use a better key datatype, say an int or a string, or check for closeness, say by doing something [this answer][1] does.


text:
Q: Elasticsearch multinode setup I want to setup an 3 node cluster setup in elasticsearch, but I unable to setup, getting error like connection refused in data machine, master machine starting fine, but it shows like 0 nodes added.

A: I would recommend to read tutorial first, like

*

*https://www.digitalocean.com/community/tutorials/how-to-set-up-a-production-elasticsearch-cluster-on-ubuntu-14-04

*https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-zen.html
then ask precise question here about a specific issue.
About your question, I think you didnt configure discovery.zen.ping.unicast.host fine, so nodes dont know each other.
Also, when you post a question, please post:

*

*elasticsearch version

*environnement (AWS, VM ...)

*configuration sample

Welcome at SO!


text:
Q: Loess: strange values of the slope on a parametric predictor conditioned on a locally weighted regression parameter this is my first question in StackOverflow, so I hope to get it right...
I am trying to fit a loess model with two predictors, one of them is locally weighted while the other is parametric.  Once the model is fitted, I want to get the slope of the regression line on the parametric predictor, conditioning on a certain value of the non-parametric predictor.  When computing this slope with whichever two values from the regression line I should get a constant value corresponding to the slope.  However, if I compute the slope with every two successive values, I get a curve resembling much of a parabola.  Here you have some code for showcasing this issue:
## DATA

criterion <- c(
  -1.8914741214789, -0.864604956700496, 2.43013372852099, -1.32227168040904,
  0.861585875211724, -1.25506145955845, 1.1201893940246, -1.18560159611826,
  1.24871681364416, -1.24362634687504, -2.22058652097061, -0.67920682239687,
  -1.14096010679208, 0.228758533000768, -1.3607742780652, 0.473165865126464,
  0.0438948075908679, -1.14355404117161, 2.60406860120487, 0.539583593348819,
  -0.599388766026817, -1.14918693916554, -0.17334788506616, -0.836478866743926,
  2.88908329995278, -0.401016464464891, -0.292311619619775, 1.12804091879547,
  3.6733647991105, -3.31190363769332, -0.672558641084861, 0.498844902537884,
  -0.037062115762172, -1.02017987978252, -0.854805324374525, 1.34168735130207,
  -0.242996720017973, 1.14871933640721, -0.736312690622741, -2.51965992948912,
  -3.16327863554555, -0.269020543067839, 0.552150179356176, 0.320523449469915,
  1.14736382025547, 0.891590469554733, -0.717678520852477, 3.15631635301073,
  -0.225648864790169, -1.35189421566795, -0.558073572773821, -1.33356547103824,
  -2.01215450549957, 1.63719762873429, -2.0218275161466, 0.513289109719022,
  -1.30263029019454, 1.85949704911488, -1.22544429584118, 0.336732253617053,
  -2.45126282746359, -4.94155955259729, 0.743231639698684, 1.04320562270113,
  3.99232225357353, -1.07752259470057, -0.353671379249384, -0.748973055922694,
  0.467443998802691, 0.966013090920868, 1.32739645813748, 1.07159468103619,
  -1.8542024758483, 0.360922743179635, -4.99642432601298, 0.596072047320551,
  -1.48256500350222, -0.251689130094422, -0.104867519535428, -3.23675187957067,
  1.15657910171856, -0.640772355492231, 2.21198640279181, -0.229386564567888,
  -2.8014148535931, 0.325261825780768, 1.65431768179619, -0.701353356393564,
  1.56301740126489, -2.91989037858617, 0.560634128846807, -3.40972988669857,
  0.519955616184439, -0.673752119923202, -0.126511467211613, -1.49156456253545,
  2.68041989003066, -3.18246878051744, -1.05338046600476, -0.122679130411665,
  0.619202563903638, -2.80132012240656, -1.50106228060585, -1.78428153598023,
  -0.17959372353835, -3.7657930817963, 1.74830598714522, 0.199267717912346,
  -0.187088254090319, -0.431926901631399, -2.50168001668916, -0.715294537723936,
  4.8050892573889, 3.48017935641437, -2.29413209640673, 1.88045620792631,
  -0.125724128270772, -0.514660621563394, 1.28920199656138, -0.888250921411933,
  -1.53336797414911, 0.566890809767711, 2.18492239723917, 1.45986142278563,
  2.29475550546227, -2.91360806155925, -1.28474245565384, -1.15236199251384,
  -2.68344935749574, -1.0406761060411, 0.236606541573282, -1.0577344636865
)

lw.predictor <- c(
  3.97543828892376, 3.74367045733871, 2.8031293667213, 3.12721154621725,
  3.57809163186571, 3.85490258924953, 3.04509486547235, 3.06527167000886,
  3.42172751371031, 3.48342454710053, 3.03382754767655, 3.29840143930276,
  3.42532870135535, 3.3466401061363, 4.19719410513314, 4.27624851591474,
  3.90521253346176, 3.66434131328865, 3.78008480009251, 3.26961939052607,
  3.37557706887951, 3.07887188021758, 3.20615845753053, 3.25681582455448,
  3.07575583761175, 3.4678563115072, 3.63412290863538, 2.7341072520575,
  3.04486992771651, 4.0244118093156, 2.75978954925269, 2.94469571886678,
  3.64916954335701, 3.23529338509991, 3.09993371559714, 3.92201374051927,
  2.63693470862178, 3.19438720086359, 4.10395732841177, 4.14695795420843,
  3.37963279191973, 2.75059146814963, 3.05430305033533, 4.07380539679535,
  3.41070032578776, 3.52175236580135, 3.9922870844146, 2.83689005875791,
  3.59280102122038, 3.744585131656, 4.07464596327428, 2.94632345777042,
  3.79563556141373, 2.92157773101387, 3.60631105869347, 3.90380916892684,
  3.4349134104059, 2.86428168814471, 2.80459505537921, 3.52738795051305,
  3.90100092529829, 3.95557522270349, 2.88144750533953, 3.4177217437656,
  2.72281079587565, 3.44307922077723, 3.58191805968554, 2.85374063580388,
  3.61825659978916, 3.35154840518957, 2.78055872970075, 3.31559205647068,
  3.72845408487401, 3.45439961676827, 3.47673283886995, 3.38348122582045,
  2.88524826215121, 3.37314129436951, 4.17608980116535, 2.78621853030773,
  4.23989532049638, 2.65428059546312, 2.75954135557898, 3.90836826127649,
  3.70911502202012, 3.9502037401938, 2.72934334016319, 3.56908337873796,
  3.53107535330031, 4.10445798400541, 3.37029733251965, 2.77784779211612,
  4.00205426701893, 3.390559011573, 3.75061638769833, 3.67591196400612,
  4.00034245109432, 4.19507212536165, 2.64290209936905, 2.84965751366817,
  2.93584367468566, 3.5792399897338, 3.87103752330681, 4.11112756588916,
  3.69820393282565, 3.47909608792875, 3.021611653787, 3.38833615773409,
  3.53688974115618, 3.86802841711593, 3.04014239032067, 3.83441517392514,
  2.78055872970075, 2.95676609717858, 3.46963343371941, 2.69652236718191,
  4.21169279083643, 3.59508797308864, 2.90229007358549, 3.74055889165213,
  4.22533130742836, 3.10942006661772, 2.81532012340698, 3.39540382330109,
  3.11580153059886, 2.73435775434875, 3.80464748245529, 3.63431137604942,
  4.09744323888573, 2.77908036429911, 3.30047734198123, 3.7238586557053
)

par.predictor <- c(
  94.3333333333333, 105.333333333333, 135.666666666667, 113.666666666667,
  116.333333333333, 112.666666666667, 117.333333333333, 100.333333333333,
  118, 118.333333333333, 119.666666666667, 109.666666666667, 116.333333333333,
  107.666666666667, 110.666666666667, 97, 99.6666666666667, 108.666666666667,
  118.333333333333, 119, 106.333333333333, 121.666666666667, 103,
  132, 99, 121.666666666667, 99.6666666666667, 104.666666666667,
  124.333333333333, 106.666666666667, 118.666666666667, 111, 125,
  101.666666666667, 101, 103, 102, 108.333333333333, 119.333333333333,
  131.333333333333, 105.666666666667, 118.666666666667, 124.333333333333,
  111.333333333333, 108.333333333333, 126.666666666667, 111, 107.333333333333,
  118.666666666667, 120.333333333333, 114, 117.666666666667, 118,
  104.666666666667, 115.333333333333, 117.666666666667, 101.666666666667,
  118, 103.333333333333, 120, 105, 106.666666666667, 104.333333333333,
  112.333333333333, 109.333333333333, 103.333333333333, 114, 112,
  122.333333333333, 115, 135.666666666667, 102.666666666667, 116,
  115.333333333333, 118, 107, 104, 113.666666666667, 130, 128.333333333333,
  110.333333333333, 127.666666666667, 129.333333333333, 107, 110.666666666667,
  97.3333333333333, 120.333333333333, 90.6666666666667, 122.333333333333,
  104, 93.6666666666667, 102.333333333333, 111.333333333333, 121.666666666667,
  127.666666666667, 115, 103, 91.6666666666667, 150.666666666667,
  127, 126.333333333333, 111.666666666667, 117.666666666667, 109,
  103, 104, 103.666666666667, 109, 122.666666666667, 122, 116.333333333333,
  117.333333333333, 102, 156, 105.666666666667, 106.333333333333,
  124.333333333333, 105.333333333333, 121.333333333333, 92.6666666666667,
  117.666666666667, 122.666666666667, 88.3333333333333, 119, 121.333333333333,
  97, 107, 109.333333333333, 113.666666666667, 103.666666666667,
  117, 112.666666666667
)

# Predictor variables are standardized prior to fitting the loess model
data <- data.frame(criterion = criterion, lw.predictor = scale(lw.predictor), par.predictor = scale(par.predictor))

## MODEL FIT

lwr.fit <- loess(
  criterion ~ lw.predictor * par.predictor, data,
  parametric = "par.predictor",
  span = .7,
  family = "gaussian", degree = 2, drop.square = "par.predictor",
  normalize = FALSE
)

## PREDICTION ON GRID

# Statistics to standardize axes (based on the sample)
par.mean <- mean(par.predictor)
par.sd <- sd(par.predictor)
lw.mean <- mean(lw.predictor)
lw.sd <- sd(lw.predictor)

# Axes
pred.lw.axis <- (sqrt(seq(7, 18.25, by = 1/12)) - lw.mean) / lw.sd
pred.par.axis <- (89:156 - par.mean) / par.sd

# Grid generation
std.prediction.values <- expand.grid(
  lw.predictor = pred.lw.axis,
  par.predictor = pred.par.axis
)

# Prediction
lwr.prediction <- predict(lwr.fit, std.prediction.values, se = TRUE)

## GRAPHIC REPRESENTATION OF THE PARAMETRIC REGRESSION

# Slope computing
test.values <- lwr.prediction$fit[1, ]
slopes <- (test.values[-1] - test.values[-length(test.values)]) / (pred.par.axis[-1] - pred.par.axis[-length(pred.par.axis)])

plot(slopes, type = "l", ylab = "Slopes")

Well, if you run this code, you will get the plot of a (near) parabolic curve as I said.  That is very weird in my opinion; one could think it is due to quantification error, but I doubt this as it would be somehow random and the values much smaller.  I may be getting it wrong, but I think the plot should show a constant line.  On the other hand, I have tried also changing the parameters of the loess model, but the problem seems to be persistent.  I hope somebody can help me, I've searched for this topic in the forums and didn't find any similar question.
Thank you so much in advance.


text:
Q: Python / Beautiful Soup - meta content not matching source I'm trying to grab meta data content from a website. Here is the code:
import requests
from bs4 import BeautifulSoup

url = "https://discord.com/invite/midjourney"
result = requests.get(url=url)
soup = BeautifulSoup(result.content, 'html5lib')

target = soup.find("meta", property="og:description")
print(target)

This returns:
<meta content="Discord is the easiest way to communicate over voice, video, and text.  Chat, hang out, and stay close with your friends and communities." property="og:description"/>

However, looking at the page source, the content is different and it includes the number of members. The number of members is what I'm after.
<meta property="og:description" content="The official server for Midjourney, a text-to-image AI where your imagination is the only limit. | 2,472,611 members" />

Is there some type of script dynamically changing the meta content? Any ideas on how to get under the meta to the actual data?

A: try:
import requests
from bs4 import BeautifulSoup

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}
session = requests.Session()
r = session.get(url, timeout=30, headers=headers)     # print(r.status_code)
soup = BeautifulSoup(r.content, 'html.parser')

#1. extract all meta tags from the page, return list of tags
print(soup.select('meta'))

[<meta charset="utf-8"/>,
 <meta content="width=device-width, initial-scale=1.0, maximum-scale=3.0" name="viewport"/>,
 <meta content="The official server for Midjourney, a text-to-image AI where your imagination is the only limit. | 2,473,729 members" name="description"/>,
 <meta content="summary_large_image" name="twitter:card"/>,
 <meta content="@discord" name="twitter:site"/>,
 <meta content="Join the Midjourney Discord Server!" name="twitter:title"/>,
 <meta content="The official server for Midjourney, a text-to-image AI where your imagination is the only limit. | 2,473,729 members" name="twitter:description"/>,
 <meta content="Join the Midjourney Discord Server!" property="og:title"/>,
 <meta content="https://discord.com/invite/midjourney" property="og:url"/>,
 <meta content="The official server for Midjourney, a text-to-image AI where your imagination is the only limit. | 2,473,729 members" property="og:description"/>,
 <meta content="Discord" property="og:site_name"/>,
 <meta content="https://cdn.discordapp.com/splashes/662267976984297473/4798759e115d2500fef16347d578729a.jpg?size=512" property="og:image"/>,
 <meta content="image/jpeg" property="og:image:type"/>,
 <meta content="512" property="og:image:width"/>,
 <meta content="512" property="og:image:height"/>,
 <meta content="https://cdn.discordapp.com/splashes/662267976984297473/4798759e115d2500fef16347d578729a.jpg?size=512" name="twitter:image"/>]

#2. extract all content of the meta tags, return list of text
content_only = [i.get('content') for i in soup.select('meta') if i.get('content')]

print(content_only)

['width=device-width, initial-scale=1.0, maximum-scale=3.0',
 'The official server for Midjourney, a text-to-image AI where your imagination is the only limit. | 2,473,729 members',
 'summary_large_image',
 '@discord',
 'Join the Midjourney Discord Server!',
 'The official server for Midjourney, a text-to-image AI where your imagination is the only limit. | 2,473,729 members',
 'Join the Midjourney Discord Server!',
 'https://discord.com/invite/midjourney',
 'The official server for Midjourney, a text-to-image AI where your imagination is the only limit. | 2,473,729 members',
 'Discord',
 'https://cdn.discordapp.com/splashes/662267976984297473/4798759e115d2500fef16347d578729a.jpg?size=512',
 'image/jpeg',
 '512',
 '512',
 'https://cdn.discordapp.com/splashes/662267976984297473/4798759e115d2500fef16347d578729a.jpg?size=512']

#3. extract the members data that you need
members_content_only = list(set([i.get('content') for i in soup.select('meta') if i.get('content') and 'members' in i.get('content')]))

print(members_content_only)

['The official server for Midjourney, a text-to-image AI where your imagination is the only limit. | 2,473,729 members']

A: There is indeed js underneath. I found a different method to extract this using selenium and bs4.
from bs4 import BeautifulSoup as bs
from selenium import webdriver
import requests
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.support.ui import WebDriverWait

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)

url = "https://discord.com/invite/midjourney"
driver.get(url)

WebDriverWait(driver, 15)

page = driver.page_source
html = bs(page, 'html.parser') #print(html)

for script in html(["script", "style"]):
    script.extract()
text = html.get_text()

lines = (line.strip() for line in text.splitlines())
text = '\n'.join(line for line in lines if line)

final_string = text.replace(",","")
start = final_string.find("Online")+6
end = final_string.find("Members")-1
subs = final_string[start:end]
subs_final = int(subs)
print(subs_final)

Output:
2496142

This was a roundabout way to get what I wanted. Lmk if there are more efficient ways to do this.


text:
Q: MYSQL query to arrange list of categories hierarchy I have a database list which looks this:
ID      Name      Parent_ID
1       Cat 1     NULL
2       Cat 2     NULL
3       Cat 3     2
4       Cat 4     3
5       Cat 5     1
6       Cat 6     2

The out put that I am trying to get is all the categories arranged in order of hierarchy and sorted alphabetically. Like this:
Cat 1
    Cat 5
Cat 2
    Cat 3
        Cat 4
    Cat 6

I am really not sure how to quite get this result, this is what I have at the moment, but does not work:
 SELECT * from Categories AS parent
 LEFT JOIN Categories AS child ON child.Parent_ID = parent.ID

Any help is appreciated.

A: I think, you need  build categories tree in PHP. Try it (example):
$sql = 'SELECT * from Categories ORDER BY parent_id ASC';
$items = // fetch as array of assoc.arrays

// example
// $items = array(
//     array('id' => 3, 'parent_id' => 1 ,'name'=>'..'),
//     array('id' => 4, 'parent_id' => 3, ,'name'=>'..'),
//     array('id' => 7,  'parent_id' => 0, ,'name'=>'..'),
//);

$childs = array();
foreach($items as &$item) $childs[$item['parent_id']][] = &$item;
unset($item);

foreach($items as &$item) if (isset($childs[$item['id']]))
    $item['childs'] = $childs[$item['id']];
unset($item);

$tree = $childs[0];

echo '<pre>';
print_r($tree);
echo '</pre>';


text:
Q: Name typedef directly from scanf Lets say I have a custom type
typedef struct {
    char code[3];
    int max_capacity;
    int state;
} Train;

I want to fill an array of these structs using scanf to read a 3char code, the issue is, I want to name the "Train" type directly with the input from scanf without having to attribute a "placeholder name" like A before retrieving the scanf value.
So lets say I input TRI for example I want to name it TRI as well as TRI.code = TRI
So, avoid something like this
void add_train(){
Train A
scanf("%s", &A.code)

And try to name it directly
void add_train(){
Train scanfstring
scanf("%s", &scanfstring.code)

What would be the best way to go about this without multiple scanf calls or attributions?

A: Struct transporter {
   int max_capacity;  int state;
};

typedef struct transporter Train;

    Void add_train() {//assumed not parameterized
    Train TRI[3];
     int code =3;
    (int i=0; i<3; i++)
    scanf("%d %d", &TRI[i].max_cpacity, TRI[i].state);
}

//I put the code as far as whar I understood from his explainatation which is so confusing.
// okay these block says that you have an transporter collection and you want to inherit a train from it. Typedef for this purpose but I believe you dont even need you can chane "transporters" to "train".
// and finally he put Not parameterazed function i didnt change; every time you call this function you will create three trains and with for loop you are able to enter capacity and state in the same line for each train


text:
Q: Time zone conversion while loading in snowflake from pyspark I am writing a data frame in snowflake using pyspark, that data frame has a column with a timestamp. I have set it in US/Eastern time zone using spark config, but when I write it to snowflake it gets converted to UTC by default. I want it to be in US/Eastern only.
What should I add in snowflake spark connector options that can fix my problem?
PS: I have tried sfOptions["sfTimezone"] = 'America/New_York', sfOptions["sfTimezone"] = 'spark'.
Both don't work :(

A: Spark provides only one type of timestamp, equivalent to the Scala/Java Timestamp type. It is almost identical in behavior to the TIMESTAMP_LTZ (local time zone) data type in Snowflake. As such, when transferring data between Spark and Snowflake, Snowflake recommends using the following approaches to preserve time correctly, relative to time zones:

*

*Use only the TIMESTAMP_LTZ data type in Snowflake.

Note The default timestamp data type mapping is TIMESTAMP_NTZ (no time zone), so you must explicitly set the TIMESTAMP_TYPE_MAPPING parameter to use TIMESTAMP_LTZ.

*

*Set the Spark time zone to UTC and use this time zone in Snowflake (i.e. don't set the sfTimezone option for the connector, and don't explicitly set a time zone in Snowflake). In this scenario, TIMESTAMP_LTZ and TIMESTAMP_NTZ are effectively equivalent.

To set the time zone, add the following line to your Spark code:
java.util.TimeZone.setDefault(java.util.TimeZone.getTimeZone("UTC"))

If you don't implement either of these approaches, undesired time modifications might occur. For example, consider the following scenario:

*

*The time zone in Spark is set to America/New_York.

*The time zone in Snowflake is set to Europe/Warsaw, which can happen by either:

*

*Setting sfTimezone to Europe/Warsaw for the connector.

*Setting sfTimezone to snowflake for the connector and setting the TIMEZONE session parameter in Snowflake to Europe/Warsaw.

*

*Both TIMESTAMP_NTZ and TIMESTAMP_LTZ are in use in Snowflake.

In this scenario:

*

*If a value representing 12:00:00 in a TIMESTAMP_NTZ column in Snowflake is sent to Spark, this value doesn't carry any time zone information. Spark treats the value as 12:00:00 in New York.

*If Spark sends this value 12:00:00 (in New York) back to Snowflake to be loaded into a TIMESTAMP_LTZ column, it is automatically converted and loaded as 18:00:00 (for the Warsaw time zone).

*If this value is then converted to TIMESTAMP_NTZ in Snowflake, the user sees 18:00:00, which is different from the original value, 12:00:00.
To summarize, Snowflake recommends strictly following at least one of these rules:

*

*Use the same time zone, ideally UTC, for both Spark and Snowflake.

*Use only the TIMESTAMP_LTZ data type for transferring data between Spark and Snowflake.

The behavior you see is also explained in detail here.


text:
Q: Помогите с сайтом. Как разъединить ссылки в html
ссылки, которые слева должны быть разъединены

header .logo {
 color: #fff;
 font-size: 15px;
 padding-top: 5px;
 text-align: center;
 margin-right: 35%;
 margin-bottom: 10px;
}

header .logo span {
 font-size: 2.3em;
 line-height: 45px;
 margin-left: 43%;

}

header .about a {
 position: absolute;
 top: 25px;
 left: 100px;
 word-spacing: 6px;
 text-decoration: none;
 color: #fff;

}

#number {
 position: absolute;
 right: 60px;
 top: 30px;
 color: #fff;
 line-height: 10px;
}

   MoreTours

  Возможности
  Преимущества
  Контакты

0-000-000-00-00

A: Как минимум, не пытаться каждой ссылке присвоить position: absolute;.

header .logo {
 color: #fff;
 font-size: 15px;
 padding-top: 5px;
 text-align: center;
 margin-right: 35%;
 margin-bottom: 10px;
}

header .logo span {
 font-size: 2.3em;
 line-height: 45px;
 margin-left: 43%;

}

header .about a {
 position: relative;
 word-spacing: 6px;
 text-decoration: none;
 color: #fff;
    margin-right: 10px;

}

.links {
  display: flex;
  align-items: center;
  top: 25px;
  left: 60px;
  position: absolute;
}

#number {
 position: absolute;
 right: 60px;
 top: 30px;
 color: #fff;
 line-height: 10px;
}

header {
  background: red;
}

   MoreTours

      Возможности
      Преимущества
      Контакты

0-000-000-00-00

А вообще, рекомендую задуматься над тем, что Вы делаете. Строить верстку сайта на абсолютных позициях - плохая практика.


text:
Q: How to move Socket.io io.on('connection') code another js file? SITUATION (MAIN QUESTION START is under)
Recently, I practice Node.js web hosting.
I generate folder with express-generator, like under.
$ express --view=pug # default jade, change pug
$ npm install

$ ls
app.js bin node_modules package.json public routes views

For Create new page named chat.js, in app.js
var chatRouter = require('./routes/chat');

...

app.use('/chat', chatRouter);

and create /views/chat.pug, /routes/chat.js simply.

Now. I want to use socket.io.
Some sample codes leads me like under.
1. change app.js
var app = express(); # express generate this line
app.io = require('socket.io')();

...

app.io.on('connection', function(socket) {
  console.log('app.js connection');
});

2. change ./bin/www
var server = http.createServer(app); # express generate this line
app.io.attach(server);

3. change /views/chat.pug
    <script src="/socket.io/socket.io.js"></script>
    <script>
        $(function() {
            var io = socket();
        });
    </script>

When I run server with sudo node ./bin/www and connect page http://www.sample.com/chat, log app.js connection is comes out. Greatly.
MAIN QUESTION START
But, I want to seperate under codes NOT app.js, for example, /routes/chat.js or somewhere for make short app.js
app.io.on('connection', function(socket) {
  console.log('app.js connection');
});

I try like under, but it not works that I expected.
In /routes/chat.js
var io = require('socket.io')(server);
io.on('connection', function(socket) {
  console.log('chat.js connection'); # NOT COMES HERE
});

Please help me to avoid make app.js longer.

A: In the bin, import another module and pass app to it
// app.js
var app = express(); # express generate this line

app.io = require('socket.io')();
require('../new-file')(app)

// new-file.js
module.exports = (app) => {
   app.io.on('connection', function(socket) {
      console.log('app.js connection');
   });
}


text:
Q: Multiple CAML query to filter Data list view My Custom list has four columns(Doc ID, Created by, Assigned To, Assigned date). I want to filter the data in Data list view.
In my page, there are 4 text boxes and a Button is there for the user input (Doc ID, Created by, Assigned To, Assigned date )
When the user enters his input in text boxes and clicks the save button how do i change the filter query at runtime.

A: You can use XmlDefinition property of the XsltListViewWebPart. Here you can find good example how to do it

A: You can generate CAML query on page dynamically and then send in to List view as string parameter (in query string, or in hidden form field):
             <View>
                <Query>
                    {CAMLQueryString}
                </Query>
                <ViewFields>
                 ...
                </ViewFields>
                <RowLimit Paged="TRUE">30</RowLimit>
                <Aggregations Value="Off"/>
                <Toolbar Type="Standard"/>
            </View>


text:
Q: devise_invitable not able to accept invitations anymore (but works via console) I am using devise_invitable to create guest accounts to access a document. When accessing a document, a guest can click on an upgrade button that will upgrade to a full account. Clicking on the upgrade button is accepting devise_invitable invitation.
Was previously working: no longer working.
Environment:

*

*rails 4.2.3 (recently upgraded)

*devise 3.4.1

*devise_invitable 1.3.6

I use a header partial for a guest user that generates an upgrade link:
<% @invite_link = accept_user_invitation_url(invitation_token: @invite_token) %>
<%= link_to "Upgrade", @invite_link, class: "btn btn-danger btn-lg" %>

@invite_token is created like:
user = current_user
user.invite! do |u|
  u.skip_invitation = true
end
@invite_token = user.raw_invitation_token

So link_to helper generates something like: https://myapp/users/invitation/accept?invitation_token=vv_JqeFDLfyX65tx2KhR
Except when I click on the link, it takes me to: https://myapp/users/sign_in
With error message: The invitation token provided is not valid!
Log reports something like:
Started GET "/users/invitation/accept?invitation_token=vv_JqeFDLfyX65tx2KhR" for 31.15.32.222 at 2015-10-15 19:18:34 +1100
Processing by Devise::InvitationsController#edit as HTML
  Parameters: {"invitation_token"=>"vv_JqeFDLfyX65tx2KhR"}
  User Load (5.9ms)  SELECT  "users".* FROM "users" WHERE "users"."invitation_token" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["invitation_token", "ea9be9890c684e13ece13ec02f89bade81fcd3ac1fb982db72d8f8561d0cf289"]]
Redirected to https://myapp/
Filter chain halted as :resource_from_invitation_token rendered or redirected
Completed 302 Found in 53ms (ActiveRecord: 5.9ms)
Started GET "/" for 31.15.32.222 at 2015-10-15 19:49:52 +1100
Processing by PagesController#index as HTML
Redirected to https://myapp/users/sign_in
Completed 302 Found in 11ms (ActiveRecord: 0.0ms)

Am able to make this work via rails console.
If I run rails console in parallel, I am able to step through the above steps and generate an accept_invitation link that works as expected (i.e. it prompts user to set a password for the full account).
NB: the raw_invitation_token is different in the rails console session.
What am I missing?

A: I found code that called user.invite! to generate raw_invitation_token when page was displayed and after the accept_invitation link was generated. This meant that the token in the accept_invitation link was now outdated.
Going via the console, this code was not called as no controller, view or javascript components are invoked. So when using the console, things worked as expected.
Fixed and all back to normal.


text:
Q: Delphi Anchor and Form.HorizontalScrollbar.Range Panel Anchor akRight ignores HorizontalScrollbar.Range I have here a very simple form for demonstration purposes . On Form Show I only do this :
  Form1.HorzScrollBar.Range:=1200;

My Problem is if I resize the Form and the Formsize becomes less then 1200 , the Panel akRight anchor is not taking into account Actual Form size , instead it seems to look at the Visible Form Size...
See Screenshot
I am probably doing here something wrong , can someone enlighten me.

A: To make the panel growing with the form beyond 1200, but prevent the panel from shrinking below 1200, you can set for the panel:

*

*Set the akRight anchor (in addition to akLeft)

*Set the Constraint.MinWidth = 1200


text:
Q: Static discharge out of 3 volts button battery I am starting to get interested in static electricity
I have found this which is very cool but I do not know how I can control the output voltage.
http://www.instructables.com/id/How-to-build-the-Worlds-Smallest-Electronic-Shock/#intro
What I need to do is to use a 3 Volts Button Battery and get a 50-500 volt static charge from it. And I need the device to be very small.
What can I change in order to control the voltage? and is a 3 volts button battery good to keep this thing alive for months? and lastly, can I flip the battery to control the out put charge (negative or positive)?

A: Take a battery of any size, and a coil of wire, the more the merrier.
Connect both ends of the wire to the battery, and then break the circuit.
You will see a spark. The more wire in the coil, the bigger the spark.
To get across the air gap takes thousands of volts.
If your victim is also connected to both ends of the wire, she will feel a jolt.
The exact voltage depends on how much electrical resistance the victim has, and that is very hard to control.
What's happening is while the battery is connected to the coil, current builds up in the coil and stores energy in its magnetic field.
When you break the connection, the current can't suddenly stop because all that energy has to go somewhere.
So it drains through whatever resistor it can find, whether it's the air gap, or your former friend.

A: That shocker will consume a lot of power. The battery will be empty within an hour.
But you could pair that circuit with an oscillator.
http://www.555-timer-circuits.com/flashing-led.html
Build the oscillator such that it turns the shocker on for a few ms every few seconds. That way it can last for weeks.
Also you can not flip the battery. It won't work at all if you do that. You can however flip the neon bulb.
Controlling the voltage is difficult with such a simple circuit. You could put a resistor between the battery and the rest of the circuit. That should reduce the output.
But why does it have to be a neon bulb? An LED would be easier to operate.


text:
Q: Doubt in the definition of closed subvarieties I'm trying to understand this definition in Fulton's algebraic curves:

In order to be $Y$ a variety, $\overline Y$ has to be an irreducible algebraic set of $\mathbb P^{n_1}\times\ldots\times\mathbb A^m$. The author shows $\overline Y$ is irreducible, but not algebraic set. How can we prove $\overline Y$ is an algebraic set? is this really necessary?
I need help
Thanks in advance

A: The closed sets in the Zariski topology are exactly the algebraic sets. Thus, the closure $\overline{A}$ of any subset $A$ of $X$ is always an algebraic set.


text:
Q: How to get d3 instance from d3 selection? I have a method that gets a d3 selection as an argument:
function foo(selection){

}

Inside that function I need the d3 instance. Instead of passing the d3 instance as an extra argument I would like to get it from the selection. Is that possible?
function foo(selection){
    var d3 = selection.getD3();
    var element = document.createElement('div');
    d3.select(element);
}

Edit
The methods provided by the selection do not include something like "getD3":
append
attr
call
classed
clone
constructor
data
datum
dispatch
each
empty
enter
exit
filter
html
insert
interrupt
lower
merge
node
nodes
on
order
property
raise
remove
select
selectAll
size
sort
style
text
transition

A: You can add a reference to d3 by adding it to the selection object
var mySelection = d3.selectAll('your_selection_criteria');

mySelection.d3_reference = d3;  //mySelection is a JSON object, so
                                // you can attach anything to it

foo(mySelection);

function foo(selection) {
    var myD3 = selection.d3_reference;
    // now myD3 is d3
}


text:
Q: Match 5th and 6th character to select value I need to match the 5th and 6th character in an input field to a value from a select menu.
I'll post some dummy HTML to demonstrate what I mean
<select class="mySelect">
  <option value="AB"></option>
  <option value="CD"></option>
  <option value="EF"></option>
  <option value="GH"></option>
</select>

<input type="text" class="myInput" />

I need to find for example if the input is (1111AB111) then alert(true)... all other characters are not important, I need to match the 5th and 6th character.

A: Use regex
var n = str.match(/^.{4}(.{2})/);

and then n[1] is 5th and 6th character string.

A: Regular expressions are powerful but can drain performance unnecessarily in cases like yours. What you really need is a simple substring function:
if (yourString.substr(4, 2) == theOptionValue) {
    // Do something
}

You could also put this in a switch statement, depending on your circumstances. jQuery is a fantastic tool, but one mustn't forget that it is a library and not a language of its own and that a lot can be done with pure old fashioned JavaScript.

A: This code is tested and working...
$(function() {
    $("input.myInput").on("keyup", function() {
        var text = $(this).val();
        if (text.length < 6) return;
        text = text.substr(4, 2);
        var $option = $("select.mySelect option[value='" + text + "']");
        if ($option.length == 0) return;
        alert("Found " + text);
    });
});

Here's a jsfiddle...
http://jsfiddle.net/UBhy9/

A: try (tested):
$( "input.myInput" ).bind('keyup', function() {
    var fifthandsixth = ($(this).val())[4] + ($(this).val())[5];
    if ( $(".mySelect > option[value='" + fifthandsixth + "']")[0] ) {
        alert("true");
    } else {
        // alert("false");
    }
});

A: I've made  a jsFiddle, showing a rough way of doing it, here: http://jsfiddle.net/TN5Ru/
function twoMatchingCharacters(selectElement,inputElement){
    if($(selectElement).val() === $(inputElement).val().slice(4,6)){
      $('p').text('That is a match');
                  }else{
      $('p').text('That is not a match');
                  }
}

$('.mySelect').change(function(){
    twoMatchingCharacters($('.mySelect'),$('.myInput'));
});

$('.myInput').keyup(function(){
    twoMatchingCharacters($('.mySelect'),$('.myInput'));
});

Obviously, you won't want to change the text of every paragraph on the page, and there are prettier ways of binding the function, but you should get the idea.


text:
Q: Change the height of an html element when a button gets clicked with ajax I have a login.php page. The page contains php and html. When the login button gets clicked it will either log me in and Forward me to the welcome page or output "your Password or username is invalid". I want to change the height of an element. Sadly this doesen't work because php is reloading the page(witch makes sense). I heard i can make it work with Ajax.
Does somebody know how to do that?
Button:
<input id="button" type="submit" value="Log In" onclick="ausgabe();">

Javascript:
function hardgainer(){
    var gainheight = document.getElementById('gain')
    gainheight.style.height ="220px";
    document.getElementById('gain').innerHTML = gainheight;
}

function ausgabe(){
    document.getElementById('button') =
        hardgainer();
}

A: You are submitting the form and therefore the page reloads. You should change the type to type="button" and then you can make something like this:

function hardgainer(){
    var gainheight = document.getElementById('gain')
    gainheight.style.height = "220px";
}

document.getElementById("gbutton").addEventListener("click", function() {
  hardgainer()
})
#gain {
  background: red;
  width: 200px;
}
<input id="gbutton" type="button" value="Log In">


text:
Q: ValueError: Found array with dim 3. Estimator expected <= 2 unresolved when applying scaler fit transform to an array it throw s the error as per below:
ValueError                                Traceback (most recent call last)
<ipython-input-72-b625cb047701> in <module>()
      1 # Normalize X_test of well 4
----> 2 X_test4 = scaler.fit_transform(X_test4)
      3
      4 # Predict to well 4
      5 y_pred4 = model.predict(X_test4)```

5 frames
/usr/local/lib/python3.7/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator)
    715         if not allow_nd and array.ndim >= 3:
    716             raise ValueError("Found array with dim %d. %s expected <= 2."
--> 717                              % (array.ndim, estimator_name))
    718
    719         if force_all_finite:

ValueError: Found array with dim 3. Estimator expected <= 2.```

[array([[  0.4301,   2.2201, 110.561 ,   1.2695,  12.7594],
        [  0.3993,   2.2409, 123.672 ,   1.9426,  12.6951],
        [  0.3847,   2.2547, 128.233 ,   2.0148,  12.6857],
        ...,
        [  0.2135,   2.5017, 122.618 ,   3.8965,  12.5515],
        [  0.2195,   2.5081, 117.772 ,   3.8736,  12.5859],
        [  0.2272,   2.5072, 114.267 ,   3.7845,  12.5653]])]

my array:
np.array(X_test4).shape
# (1, 12080, 5)


text:
Q: Not using Java modules, but getting module related exception I have the following codes which I got from here.
import net.openhft.chronicle.core.OS;
import net.openhft.chronicle.queue.ChronicleQueue;
import net.openhft.chronicle.queue.ExcerptAppender;
import net.openhft.chronicle.queue.ExcerptTailer;

public class ChronicleQueueTutorial {

    public static void main(String[] args) {
        String basePath = OS.getTarget() + "/getting-started";
        System.out.println("Base path: " + basePath);
        try (ChronicleQueue queue = ChronicleQueue.singleBuilder(basePath).build()) {
            ExcerptAppender appender = queue.acquireAppender();
            appender.writeText("TestMessage");
            ExcerptTailer tailer = queue.createTailer();
            System.out.println(tailer.readText());
        }
    }

}

Here is my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>ChronicleTutorial</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>net.openhft</groupId>
            <artifactId>chronicle-queue</artifactId>
            <version>5.23ea25</version>
        </dependency>
    </dependencies>
</project>

I tried to run it in IntelliJ with Java 17, but it threw the following exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
    at net.openhft.chronicle.core.Jvm.getSetAccessible0Method(Jvm.java:232)
    at net.openhft.chronicle.core.Jvm.<clinit>(Jvm.java:132)
    at net.openhft.chronicle.core.OS.<clinit>(OS.java:48)
    at ChronicleQueueTutorial.main(ChronicleQueueTutorial.java:9)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at net.openhft.chronicle.core.Jvm.getSetAccessible0Method(Jvm.java:228)
    ... 3 more
Caused by: java.lang.IllegalAccessException: module java.base does not open java.lang.reflect to unnamed module @39ed3c8d
    at java.base/java.lang.invoke.MethodHandles.privateLookupIn(MethodHandles.java:259)
    ... 8 more

I am not even using the Java module system (I don't have module.info). Why am I getting this error?


text:
Q: How to show on top one workbook after a filter in vba I have a code that do a filter on vba and in order to put the data that is going to use in the filter i use an userform, that part is working (in part thanks to the users of this page so thanks again.. :P) but the issue now is that if there is another book already open it doesn't bring the one i'm using to the top.
Another issue is that i use the Workbooks("Database 2017 plus").Windows(1).Visible = True/False in order to hide the book when the userform is shown but at the same time don't hide others books that were open in that moment and it work but as long as the userform is active i can't use those other books and i' d like to if its possible.
Thanks in advance
Private Sub AllIssues_Click()
Unload Me
Workbooks("Database 2017 plus").Windows(1).Visible = True

With Workbooks("Database 2017 plus")

sheets("reported").Visible = True
sheets("reported").Select
sheets("datos").Unprotect
sheets("datos").Visible = True
sheets("principal").Visible = True
sheets("History slot").Unprotect
sheets("history slot").Visible = True

End With

End Sub

And about the other issue with show 0 works thanks


text:
Q: Quantum Lorentz Transformations Now I am reading a Weinberg's book "Quantum theory of field". Vol.1 page: 55
Сould you explain me the following things?

Einstein's principle of relativity states the equivalence of certain 'inertial' frames of reference. It is distinguished from the Galilean principle of relativity, obeyed by Newtonian mechanics, by the transformation connecting
  coordinate systems in different inertial frames. If $x^\mu $ are the coordinates in one inertial frame (with $x^1$,$x^2$,$x^3$ Cartesian space coordinates, and $x ^ 0 = t$ a time coordinate, the speed of light being set equal to unity) then in any other inertial frame, the coordinates $x^\mu$ must satisfy:
  $$\eta_{\mu\nu}dx^{'\mu}dx^{'\nu} = \eta_{\mu\nu}dx^{\mu}dx^{\nu} \tag{2.3.1}$$
  or equivalently:
  $$\eta_{\mu\nu}\frac{dx^{'\mu}}{dx^{\rho}}\frac{dx^{'\nu}}{dx^{\sigma}} = \eta_{\rho\sigma}. \tag{2.3.2}$$

How can it be equivalent? What are $\rho$ , $\sigma$, $\nu$? Why do we have $\eta_{\mu\nu}$ at both sides in the first equation?

A: In the first equation you have $\eta_{\mu\nu}$ at both sides because you define the Lorentz transformations as those leaving the metric $\eta_{\mu\nu}$ invariant. So $\eta'_{\mu\nu}=\eta_{\mu\nu}$.
You can obtain the first equation from the second by multiplying times $dx^{\rho}dx^{\sigma}$:$$\eta_{\mu\nu}\frac{dx^{'\mu}}{dx^{\rho}}dx^{\rho}\frac{dx^{'\nu}}{dx^{\sigma}}dx^{\sigma} \equiv \eta_{\mu\nu}dx'^{\mu}dx'^{\nu}=\eta_{\rho\sigma}dx^{\rho}dx^{\sigma}$$
where the last step is just multiplying the right hand side of the start point equation times $dx^{\rho}dx^{\sigma}$

A: I hope this is useful for you. This has to do with how to measure distances in Minkowski space. This is done through the metric, an amount that in principle depends on the point in space but in this case, special relativity, is constant. These equations that you have written tell us precisely about that. In the first, we see that the way to measure distances when we move from one frame of reference to another is "similar". The second is a bit more explicit, we see the way we transform the metric when we move from one frame of reference to another, this is done through the Lorentz transformations. The Lorentz transformations ($\Lambda_{\mu}^{\nu}=\frac{dx'^{\mu}}{dx^{\nu}}$) are those used in the Minkowsi space to change coordinates. Thus, $\eta_{\mu\nu}$ appears on both sides of the equation because it is invariant under the Lorentz transformations.
$\rho,\sigma, \nu$, they serve to label the coordinates

A: You have to remember that the summation convention is being used, so that (for instance) $η_{μν} dx^μ dx^ν$ means
$$\sum_{μ=0,1,2,3}{\sum_{ν=0,1,2,3}{η_{μν} dx^μ dx^ν}}.$$
If treat the line element as a proper distance $s$, then with $x^0 = t$ and $(x^1, x^2, x^3) = (x, y, z)$, the components are
$$η_{00} = -c^2, \hspace 1em η_{11} = η_{22} = η_{33} = 1, \hspace 1em η_{μν} = 0 \hspace 1em (μ ≠ ν),$$
so that the respective line elements read:
$$-c^2 dt'^2 + dx'^2 + dy'^2 + dz'^2 = -c^2 dt^2 + dx^2 + dy^2 + dz^2,$$
and that's what equation (2.3.1) is actually saying. There is no $μ$ or $ν$ anywhere in there, except as place-holders for the summation operator.
I won't write out (2.3.2) in full, but with the conventions spelled out explicitly like this, I think you can see more clearly that it's just an application of the chain rule, applied to the coordinate differentials $(dt', dx', dy', dz')$, starting from (2.3.1).
The Lorentz group is the symmetry group that preserves $x^2 + y^2 + z^2 - c^2 t^2$, with the coordinates in place of coordinate differentials. In contrast, it's the Poincaré group that preserves the line element with the coordinate differentials. In particular, the Poincaré group includes translations on the coordinates: $x^μ → x^μ + a^μ$ for constant $\left(a^0, a^1, a^2, a^3\right)$.
Weinberg, in fact, spoke wrong in another respect. There is no fundamental difference between the relativistic and non-relativistic cases - he only thought there was. This can be best seen by treating $s$ as proper time instead of as proper distance. Then, the corresponding line element becomes
$$-c^2 ds^2 = -c^2 dt^2 + dx^2 + dy^2 + dz^2,$$
or just:
$$c^2 (ds^2 - dt^2) + dx^2 + dy^2 + dz^2 = 0.$$
The Poincaré group can then be thought of as the group which preserves this line-element / constraint and which leaves $ds$ invariant. The only difference from non-relativistic theory is that $s$ and $t$ are distinct. In the limit, their difference $s - t$, the time-dilation, vanishes; thus leading the the (mistaken!) impression that there is nothing corresponding to time-dilation in non-relativistic theory.
Actually, there is. It just wasn't recognized until much later ... well into the 20th century. Though $s - t → 0$ in the non-relativistic limit, this is not the case for its scaled-up version $u = c^2 (s - t)$, which has a non-trivial and meaningful non-relativistic limit. In fact, if you substitute for $s$, then the line element becomes:
$$dx^2 + dy^2 + dz^2 + 2 dt du + \frac{1}{c^2} du^2 = 0,$$
while the linear invariant (that is: $ds$) becomes:
$$dt + \frac{1}{c^2} du.$$
The invariance group is also Poincaré ... trivially extended in that it also allows for translation on the $u$ coordinate.
This is one member of a family of invariants, parameterized by $α$:
$$dx^2 + dy^2 + dz^2 + 2 dt du + α du^2 = 0, \hspace 1em dt + α du.$$
When $α > 0$, this yields the (trivially extended) Poincaré group, with light speed set to $c = \sqrt{1/α}$; while when $α = 0$, with the corresponding items being:
$$dx^2 + dy^2 + dz^2 + 2 dt du = 0, \hspace 1em dt,$$
the symmetry group is the central extension of the Galilei group: also known as the Bargmann group. The $u$-translations corresponds to mass, in the very same way that the spatial-translations correspond to momentum, and the time-translations to (the negative of) energy.
For $α < 0$ the corresponding geometry provides a container for 4-dimensional Euclidean geometry, where $t$ is now a spatial dimension. In all cases, for all $α$, the ambient 5D geometry is a (4+1)-dimensional Minkowski space. They differ from one another only by which direction the invariant coordinate $s$ is oriented in.
So, there is a metric there - provided that (1) you add in the extra coordinate and dimension, (2) constrain to a 4D sub-space of the underlying ambient 5D-geometry and (3) impose the requirement that the coordinate differential $ds$ - for  proper time - be invariant. In the non-relativistic case, where $α = 0$, the geometry is called the Bargmann geometry. Its relativistic version, where $α > 0$ has no name that I am aware of. But, as you can see, the Minkowski geometry is sitting there, right inside of it, as a 4D subspace. There's a (4+1)-Minkowski metric, for the line element, and a linear "metric" for the proper time, $ds = n_μ dx^μ$ where $n_1 = n_2 = n_3 = 0$, $n_4 = 1$ and $n_5 = α$, this time with
$$\left(x^1, x^2, x^3, x^4, x^5\right) = (x, y, z, t, u).$$
In retrospect, you can see why Weinberg totally missed this: he kept using the ill-advised convention $c = 1$, which Sapir-Whorf's away the very ability to even express what's just been stated in the preceding paragraphs! That's an example (one of many) of the problem, which runs amok in the Physics literature.
And by the way, on that issue:
Sapir-Whorf Hypothesis:
https://en.wikipedia.org/wiki/Linguistic_relativity


text:
Q: Storing DATABASE_PRINCIPAL_ID in sql server table We're using stored procedures to restrict the access of some of our database users. They need access to specific parts of the database (not just tables/views, but also specific rows), and the sproc should check if the user is allowed to see the table rows he's requesting.
To store the authorization rules, we're planning to use a table dbo.AuthRules like that:
|ID|UserId  |AccessFrom  |AccessTo    | ...
===============================================
| 1|       1| 01.01.2013 | 31.12.2013 | ...
| 2|       2| 31.05.2012 | 31.12.2015 | ...

The stored procedure would then query that table to check if the current user has access to the requested data. To make it clear: We cannot just use GRANT PERMISSION because we need fine-grained access rules down to the rows in the DB.
We're not sure about the UserId column. The best solution would be some kind of foreign key to the system view sys.database_principals, but there are no foreign keys to views.

*

*Should we just store the principal_id column of sys.database_principals, without any constraint?

*Would it be better to store the name column instead of principal_id?

*Are there other options to store a reference to the DB user?

A: Q: Should we just store the principal_id column of sys.database_principals, without any constraint?
A: If you are evaluating only a constraint-based solution, you don't really have any choice. However, if you are willing to write a trigger, that would be the way to at least 'virtually' create constraint. Otherwise you would have to reference system sysowners table and this isn't possible without some hacking.
Q: Would it be better to store the name column instead of principal_id?
A: To answer that you have to ask the what-if question. What if principal_id changes? What if name changes? What about updates/deletes? I would always rather have an id-based solution.
Q: Are there other options to store a reference to the DB user?
A: As stated in answer#1, I don't think there are any possibilities except creating a trigger...

A: Consider this design method.
USE "master";

-- Create our test logins (don't forget to tidy these up later!)
CREATE LOGIN "batman"
  WITH PASSWORD = N''
     , CHECK_EXPIRATION = OFF
     , CHECK_POLICY = OFF;

CREATE LOGIN "robin"
  WITH PASSWORD = N''
     , CHECK_EXPIRATION = OFF
     , CHECK_POLICY = OFF;

USE "playdb";

-- Create the corresponding users
CREATE USER "batman"
  FOR LOGIN "batman";

CREATE USER "robin"
  FOR LOGIN "robin";

-- Grant them some select permissions
EXEC sp_addrolemember N'db_datareader', N'batman';
EXEC sp_addrolemember N'db_datareader', N'robin';

-- Create our "user access" table
DECLARE @users table (
   username    sysname NOT NULL
 , access_from date    NOT NULL DEFAULT '1900-01-01' -- Deliberately not allowing nulls and setting the widest possible value range
 , access_to   date    NOT NULL DEFAULT '9999-12-31' --   this will make our queries so much easier!
);

-- Give one user full permissions
INSERT INTO @users (username)
  VALUES ('batman');

-- Limit what this chappy can see
INSERT INTO @users (username, access_from, access_to)
  VALUES ('robin', '2011-01-01', '2012-01-01');

-- Example data table
DECLARE @data table (
  date_field date NOT NULL
);
-- ...with example data
INSERT INTO @data (date_field)
  VALUES ('2010-01-01')
       , ('2011-01-01')
       , ('2012-01-01')
       , ('2012-01-01')
       , ('2013-01-01')
       , ('2014-01-01');

-- Let's mimic our full access user
SETUSER 'batman';

SELECT System_User As current_username
     , *
FROM   @data As data
WHERE  EXISTS ( -- Limit the records to only those this user is allowed to see
         SELECT *
         FROM   @users
         WHERE  username = System_User
         AND    data.date_field >= access_from
         AND    data.date_field <  access_to
       );

SETUSER; -- Reset user

-- Imitate the chap with restricted access
SETUSER 'robin';

-- Exacty same query as before
SELECT System_User As current_username
     , *
FROM   @data As data
WHERE  EXISTS (
         SELECT *
         FROM   @users
         WHERE  username = System_User
         AND    data.date_field >= access_from
         AND    data.date_field <  access_to
       );


text:
Q: Inconsistencies in Big-O of removing from an ArrayList vs a Hash Table? I'm looking at this website that lists Big O complexities for various operations.  For Dynamic Arrays, the removal complexity is O(n), while for Hash Tables it's O(1).
For Dynamic Arrays like ArrayLists to be O(n), that must mean the operation of removing some value from the center and then shifting each index over one to keep the block of data contiguous.  Because if we're just deleting the value stored at index k and not shifting, it's O(1).
But in Hash Tables with linear probing, deletion is the same thing, you just run your value through the Hash function, go to the Dynamic Array holding your data, and delete the value stored in it.
So why do Hash Tables get O(1) credit while Dynamic Arrays get O(n)?

A: This is explained here. The key is that the number of values per Dynamic Array is kept under a constant value.
Edit: As Dukeling pointed out, my answer explains why a Hash Table with separate chaining has O(1) removal complexity. I should add that, on the website you were looking at, Hash Tables are credited with O(1) removal complexity because they analyse a Hash Table with separate chaining and not linear probing.

A: The point of hash tables is that they keep close to the best case, where the best case means a single entry per bucket. Clearly, you have no trouble accepting that to remove the sole entry from a bucket takes O(1) time.

A: When there are many hash conflicts, you certainly need to do a lot of shifting when using linear probing.
But the complexity for hash tables are under the assumption of Simply Uniform Hashing, meaning that it assumes that there will be a minimal number of hash conflicts.
When this happens, we only need to delete some value and shift either no values or a small (essentially constant) amount of values.

A: When you talk about the complexity of an algorithm, you actually need to discuss a concrete implementation.

*

*There is no Java class called a "Hash Table" (obviously!) or "HashTable".

*There are Java classes called HashMap and Hashtable, and these do indeed have O(1) deletion.
But they don't work the way that you seem to think (all?) hash tables work. Specifically, HashMap and Hashtable are organized as an array of pointers to "chains".
This means that deletion consists of finding the appropriate chain, and then traversing the chain to find the entry to remove.  The first step is constant time (including the time to calculate the hash code.  The second step is proportional to the length of the hash chains.  But assuming that the hash function is good, the average length of the hash chain is a small constant.  Hence the total time for deletion is O(1) on average.

The reason that the hash chains are short on average is that the HashMap and Hashtable classes automatically resize the main hash array when the "load factor" (the ratio of the array size to the number of entries) exceeds a predetermined value.  Assuming that the hash function distributes the (actual) keys pretty evenly, you will find that the chains are roughly the same length.  Assuming that the array size is proportional to the total number of entries, the actual load factor will the average hash chain length.
This reasoning breaks down if the hash function does not distribute the keys evenly.  This leads to a situation where you get a lot of hash collisions.  Indeed, the worst-case behaviour is when all keys have the same hash value, and they all end up on a single hash chain with all N entries.  In that case, deletion involves searching a chain with N entries ... and that makes it O(N).

It turns out that the same reasoning can be applied to other forms of hash table, including those where the entries are stored in the hash array itself, and collisions are handled by rehashing scanning.  (Once again, the "trick" is to expand the hash table when the load factor gets too high.)


text:
Q: cannot find symbol Serializable? Why does this:
package com.example;

import com.example.Foo.Bar.Baz;

import java.io.Serializable; // I did import Serializable...

public class Foo implements Serializable {

    public final Bar bar;

    public Foo(Bar bar) {
        this.bar = bar == null ? new Bar(Baz.ONE) : bar;
    }

    public static class Bar implements Serializable { // this is line 15, where the compiler error is pointing

        public enum Baz {
            ONE
        }

        public final Baz baz;

        public Bar(Baz baz) {
            this.baz = baz;
        }
    }

}

Give me this:
[ERROR] <path to file>/Foo.java:[15,44] cannot find symbol
[ERROR] symbol:   class Serializable
[ERROR] location: class com.example.Foo

If I replace the Serializable interface to something else like :
public interface MyMarkerInterface {}

then the code compiles. (even Cloneable works!)
What makes this happen?
intelliJ didn't spot anything wrong through static analysis.

A: Don't try and import the internal class. That's causing your compiler error
// import com.example.Foo.Bar.Baz;
import java.io.Serializable;

public class Foo implements Serializable {
    public final Bar bar;

    public Foo(Bar bar) {
        this.bar = bar == null ? new Bar(Bar.Baz.ONE) : bar;
    }

    public static class Bar implements Serializable {
        public enum Baz {
            ONE
        }
        public final Baz baz;
        public Bar(Baz baz) {
            this.baz = baz;
        }
    }
}

A: in java7 and java8 compiling depended on order of imports.
your code works in java >= 9. see https://bugs.openjdk.java.net/browse/JDK-8066856 and https://bugs.openjdk.java.net/browse/JDK-7101822
to make it compile in java7 and java8 just reorder the imports


text:
Q: Breaking my code by putting Dictionaries in a list. What am I doing wrong? I made a webscraper for a supermarket's website. It believe I did everything right, but somehow I messed up using dictionaries in lists, while using a for loop. My code wont even print text anymore and I can't find the solution myself.
I tried putting an empty dic outside the loop, on different spots in the code but it all seems to fail. I tried putting simple print("test")code throughout to see where the code fails. Still, the fail seems illogical.
import time
import csv
from urllib.parse import urljoin
from selenium import webdriver

# csvFile = open('products.csv', 'w')
# writer = csv.writer(csvFile)
# writer.writerow(('name', 'price'))

pagenum = 1

base_url = 'https://www.ah.nl'
search_url = '/zoeken?query=groente&page={}'.format(pagenum)
active_url = urljoin(base_url,search_url)
driver = webdriver.Chrome()
driver.get(active_url)
driver.implicitly_wait(100)

next_page = driver.find_elements_by_tag_name('article')
total_products = driver.find_element_by_class_name('f-load-more')
T = total_products.text.split()
print(" Total products: " + str(T[3]))

var = len(next_page)-1
h = next_page[var]

while int(T[0]) < int(T[3]):
    try:
        time.sleep(1)
        driver.execute_script("arguments[0].scrollIntoView();", h)
        total_products.find_element_by_tag_name('button').click()
        time.sleep(1)

    except:
        print("We did it boys. Proceeding with products ..")
        break

def linkGrabber():
    items = driver.find_elements_by_tag_name('article')
    print(str(len(items)) + " items found on page.")
    urls = []
    for i in items:
        try:
            L = i.find_element_by_tag_name('a') .get_attribute('href')
            urls.append([L])
        except:
            print('link for' + str(i) + ' not found.')
    return urls

yum = linkGrabber()
# for practise purposes:
yum = yum[0:3]

P_LIST = []

for i in yum:
    newdict = {}
    i = "".join(i)
    driver.get(i)
    TITLE = driver.find_element_by_xpath('//*[@id="app"]/main').get_attribute('title')
    newdict["url"] = i
    newdict["name"] = TITLE
    try:
        x = driver.find_element_by_class_name('product-info-content-block')
        x = x.find_element_by_tag_name('p').text
        newdict["weight/amount"] = x
    except:
        continue
    try:
        NUTRITION_TABLE = driver.find_element_by_tag_name('tbody')
        ENERGY = NUTRITION_TABLE.find_elements_by_tag_name('tr')
        for i in ENERGY:
            A = i.find_elements_by_tag_name('td')
            UNIT = A[0].text
            VALUE = A[1].text
            newdict[UNIT] = VALUE
        P_LIST.append(newdict)

    except:
        continue

    print("-----------------------------------")

print(P_LIST)

# csvFile.close()

output:
We did it boys. Proceeding with products ..

1444 items found on page.

link for<selenium.webdriver.element> not found.

[]

I'm trying to grab all info from unique products in a list of dictionaries. After that, I'll write this info to a csv file (code in progress). I'll start using Pandas as well.
If you have any tips on structuring my code or anything else, please feel free to share them. Thanks for helping.

A: Move this P_LIST.append(newdict) after except condition and before print("-----------------------------------")
The value of P_LIST in above code is getting updated in second try except case and if that try except fails you will not get any value appended in P_LIST.
(Suggestion) Also add some debug logs in your code for better debugging in future.


text:
Q: How to access $q library with webpack? I have a project, that i'm packing with webpack.
However I have this one issue, where I can't access the angular promise library.
I have a properties.js file, with the following code:
define(['qlik', 'ng!$q'], function(qlik, $q) {
  var defer = $q.defer();
  ...
  ...
})

and when I try to hit 'npm run build' in cmd line, I get this output:
ERROR in ./properties.js
Module not found: Error: Can't resolve '$q' in '...path...\src'
 @ ./properties.js 1:0-545:2

Anyone who knows the answer to this?
Thanks in advance.
//Rasmus


text:
Q: Why does textmate modify the file mtime after closing the tab? I use electron-vue to automatically reload the page, and every time I close the file, textmate automatically update mtime of the file. This was not the case before, and I don't know why.

A: Via the mailing list;

The reason is that TextMate uses extended attributes to store things
  such as position of insertion point, selection etc.
You can disable this via .tm_properties. Create a .tm_properties file
  in the root of your project and let it contain this line:
disableExtendedAttributes = true You can also create the file in ~ to
  disable the behavior globally, or you can limit it to certain file
  types, e.g. by using:
[ *.vue ] disableExtendedAttributes = true

-- Allan Odgaard


text:
Q: Swift Sqlite SQL error I'm attempting to create a simple sqlite database in Swift, but I'm getting an error (specifically SQLITE_ERROR) when attempting to create a table.
Here is my code:
        var db :OpaquePointer?
        let dbPath = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            .appendingPathComponent("\(Date.init().timeIntervalSince1970)".replacingOccurrences(of: ".", with: "") + ".db")
            .absoluteString

        var returnCode :Int32 = sqlite3_open(dbPath.cString(using: .utf8), &db)
        if SQLITE_OK != returnCode {
            preconditionFailure("Failed to open db")
        }

        var stmt :OpaquePointer?
        returnCode = sqlite3_prepare_v2(db, "CREATE TABLE Things (name TEXT)".cString(using: .utf8), -1, &stmt, nil)
        if SQLITE_OK != returnCode {
            preconditionFailure("Failed to prepare table creation SQL")
        }

Sqlite is included via a Cocoapod. I have tried using different encodings of the string when converting to a C string, specifically I've tried using ASCII encoding, and I've also tried hard coding the database name.
The error occurs in sqlite3_prepare_v2.
The error message is "near \"\u{01}\": syntax error"

A: I am not 100% sure why your .cString(using: .utf8) approach
to convert a Swift string to a C string causes problems.
It could be the same issue as in
Why does Swift return an unexpected pointer when converting an optional String into an UnsafePointer? (which was
reported as a Swift bug). Unwrapping the result of cString()
explicitly seems to help:
let sql = "CREATE TABLE Things (name TEXT)".cString(using: .utf8)!
returnCode = sqlite3_prepare_v2(db, sql, -1, &stmt, nil)

But you can pass a Swift String directly to C functions expecting
a const char * (compare String value to UnsafePointer<UInt8> function parameter behavior):
var returnCode = sqlite3_open(dbPath, &db)
// ...
returnCode = sqlite3_prepare_v2(db, "CREATE TABLE Things (name TEXT)", -1, &stmt, nil)

and this works as expected.
Additional remarks:

*

*Use .path to convert a URL to a file path string,
not .absoluteString.

*Use sqlite3_errmsg() to get error messages if something failed.

*Remove unnecessary type annotations, as in var returnCode :Int32.

Putting it all together:
var db: OpaquePointer?
let dbPath = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    .appendingPathComponent("xxx.db")
    .path

var returnCode = sqlite3_open(dbPath, &db)
if SQLITE_OK != returnCode {
    let errmsg = String(cString: sqlite3_errmsg(db))
    fatalError("Failed to open db: \(errmsg)")
}

var stmt: OpaquePointer?
returnCode = sqlite3_prepare_v2(db, "CREATE TABLE Things (name TEXT)", -1, &stmt, nil)
if SQLITE_OK != returnCode {
    let errmsg = String(cString: sqlite3_errmsg(db))
    fatalError("Failed to prepare table creation SQL: \(errmsg)")
}