Q: Three table with value join query base value is first ,secound and third table i need to develop the query with join or any thing i can't make it
my concept is the first table have a usr id and usr type id
the second table have details of usr type and id and usr master details id
the third table have usr master details and id my question is how i select the value of those three table
Sample table is
user_details
usr_id   Name  us_ty_id
25       john     2
34       sam      3
24       rose     1

user_type
us_ty_id    type    usr_ma_id
1            dev      2
2            desi     1
3            test     2

user_master
usr_ma_id   details
1            team1
2            team2
3            team3

my output like below
usr_id   type     details
34       test      team3

the first table us_type_id find the type and usr_ma_id in second and find the details of selected id of usr_ma_id in second table and find the details
ple help me...

A: What about the simple:
SELECT *
FROM user_details d
INNER JOIN user_type t ON t.us_ty_id = d.us_ty_id
INNER JOIN user_master m ON m.usr_ma_id = t.usr_ma_id;


Q: Hibernate throwing StackOverflow Exception(Spring Boot) I'm working with SprinBoot/JPA in an integration via XML. I have to read an XML file and persist the data into my db.
Steps:

*

*I must verify if this XML is not recurrent if it does, I have to update this register.

*Each XML comes with a list of items, I have to verify if each child already exists, if it does I have to update, if not I have to create a new one.

*I have to verify if some child is not recurrent and if it not, I have to remove this item.

*I have to verify if the material, color and product are existent otherwise I have to create a new one for each case.
Generally, everything works fine. But I have some cases when I getting a StackOverflow Exception.

*

*It's not because it is recursive because 90% of the files are saved correctly and updated correctly.

*I tried to save separately the children, no success.

*It's always the same files that throw the exception.

*It's not the memory because I have success cases that the file is bigger than the ones who failed.

*I can save the success files multiple times and no error occurs but If I try to save just one problematic error and the exception occurs.
This is my class responsible for managing the loaded XML and persisting
    @Override
    public void createProductionSet(ClientOrder clientOrder) throws Exception {
        try{
            List<Long> recurrent = new ArrayList<>();
            ProductionOrder order = orderService.findByCodeAndClientCode(clientOrder.getOp(), clientOrder.getClientCode());
            boolean newProdOrder = order == null,
                    hasChildrenInfo = hasChildrenInfo(clientOrder);

            if(newProdOrder)
                order = new ProductionOrder(clientOrder.getOp(), clientOrder.getClientCode(), clientOrder.getObservation());
            order.setItems(new ArrayList<>());
            if(hasChildrenInfo)
                manageCollectionChildrenValues(clientOrder, order, newProdOrder, recurrent);
            else
                manageCollection(clientOrder, order, newProdOrder,recurrent,
                                loadColor(clientOrder.getColorReference(), clientOrder.getColor()),
                                loadMaterial(clientOrder.getMaterialReference(), clientOrder.getMaterial()),
                                loadProduct(clientOrder.getProductReference(), clientOrder.getProduct(), clientOrder.getUnitOfMeasurement()));

            if(!newProdOrder)
                prodOrderItemService.deleteNotIn(recurrent, order.getId());
            orderService.save(order);
        } catch(StackOverflowError t) {
            throw  new Exception("Erro de StackOverflowError : "+clientOrder.toString());
        }catch (Exception e){
            log.warn("ERRO >> "+e.getMessage());
        }
    }

    private void manageCollection(ClientOrder clientOrder, ProductionOrder order, boolean newProdOrder, List<Long> recurrent,
                                  MaterialColor materialColor, Material material, Product product) {
        for(ItemOrder item : clientOrder.getItems()) {
            item.setColorObj(materialColor);
            item.setMaterialObj(material);
            item.setProductObj(product);
            manageItem(item, order, newProdOrder, recurrent);
        }
    }

    private void manageCollectionChildrenValues(ClientOrder clientOrder, ProductionOrder order, boolean newProdOrder, List<Long> recurrent) {
        for(ItemOrder item : clientOrder.getItems()) {
            item.setColorObj(loadColor(item.getColorReference(), item.getColor()));
            item.setMaterialObj(loadMaterial(item.getMaterialReference(), item.getMaterial()));
            item.setProductObj(loadProduct(item.getProductReference(), item.getProduct(), clientOrder.getUnitOfMeasurement()));
            manageItem(item, order, newProdOrder, recurrent);
        }
    }

    private void manageItem(ItemOrder item, ProductionOrder order, boolean newProdOrder, List<Long> recurrent) {
        ProdOrderItem aux = null;
        if(!newProdOrder)
            aux = prodOrderItemService.findOneByProductionOrderAndSize(order.getId(), item.getSize());

        if(aux != null) {
            aux.update(item);
            recurrent.add(aux.getId());
        }else {
            aux = new ProdOrderItem(item, order);
            order.getItems().add(aux);
        }
    }

    private boolean hasChildrenInfo(ClientOrder clientOrder) {
        return clientOrder.getColorReference() == null
                && clientOrder.getProductReference() == null
                && clientOrder.getMaterialReference() == null;
    }

    private Product loadProduct(String reference, String description, String unitOfMeasurement) {
        if(reference != null && !reference.isEmpty()) {
            Product product = productService.findProductByReference(reference);
            if (product != null)
                return product;
            return productService.save(new Product(description, reference, unitOfMeasurement));
        }
        return productService.loadFirstOrDefault();
    }

    private MaterialColor loadColor(String reference, String description) {
        if(reference != null && !reference.isEmpty()) {
            MaterialColor materialColor = colorService.findByReference(reference);
            if (materialColor != null)
                return materialColor;
            return colorService.save(new MaterialColor(reference, description));
        }
        return colorService.loadFirstOrDefault();
    }

    private Material loadMaterial(String reference, String description) {
        if(reference != null && !reference.isEmpty()) {
            Material material = materialService.findByReference(reference);
            if (material != null)
                return material;
            return materialService.save(new Material(description, reference, null));
        }
        return materialService.loadFirstOrDefault();
    }
}

These are my models:
@Entity(name = "production_order")
public class ProductionOrder {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Temporal(TemporalType.TIMESTAMP)
private Date created;

@Temporal(TemporalType.TIMESTAMP)
private Date updated;

@Type(type = "org.hibernate.type.NumericBooleanType")
private boolean deleted;

@Column(nullable = false, length = 30)
private String code;

@Column(length = 30)
private String clientCode;

@Column(length = 200)
private String observation;

@OneToMany(fetch = FetchType.EAGER, mappedBy ="productionOrder", orphanRemoval = true, cascade = {CascadeType.ALL})
@Cascade({org.hibernate.annotations.CascadeType.ALL})
private List<ProdOrderItem> items;

...

}
@Entity(name = "order_item")
public class ProdOrderItem {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(nullable = false, length = 10)
private String size;

@Column(nullable = false)
private float quantity;

@Column(nullable = false)
private float weight;

@Column(nullable = false)
private float tolerance;

@Temporal(TemporalType.TIMESTAMP)
private Date created;

@Temporal(TemporalType.TIMESTAMP)
private Date updated;

@Type(type = "org.hibernate.type.NumericBooleanType")
private boolean deleted;

@ManyToOne(optional = false)
@JoinColumn(name = "product_id")
private Product product;

@ManyToOne(optional = false)
@JoinColumn(name = "color_id")
private MaterialColor color;

@ManyToOne(optional = false)
private Material material;

@ManyToOne
@JoinColumn(name = "characteristic_id")
private Characteristic characteristic;

@ManyToOne(optional = false)
@JoinColumn(name="order_id")
private ProductionOrder productionOrder;

And this is the log:
java.lang.StackOverflowError
    at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:131)
    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
    at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)
    at com.sun.proxy.$Proxy106.prepareStatement(Unknown Source)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1929)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876)
    at org.hibernate.loader.Loader.doQuery(Loader.java:919)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:306)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:60)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:50)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4019)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
    at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1022)
    at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:639)
    at org.hibernate.type.EntityType.resolve(EntityType.java:431)
    at org.hibernate.type.ComponentType.resolve(ComponentType.java:687)
    at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:848)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:714)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:972)
    at org.hibernate.loader.Loader.doQuery(Loader.java:930)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:306)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:60)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:50)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4019)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
    at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1022)
    at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:639)
    at org.hibernate.type.EntityType.resolve(EntityType.java:431)
    at org.hibernate.type.ComponentType.resolve(ComponentType.java:687)
    at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:848)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:714)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:972)
    at org.hibernate.loader.Loader.doQuery(Loader.java:930)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:306)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:60)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:50)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4019)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
    at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1022)
    at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:639)
    at org.hibernate.type.EntityType.resolve(EntityType.java:431)
    at org.hibernate.type.ComponentType.resolve(ComponentType.java:687)
    at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:848)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:714)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:972)
    at org.hibernate.loader.Loader.doQuery(Loader.java:930)
    at

The complete log is here, together with 2 xml files

A: The reason can be in FetchType.EAGER try to remove it:

@Entity(name = "production_order")
public class ProductionOrder {
....
@OneToMany(mappedBy ="productionOrder", cascade = {CascadeType.ALL})
@Cascade({org.hibernate.annotations.CascadeType.ALL})
private List<ProdOrderItem> items;


Q: Encode Trie to a file to avoid rebuilding I've constructed a Trie with about 400,000 nodes from a dictionary having about 180,000 words. The problem is that the trie is taking too long to construct on my phone.
So I've decided to create the trie once and store it in some format to the disk, for fast recreation whenever needed. But I'm unable to come up with a good format to store it.
What would be the most efficient format to encode the trie, so that it can be reconstructed from the file as fast as possible?

A: If your Trie data structure implements serializable then writing to and from a file should be fairly straight forward. Java will take care of the file representation.
See this link.

A: Maybe good idea - to keep tried in the memory buffer in the position-independent code, and read it into memory by mmap(). This is mostly quick way to work with trie from "cold start".
Also, maybe you can keep data not in the tries, but in the hashtable. By this method, you can keep in the memory only "bucket index", which is very small. And, when compute hash - pread() bucket into memory from file, and search in loaded part.


Q: PHP Use array results to complete MySQL query and add results to existing array I solved the problem with both the foreach loop stopping after the first iteration, as well as it not writing to the array by adding true to the json_decode. I was unaware that that changed it from object oriented to associated.
include '/var/www/html/api/apitoken.php';
include '/var/www/html/api/secrets.php';

$data = file_get_contents('/var/www/html/api/shOrders.json'); // put the contents of the file into a variable
$shOrders = json_decode($data, true);

$con = mysqli_connect("127.0.0.1",$user,$pass,"api") or die('Could not connect: ' . mysqli_error());

$a=0;

foreach($shOrders['varID'] AS $varID) {

  $sql_statement= " SELECT invTrack AS invTrack, varID AS varID, varSKU AS varSku, revelSku AS revelSku, revelInvID AS revelInvID, p.prodID AS prodID, pr.ingredient AS ing, pr.main_product AS mainProduct, pr.product AS product, i.invID AS invC, pr.qty AS QTY
                    FROM shopifyProd sp
                    LEFT JOIN product p ON sp.revelSku = p.sku AND p.location = 1
                    LEFT JOIN prodRecipe pr ON p.prodID = pr.main_product
                    LEFT JOIN inventory i ON pr.product = i.prodID
                    WHERE varID =" . $varID . " ;   ";

  //connect to mysql db and process the statement
  $result = mysqli_query($con,$sql_statement);

  //var_dump($sql_statement . "

");
  while($row = mysqli_fetch_assoc($result)) {
    echo "varID: ";
    print_r($row['varID']);
    echo "
";
      if($varID == $row['varID']) {
      //set correct invID for product in revel
        if (!$row['invC']) {
          $revInvID = ( (int) $row['revelInvID']);
        }else{
          $revInvID = ( (int) $row['invC']);
        }
      //calculate qty to change in revel
        if(!$row['QTY']) {
          $changeQTY = $shOrders['soldQTY'][$a];
        }else{
          $changeQTY = ($row['QTY'] * $shOrders['soldQTY'][$a]);
        }

        echo $varID . " RESULTS! -- ";
        print_r("varSku: " . $shOrders['varSku'][$a]);
        echo ", ";
        print_r("revelInvID: " . $row['revelInvID']);
        echo ", ";
        print_r("soldQTY: " . $shOrders['soldQTY'][$a]);
        echo ", ";
        print_r("ingredient: " . $row['ing']);
        echo ", ";
        print_r("Product: " . $row['product']);
        echo ", ";
        print_r("invC: " . $revInvID);
        echo ", ";
        print_r("changeQTY: " . $changeQTY);
        echo "

";

        $shOrders['revProdID'][$a] = ( (int) $row['product']);
        $shOrders['revInvID'][$a] = ( (int) $revInvID);
        $shOrders['changeQTY'][$a] = ( (float) $changeQTY);

        if (!mysqli_query($con, $sql_statement)) {
        print_r(mysqli_error_list($con));
        echo "
";
        mysqli_close($con);
        }
      }

    }
    $a++;
  set_time_limit ( 30 );
}

echo "
";
print_r($shOrders);
echo "
";

A: var_dump out your query just before you run it, Are all the expected parameters there? Try running that in your local db tool (mysql workbench, phpmyadmin), does it do what you like?
var_dump out the variables at each step of the way and die (or alternatively use a debugger to step through the code 1 line at a time), to see what is happening.
It doesn't look like you've declared $varID above the query.
I think you need to move
foreach($shOrders->varID AS $varID) {

above the $sql_statement = ... line.


Q: How to translate Japanese response page to English in Python Selenuim How to translate Japanese response page to English in Python Selenium. As i need to scrape a Japanese site, i could'nt even extract a single text from the site because all are in Japanese.

A: Google Chrome has a built in feature that lets you translate an entire page into your language. What you could do is set the language in the application to, say, English, go to the site in Chrome and auto translate back in to your language. However this could be tricky and may require something like https://chrome.google.com/webstore/detail/google-translate/aapbdbdomjkkjkaonfhkkikfgjllcleb?hl=en google chrome extension to fulfill your requirement. You can automate this utility using autoit.
To add an extension for chrome driver, please refer to those links:
Create .CRX file and Add extension to Chrome WebDriver
A possible workaround could be if you can utilize something like these custom configs. Those Python examples, should help :
Firefox:
import os
from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference('intl.accept_languages', 'es')
driver = webdriver.Firefox(profile)

Chrome:
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option( "prefs", {'--lang': 'es'})
driver = webdriver.Chrome(chrome_options=chrome_options)


Q: Array of Strings to Convert to Mixed Array I'm trying to convert an Array of Arrays consisting of Ruby Strings into an Array of Arrays consisting of Strings and Floats.
Here is my attempt:
array = [["My", "2"], ["Cute"], ["Dog", "4"]]
array.collect! do |x|
  x.each do |y|
    if y.gsub!(/\d+/){|s|s.to_f}
    end
  end
end

 => [["My", "2.0"], ["Cute"], ["Dog", "4.0"]]

I'm looking for this to rather return [["My", 2.0], ["Cute"], ["Dog", 4.0]] What did I do wrong?

A: What you did wrong is that you used gsub!. That takes a string and changes the string. It doesn't turn it into anything else, no matter what you do (even if you convert it to a float in the middle).
A simple way to achieve what you want is:
[["My", "2"], ["Cute"], ["Dog", "4"]].map{|s1, s2| [s1, *(s2.to_f if s2)]}

If you do not want to create the element array, but replace its contents, then:
[["My", "2"], ["Cute"], ["Dog", "4"]].each{|a| a[1] = a[1].to_f if a[1]}

If the numerical strings appear in random positions, then:
 [["My", "2"], ["Cute"], ["Dog", "4"]]
.each{|a| a.each.with_index{|e, i| a[i] = a[i].to_f if a[i] and a[i] =~ /\d+/}}


Q: django-nonrel specify MongoDB BSON element name to model attributes In C# it is possible to use the MongoDB driver to define a custom BSONElement Name to each attribute in your data models, in order to shorten its stored name, such as
[BsonElement("c")]
public Boolean Current { get; set; }

Is there any way to accomplish this with a django-nonrel setup and a model defined like
class Test(models.Model):
    Current = models.BooleanField()

so that the attribute "Current" will be stored as "c" and be referenced in code as "Current"?
Research did not work very well on this one.

A: Try setting the db_column option to BooleanField, or any field -- that should be the actual field name stored in MongoDB.


Q: How is the maildir for each user supposed to be created? I've installed postfix+dovecot under ubuntu and got permission errors when receiving mail:
Nov 10 22:04:08 amalthea postfix/local[14942]: warning: maildir access problem for UID/GID=9999/9999: create maildir file /var/mail/skyking/tmp/1447189448.P14942.amalthea: Permission denied
Nov 10 22:04:08 amalthea postfix/local[14942]: warning: perhaps you need to create the maildirs in advance

This was solved by simply creating the directory /var/mail/skyking (with permissions drwxr-sr-x).
How was the directory /var/mail/skyking supposed to be created? I mean it's not feasible to manually create a new directory for each user.
Note: I use LDAP for user accounts so creating users don't need to happen on the mail server. Also mail is read on another computer via IMAP.

A: Does postfix have the right to create the maildir? Check that the user shown by ls -ld /var/mail is the same as that shown by ls -l /var/mail/skyking.


Q: Problem connecting to MS SQL server 2000 with Spring Boot I try connect to ms sql server 2000 and I can't understand what I'm doing wrong. Unfortunately, I can not use another server. Help me please.
server image
tree
Application.properties
spring.datasource.url=jdbc:sqlserver://DESKTOP-J1EE59P\\EGOR;databaseName=dekanat
spring.datasource.username=sa
spring.datasource.password=123
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
spring.jpa.hibernate.ddl-auto = create-drop

Grandle file
 dependencies {
        compile('org.springframework.boot:spring-boot-starter-actuator')

        //compile('org.springframework.cloud:spring-cloud-starter-eureka-server')
        //compile('org.springframework.cloud:spring-cloud-starter-config')

        compile('org.springframework.boot:spring-boot-starter-data-jpa')
        compile("org.apache.commons:commons-dbcp2:2.1.1")
        compile group: 'net.sourceforge.jtds', name: 'jtds', version: '1.2'

        compile('org.springframework.boot:spring-boot-starter-web')
        compile('org.springframework.boot:spring-boot-starter-security')
        compile group: 'com.google.code.gson', name: 'gson', version: '1.7.2'
        compile('io.jsonwebtoken:jjwt:0.9.0')
        testCompile('org.springframework.boot:spring-boot-starter-test')
        compileOnly "org.projectlombok:lombok:1.16.16"
        compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.2.4'
        compile group: 'org.modelmapper', name: 'modelmapper', version: '0.7.5'
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter
       // compile group: 'org.springframework.boot', name: 'spring-boot-starter', version: '2.0.0.RELEASE'
    // https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc
        testCompile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '7.0.0.jre8'
        // https://mvnrepository.com/artifact/net.sourceforge.jtds/jtds
        compile group: 'net.sourceforge.jtds', name: 'jtds', version: '1.3.1'
        // https://mvnrepository.com/artifact/com.microsoft.sqlserver/sqljdbc4
        testCompile group: 'com.microsoft.sqlserver', name: 'sqljdbc4', version: '4.0.0'

Errors
org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Cannot load JDBC driver class 'com.microsoft.sqlserver.jdbc.SQLServerDriver'

A: Make sure you have following dependency on your pom.
<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>sqljdbc4</artifactId>
    <version>4.0</version>
</dependency>


Q: What do you call "testing if a probability will trigger or not" Apologies if this is a bit technical. I'm writing a paper describing a simulation. Inside the simulation, at each time step, some event has a certain probability of happening. Essentially, the computer "rolls a die" and sees if that event will happen or not each second.
How do you describe this action?

*

*Test if the probability will happen?

*Check if the probability will occur?

A: The condition was satisfied.
There are a few things to parse here. Use words very carefully and things will be clear.
First, the probability p is a number between 0 and 1 inclusive. It doesn't occur or happen, it just is.
Your computer is generating a (likely random) number between 0 and 1 inclusive, and testing whether the generated number is less than the probability p. In this case you would say the condition was satisfied.
If the condition is satisfied, you consider that an event, such as the triggering of an action, or logging that the condition was satisfied. In the former case you can say the action was triggered, or that the event occurred.
You could say the X event occurred, or that the X condition was satisfied, after establishing that X is the event or condition associated with probability p. In no case would you state p by name, unless you had a very wordy the condition associated with p was satisfied. In your case if you'd like to use "trigger", then the condition associated with p was triggered would work.

A: In game development, this might be termed a proc, but this may not be a term of art in your field.
Short for either "procedure" or "programmed random occurrence" (depending on who you ask) it is used as a shorthand for event triggering based on "dice rolls" or other conditions.
Rhymes with "dock." Used as a noun or verb.

A: The word you are looking for is "event"
For example, we might write, "with probability 0.5718 the event will occur.
Probabilities are numeric quantities, such as 89.2%
Events are things like, "the card player drew a spade or a club from the deck"


Q: CGImageMaskCreate: invalid mask bits/component: 16 I am updating an old objc project.
I noticed that creating an image mask doesn't work on iOS 11 & iPhone 7
I get "CGImageMaskCreate: invalid mask bits/component: 16. " warning.
If I decrease bits per component used to 8 (which seems to be maximum) it works but quality of gradient I draw is pretty bad.
Here is my code:
- (void)_background:(CGRect)rect
{
    // context for drawing
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGImageRef backgroundimage = CGBitmapContextCreateImage(context);
    CGContextClearRect(context, rect);
    //CGContextDrawImage(context, rect, backgroundimage);

    // save state
    CGContextSaveGState(context);

    // flip the context (right-sideup)
    CGContextTranslateCTM(context, 0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    //colors/components/locations
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    CGFloat black[4] = {0.0,0.0,0.0,BACKGROUND_ALPHA};
    CGFloat white[4] = {1.0,1.0,1.0,1.0};//clear

    CGFloat components[8] = {

        white[0],white[1],white[2],white[3],
        black[0],black[1],black[2],black[3],
    };

    CGFloat colorLocations[2] = {0.25,0.5};

    // draw spotlights
    NSInteger spotlightCount = _positionArray.count;
    for (int i=0; i<spotlightCount; ++i)
    {
        // center and radius of spotlight
        CGPoint c = [[_positionArray objectAtIndex:i] CGPointValue];
        CGFloat radius = [[_radiusArray objectAtIndex:i] floatValue];

        CGContextSaveGState(context);

        //add gradient
        //create the gradient Ref
        CGGradientRef gradientRef = CGGradientCreateWithColorComponents(colorspace, components, colorLocations, 2);
        CGContextDrawRadialGradient(context, gradientRef, c, 0.0f, c, radius*2, 0);
        CGGradientRelease(gradientRef);

        CGContextRestoreGState(context);
    }

    CGColorSpaceRelease(colorspace);
    CGContextRestoreGState(context);

    //convert drawing to image for masking
    CGImageRef maskImage = CGBitmapContextCreateImage(context);

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskImage),
                                        CGImageGetHeight(maskImage),
                                        CGImageGetBitsPerComponent(maskImage),
                                        CGImageGetBitsPerPixel(maskImage),
                                        CGImageGetBytesPerRow(maskImage),
                                        CGImageGetDataProvider(maskImage), NULL, NO);

    //
    //------> CGImageMaskCreate: invalid mask bits/component: 16.
    //

    //mask the background image
    CGImageRef masked = CGImageCreateWithMask(backgroundimage, mask);
    CGImageRelease(backgroundimage);
    //remove the spotlight gradient now that we have it as image
    CGContextClearRect(context, rect);

    //draw the transparent background with the mask
    CGContextDrawImage(context, rect, masked);

    CGImageRelease(maskImage);
    CGImageRelease(mask);
    CGImageRelease(masked);
}

Do you have an idea?
Thanks.

A: CGImageMaskCreate is documented as “Image masks must be 1, 2, 4, or 8 bits per component.”


Q: Excel return cell without duplicates I have a column that uses the LOOKUP function to pull a list of names from a separate sheet within the same workbook. The list of names is concatenated using an IF function - the list is in a single cell; names are separated by commas; and some names repeat.
Is there a function that can be applied or some other excel magic that can return this list of names without duplicates?
e.g. I have a table of company names in one column and account managers in another column - the LOOKUP function pulls the list of all account managers associated with that company into one cell with names separated by commas. For example, currently, the account managers shown for "Google" (A2) are "Bob, Joe, Bob, Tom, Bob" (B2), but I would like for it to only show "Bob, Joe, Tom".
EDIT:
Each row details a specific sale.
Column A: Company (a single company can appear multiple times)
Column B: Account Manager (a single name can be associated with multiple Companies)
Column C: concatenates Account Managers into single line using formula =IF(A2=A1,C1&", " & B2,B2)
Every time new data is added, the entire sheet is sorted A-Z by Company. The goal of the concatenation is to have ALL Account Managers associated with that particular company in one cell so that that cell can be referenced in the table mentioned above, which appears on a separate sheet in this workbook; however, if that AM has made multiple sales for the same company, the formula still adds it to the final list, which can result in a list of "Bob, Joe, Bob, Tom, Bob" when I want to see "Bob, Joe, Tom".
The formula I use in the table to reference this list of AMs for each company is =LOOKUP(A5,'7.1.16 data'!A:A,'7.1.16 data'!C:C)

A: Just add a SEARCH query in your IF statement:
=IF(A2=A1,IF(ISNUMBER(SEARCH(B2, C1)), C1, C1 &", " & B2),B2)

Regards
Cg


Q: Cancelling Http connection in android I am using org.apache.http and I've this code:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);

HttpResponse resp = client.execute(get);
HttpEntity entity = resp.getEntity();

InputStream input = entity.getContent();

...
//Read the bytes from input stream

This is the code I am using to download files over Http, I want to cancel the connection(may be user chooses to) What is the graceful way to close the connection. I found 2 ways, Both cancels the download.

*

*Closing inputsteram, input.close(); which causes IOException.

*Aborting HttpGet object, get.abort() causes SocketException.

I have try catch, so no erros, but without throwing exception,
is there a way to cancel or abort the connection?
What is the right way to go about it ?

A: The proper way doing this is sending FIN value to the server side.
How ever in android you do not have the option to be involved in this level, so you can implement by your self using C, or use one of the methods you mention in your question.

A: Using HttpUriRequest#about is the right way in my opinion. This will cause immediate termination of the underlying connection and its eviction from the connection pool. Newer versions of HttpClient (4.2 and newer) intercept SocketExceptions caused by premature request termination by the user. The problem is that Google ships a fork of HttpClient based on an extremely outdated version (pre-beta1). If you are not able or willing to use a newer version of HttpClient your only option is to catch and discard SocketException in your code.

A: Use this
client.getConnectionManager().closeExpiredConnections();
client.getConnectionManager().shutdown();

Now you can decide where would you like to write these 2 lines in code.. It will close the connection using the DefaultHttpClient object that you created.
Let me know if this helps you.

A: Try to cancel the task when you want to interrupt the connection:
            task.cancel(true);
This will cancel the task and the threads running in it.
Check this for reference:
public final boolean cancel (boolean mayInterruptIfRunning)
Since: API Level 3
Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.
Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never invoked. After invoking this method, you should check the value returned by isCancelled() periodically from doInBackground(Object[]) to finish the task as early as possible.
Parameters
mayInterruptIfRunning   true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.
Returns
false if the task could not be cancelled, typically because it has already completed normally; true otherwise


Q: jQuery Remote validation for multiple fields I have a form with two fields User ID and Email ID.  I am trying to validate value of each field is already taken or not using same php file with jQuery remote validation.
But my confusion is how should be the remote file in my case (validate.php). How it can determine the fields.
My code looks like:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Validationt</title>

<script type="text/javascript">
$(document).ready(function(){
   $("form").validate({
      rules: {
         userid: {
            required: true,
            remote: {
               url: "validate.php",
               type: "post",
             }
         }
          emailid: {
            required: true,
            remote: {
               url: "validate.php",
               type: "post",
             }
         }
      },
      messages: {
         userid: {
            remote: jQuery.validator.format("userid {0} is already taken")
     }
         emailid: {
            remote: jQuery.validator.format("emailid {0} is already taken")
     }
      }
   });
});
</script
</head>
<body>
<form method="post" id="form" action="">
<input id="userid" name="userid"  type="text" />
<input id="emailid" name="emailid" type="text" />
<input type="submit" name="submit" id="submit"/>
</form>
</body>
</html>

Any help ?

A: Like,
//validate.php

//get the post fields
$email_address = trim( $_POST["emailid"] );
//check if email exists against database, like
if( is_valid_from_db( $email_address ) ) {
  return TRUE;
}
else {
  return FALSE;
}

A: I am sure you have looked at the docs:
http://docs.jquery.com/Plugins/Validation/Methods/remote#options
validate.php just needs to do what it says validate the fields.
This other question might be of some help:
jQuery Remote validation

A: I was also looking for an answer for this problem of validating multiple fields with remote method.
To determine each field separately, you don't have to define remote method for each field. Whereas you can define remote method for your 'emailid' field and you can send 'userid' alongside the emailid using data option as follows.
            emailid: {
                required: true,
                remote: {
                   url: "validate.php",
                   type: "post",
                   data: {
                       userid: function() {
                       return $("#userid").val();
                      }
                   }
                 }
             }

So you can have your js like this
<script type="text/javascript">
   $(document).ready(function(){
   $("form").validate({
      rules: {
         userid: {
            required: true
         }
          emailid: {
            required: true,
            remote: {
               url: "validate.php",
               type: "post",
               data: {
                   userid: function() {
                   return $("#userid").val();
                  }
               }
             }
         }
      },
      messages: {
         userid: {
            remote: jQuery.validator.format("userid {0} is already taken")
     }
         emailid: {
            remote: jQuery.validator.format("emailid {0} is already taken")
     }
      }
   });
});
</script>

The above will post userid and emailid to your validate.php where you can follow DemoUser's answer. But make sure the returning values (true/false) are string values


Q: Phone Number Formatting Python Whenever i run my program is print the number 10 randomly and i don't know where its coming from. Anyone help me out?

def main():
    phoneNumber=int(input("Enter a 10 digit unformatted telephone number in the format ##########: "))
    tempNumber = []
    phoneNumber = str(phoneNumber)
    length = len(phoneNumber)
    index=0
    print(length)

    if (length ==10):
        print("The unformatted number is: ",phoneNumber)
    else:
        print("The telephone number was NOT entered in unformatted format ##########.")

    for num in phoneNumber:
        tempNumber.append(num)

    tempNumber.insert(0,"(")
    tempNumber.insert(4,")")
    tempNumber.insert(8,"-")
    phoneNumber = ''.join(tempNumber)
    print("The formatted number is: ",phoneNumber)

main()

A: You are printing the length of the input given by user, so that's why 10 is printed out (see statement no. 6 inside main() function).
phoneNumber = str(phoneNumber)
length = len(phoneNumber)
index = 0
print(length)  # <--- this statement is printing the length of the input


Q: C# Date in CSV file I have to  change a csv file with several dates in it. Every row starts with a date followed whith data.
11-nov-2015,data,data,data
10-nov-2015,data,data,data
9-nov-2015,data,data,data
With the following code I put the data in the right place (20141109 (yyyymmdd))
string[] values = lines1[i].Split(',');

if (values.Length >= 3)
{
    string[] parts = values[0].Split('-');
    if (parts.Length == 3)
    {
        values[0] =  String.Format("{0}-{1}-{2}", parts[2], parts[1], parts[0]);
        lines1[i] = String.Join(",", values);
    }
}

But two problems remain:
1) The month has to change from nov to 11
2) In the file I download the day for example 9-nov-2014 has to change to 09. for 8-nov-2014 to 08. So an extra 0.
How can this be solved in C#

A: Instead of making your own datetime format parser, you should use the one already available for you. DateTime.TryParseExact is your tool to convert a string in a date when you know the exact format.
Converting back the date, in the string format that you like, is another task easily solved by the override of ToString() specific for a datetime
string[] values = lines1[i].Split(',');
if (values.Length >= 3)
{
    DateTime dt;
    if (DateTime.TryParseExact(values[0], "d-MMM-yyyy",
        System.Globalization.CultureInfo.CurrentCulture,
        System.Globalization.DateTimeStyles.None, out dt))
    {
        values[0] = dt.ToString("yyyyMMdd");
        lines1[i] = String.Join(",", values);
    }
}

A: I would parse the string into a date and then write it back using a custom date format. From this link  we can write this code:
String pattern = "dd-MMM-yyyy";
DateTime dt;
if (DateTime.TryParseExact(values[0], pattern, CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out dt)) {
    // dt is the parsed value
    String sdt = dt.ToString("yyyyMMdd"); // <<--this is the string you want
} else {
    // Invalid string, handle it as you see fit
}


Q: How would Earth's moment of inertia be affected if all people jumped simultaneously? We were arguing about this thought experiment with a friend.
He was claiming that people continue to consist of earth's mass regardless of whether they touch the ground or not, whereas I claimed that when people lose touch of the ground, they momentarily cease to consist of the rigid body "earth". So, he concluded what when people jumped, earth's moment of inertia would increase, whereas I concluded that it would decrease.
Which is the right opinion?

A: The answer is that you simply need to define what the Earth actually is.  If you define it one way, the moment of inertia will increase.  If you define it another way, it will decrease.
All the people in the world jumping is a pretty tiny activity.  The phrase "fleas on the back of an elephant" comes to mind.  It's easier to visualize this if we raise the stakes.  Instead of everyone jumping, lets have the entire mantle of the Earth get involved.  Really raise the stakes.  Have the entire mantle of the earth jump up a few feet, and we can worry about how to put things back together later.
If we define the Earth the way you did, the equivalent to this whole mantle jumping would be to say that the mantle ceases to be part of the Earth.  All that's left to be "Earth" is the core.  In such a situation, it's trivial to see that the moment of inertia must decrease.  The core has a far smaller moment than the entire mantle and core did.
However, if we define the Earth the way your friend did, then the mantle is still part of the Earth.  As such, there's more mass further from the center than there was before, so the moment has increased.
The paradox is not actually one of physics, but of linguistics.  The physics answer is that you are looking at the moment of inertia of two different bodies, so of course you will get different answers.  But linguistically, we like the idea that "the Earth" continues to be "the Earth," even after a radical change in topology.
Agree upon what "the Earth" means, and the answer becomes simple.
The answer probably depends on what you intend to do with the earth.  If you want to make it spin just a hair faster, then your definition is probably the more useful.  Atmospheric drag and the forces of people upon the dirt as they hit the ground will ensure the people continue to rotate at the same rate as the ground does.  Thus, it makes sense to keep them as part of the Earth, just as it made sense to keep the mantle as part of the Earth because it will soon settle and regain its position.  In such a situation, your friend is more right.
On the other hand, if you want everyone to jump and then have Superman spin the planet.  Spin it fast, fast, fast, faster until it would fling any human that touches it off into space (and thus also fast enough that the Earth will soon disintegrates under its own centrifugal pseduoforces), and I'm going to side with you rather than your friend.  In such a situation, the object that Superman must spin has a lower inertia because he doesn't have to spin up the people with it.  As such, you are more right.
It's all quite relative, for it's really all language.


Q: Cassandra 2.2.11 add new map column from text column Let's say I have table with 2 columns
primary key: id - type varchar
and non-primary-key: data - type text
Data column consist only of json values for example like:
{
"name":"John",
"age":30
}

I know that i can not alter this column to map type but maybe i can add new map column with values from data column or maybe you have some other idea?
What can i do about it ? I want to get map column in this table with values from data

A: You might want to make use of the CQL COPY command to export all your data to a CSV file.
Then alter your table and create a new column of type map.
Convert the exported data to another file containing UPDATE statements where you only update the newly created column with values converted from JSON to a map. For conversion use a tool or language of your choice (be it bash, python, perl or whatever).
BTW be aware, that with map you specify what data type is your map's key and what data type is your map's value. So you will most probably be limited to use strings only if you want to be generic, i.e. a map<text, text>. Consider whether this is appropriate for your use case.


Q: Inconsistent outputs from Scala Spark and pyspark job I am converting my Scala code to pyspark like below, but got different counts for the final RDD.
My Scala code:
val scalaRDD = rowRDD.map {
  row: Row =>
  var rowList: ListBuffer[Row] = ListBuffer()
  rowList.add(row)
  (row.getString(1) + "_" + row.getString(6), rowList)
}.reduceByKey{ (list1,list2) =>

  var rowList: ListBuffer[Row] = ListBuffer()
  for (i <- 0 to list1.length -1) {
    val row1 = list1.get(i);

    var foundMatch = false;

    breakable {
      for (j <- 0 to list2.length -1) {
         var row2 = list2.get(j);
         val result = mergeRow(row1, row2)
         if (result._1) {
           list2.set(j, result._2)
           foundMatch = true;
           break;
         }
      } // for j loop
    } // breakable for j

    if(!foundMatch) {
      rowList.add(row1);
    }
  }

  list2.addAll(rowList);

  list2
}.flatMap { t=> t._2 }

where
def mergeRow(row1:Row, row2:Row):(Boolean, Row)=  {
  var z:Array[String] = new Array[String](row1.length)
  var hasDiff = false

  for (k <- 1 to row1.length -2){
               // k = 0  : ID, always different
               // k = 43 : last field, which is not important

      if (row1.getString(0) < row2.getString(0)) {
        z(0) = row2.getString(0)
        z(43) = row2.getString(43)
      }  else {
        z(0) = row1.getString(0)
        z(43) = row1.getString(43)
      }

      if (Option(row2.getString(k)).getOrElse("").isEmpty && !Option(row1.getString(k)).getOrElse("").isEmpty) {
          z(k) = row1.getString(k)
          hasDiff = true
      } else if (!Option(row1.getString(k)).getOrElse("").isEmpty && !Option(row2.getString(k)).getOrElse("").isEmpty && row1.getString(k) != row2.getString(k)) {
          return (false, null)
      } else {
          z(k) = row2.getString(k)
      }
  } // for k loop

  if (hasDiff) {
      (true, Row.fromSeq(z))
  } else {
      (true, row2)
  }
}

I then tried to convert them to pyspark code as below:
pySparkRDD = rowRDD.map (
  lambda row : singleRowList(row)
).reduceByKey(lambda list1,list2: mergeList(list1,list2)).flatMap(lambda x : x[1])

where I have:
def mergeRow(row1, row2):
  z=[]
  hasDiff = False

  #for (k <- 1 to row1.length -2){
  for k in xrange(1, len(row1) - 2):
               # k = 0  : ID, always different
               # k = 43 : last field, which is not important

      if (row1[0] < row2[0]):
        z[0] = row2[0]
        z[43] = row2[43]
      else:
        z[0] = row1[0]
        z[43] = row1[43]

      if not(row2[k]) and row1[k]:
          z[k] = row1[k].strip()
          hasDiff = True
      elif row1[k] and row2[k] and row1[k].strip() != row2[k].strip():
          return (False, None)
      else:
          z[k] = row2[k].strip()

  if hasDiff:
      return (True, Row.fromSeq(z))
  else:
      return (True, row2)

and
def singleRowList(row):
  myList=[]
  myList.append(row)

  return (row[1] + "_" + row[6], myList)

and
def mergeList(list1, list2):
  rowList = []
  for i in xrange(0, len(list1)-1):
    row1 = list1[i]
    foundMatch = False
    for j in xrange(0, len(list2)-1):
      row2 = list2[j]
      resultBool, resultRow = mergeRow(row1, row2)
      if resultBool:
          list2[j] = resultRow
          foundMatch = True
          break

    if foundMatch == False:
      rowList.append(row1)

  list2.extend(rowList)

  return list2

BTW, rowRDD is converted from a data frame. i.e. rowRDD = myDF.rdd
However, I got different counts for scalaRDD and pySparkRDD. I checked the codes many times but couldn't figure out what I missed. Does anyone have any ideas? Thanks!

A: Consider this:
scala> (1 to 5).length
res1: Int = 5

and this:
>>> len(xrange(1, 5))
4


Q: GroupBy first result of lookup table in Entity Framework Core I'm trying to get the total Man Days worked by volunteers per section between a date range. There is an attendance table which includes the day and the member id to map to the member table.  There is also a section table to list all the sections and a membertosection table as a member can be in more than one section.
I want to group by the first section a member is in and then have a count of all the attendance days for that section.
The following works perfectly where I'm grouping by a 1 to many field (Category) on the members table but I can't work out how to change this to the first section (If the member has a section)
var result = await _context.Attendance
                .Where(p => p.Day >= firstDayOfLastQuarter && p.Day <= lastDayOfLastQuarter)
                .GroupBy(p => p.Member.Category.Name)
                .Select(p => new { key = p.Key, count = p.Count() })
                .ToListAsync();

I'm looking for something like
var result = await _context.Attendance
                .Where(p => p.Day >= firstDayOfLastQuarter && p.Day <= lastDayOfLastQuarter && p.Member.MemberToSection.Any(s => s.MemberId == p.MemberId))
                .GroupBy(p => p.Member.MemberToSection.First().Section.Name)
                .Select(p => new { key = p.Key, count = p.Count() })
                .ToListAsync();

Update
T-Sql code that produces the desired result is
SELECT Count(*) as Total, Section.Name
FROM Attendance
LEFT JOIN Member on Attendance.Member_Id = Member.Id
OUTER APPLY (
  SELECT TOP(1) sec.id, sec.Name
  FROM MemberToSection m2s
  LEFT JOIN Section sec ON m2s.Section_Id = sec.Id
  WHERE m2s.Member_Id = Member.Id
) as Section
WHERE Attendance.Day >= '2016-10-01' AND Attendance.Day <= '2016-12-31'
GROUP BY Section.Name

The "something like" code returns the error
An unhandled exception occurred while processing the request.

ArgumentException: Property 'System.String Name' is not defined for type 'Microsoft.EntityFrameworkCore.Storage.ValueBuffer'

Classes
As requested here are the relevant classes
Attendance.cs
public partial class Attendance
{
    public long Pk { get; set; }
    public int MemberId { get; set; }
    public DateTime Day { get; set; }

    public virtual Member Member { get; set; }
}

Member.cs
public partial class Member
{
    public Member()
    {
        MemberToSection = new HashSet<MemberToSection>();
    }

    public int Id { get; set; }
    public int? CategoryId { get; set; }

    public virtual ICollection<MemberToSection> MemberToSection { get; set; }
}

MemberToSection.cs
public partial class MemberToSection
{
    public int SectionId { get; set; }
    public int MemberId { get; set; }

    public virtual Member Member { get; set; }
    public virtual Section Section { get; set; }
}

Section.cs
public partial class Section
{
    public Section()
    {
        MemberToSection = new HashSet<MemberToSection>();
    }

    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<MemberToSection> MemberToSection { get; set; }
}

A: The (currently combined) EF documentation starts with Compare EF Core & EF6.x section which contains the very "useful" topic Which One Is Right for You. Well, looks like EF Core is not for you (yet). The following applies to latest at this time EF Core v1.1.0.
First, GroupBy (even by simple primitive property) is always processed in memory.
Second, there are a lot of internal bugs causing exceptions when processing pretty valid LINQ queries like yours.
Third, after some trial and error, the following equivalent construct works for your case (at least does not generate exceptions):
.GroupBy(p => p.Member.MemberToSection.Select(m => m.Section.Name).FirstOrDefault())

(btw, irrelevant to the issue, the s => s.MemberId == p.MemberId condition inside the p.Member.MemberToSection.Any call is redundant because it is enforced by the relationship, so simple Any() would do the same.)
But now not only the GroupBy is performed in memory, but also the query is causing N + 1 SQL queries similar to EF Core nested Linq select results in N + 1 SQL queries. Congratulations :(


Q: Use layers or invoke another lambda? I have a module that maintains a connection instance to a redis server:
const getClient = (() => {
    let client;
    return () => {
        if (!client) client = clientFactory(); // lazy loading of the redis client
        return client;
    }
})();

And this module is intended to be deployed on AWS Lambda. As per best practices suggest, the redis client in the closure above shall never be destroyed manually in favour of context reuse, and will be automatically destroyed when the lambda invocation instance is killed.
Now the problem is: I have some other modules, which will also be deployed on lambda as separate lambda functions, and will need to utilize the redis client module. Should I set the redis module as a reusable layer, or should I deploy the module as yet another separate function, and directly invoke the function from the calling modules?
Concerns for using layer: the redis connection will be instantiated for every separate calling module, which is not good for context reuse.
Concerns for invoking another lambda function: network overhead.
As I understand invocation between two lambda functions, the caller will send an API request to the callee, producing extra network overhead. So will this matter more than poor context reusing?


Q: How to delete a specific cell in a csv file when the contents is said in an input in python     elif addordelete = "delete":
         whichdelete = input("What thing do you want to delete? ")

GameCharacter.csv
I want to know how to delete a specific cell in a csv file through a python input.
For example if the user in the python program says that they want to delete MP40 from the file, then it should delete. Can someone explain how to do this in simple terms as possible (I'm kind of a python noob. Code is appreciated.

A: You'll have to import the whole CSV into python, process it and saving it back to file.
Here's a simple snippet which opens the CSV, processes it asking what you want to delete, then saves it back again.
 You can start from this code to get what you need.
import csv

try:
    csvfile = open('testcsv.csv','rb')
    table = [row for row in csv.reader(csvfile)] #further parameters such as delimiters on doc
    whichdelete = whichdelete = input("What thing do you want to delete? ")
    header = table.pop(0) #remove header and save it to header variable
    res = [row for row in table if whichdelete not in row] #save result without the row you want to delete
    csvfile.close()
except IOError:
    print "File not found"
    quit()

try:
    resultFile = open('resultCSV.csv','wb+')
    writer = csv.writer(resultFile)
    writer.writerow(header)
    for row in res:
        writer.writerow(row)
    resultFile.close()

except IOError:
    print "Error creating result file"
    quit()


Q: OOP Javascript, get instance name I have an object and I write the instance:
var table1=new searchTable(someoptions)

Is there anyway to get "table1" programatically from inside the object?

A: No. Objects have no knowledge of what variables and properties (there can be multiple) they are assigned to.

A: There is absolutely no way of doing this.
When you do
LHS = RHS

RHS has no clue of what its result is going to be assigned to.


Q: Capture Stack Trace in Managed Package Can you capture and store stack trace information in a managed package? This page says that the idea was delivered, but that's not what I'm seeing.
The same code stores this stack trace in the unmanaged version:
 Stack Trace:
    Class.PMT_PaymentCreator.<init>: line 107, column 1
    Class.PMT_Payment_TDTM.run: line 48, column 1
    Class.TDTM_TriggerHandler.runClass: line 118, column 1
    Class.TDTM_TriggerHandler.run: line 68, column 1
    Trigger.TDTM_Opportunity: line 34, column 1

And this one in the managed one:
 Stack Trace:
   (npsp)

I'm using the getStackTraceString method from the Exception class.

A: You need to be an ISV and login to the customers org using Subscriber support to see any logging from the managed package, including the stack trace.
See comments on Capturing process information with Apex

A: In addition to the ISV subscribers console method posted by Daniel backline support is technically able to "unmask debug logs" for a managed namespace temporarily which will expose this info. You'll need consent from the package author (if it's not you) to make this happen.


Q: c# Model abstraction and generics, cast unknown generic like Java Basic Java way
class SomeModelController {

    public void makeSomeRequest<T extends BaseJsonClass>(Type type, RequestCallback requestCallback) {
        // Do request stuff.
        requestCallback.success(Type.cast(sucessObject));
    }
}

// Some code
ModelController.makeRequest<UserLoginResponse>(UserLoginResponse.class, new RequestCallback() {
    public void success(UserLoginResponse sucessObject) {
        // Object is now treated like response.
    }
}

I'm aware that C# does not have a type erasor; so I can just use T (Generic as is?)
My C# class and where I'm struggling:
public class Response<T> {

    private Action<T> success;
    private Action<FailedReason> failed;

    public Response(Action<T> success, Action<FailedReason> failed) {
        this.success = success;
        this.failed = failed;
    }

    public void Success<T>(T objectSuccess) {
        // ?? How to convert success object to type?
        success.Invoke(objectSuccess);
    }

    public void Failed(FailedReason failedReason) {
        failed.Invoke(failedReason);
    }

}

Edit 1
I'm getting the following complaint from the compiler:
I'm getting "Cannot implicitly convert T to T" when trying to compile.

A: You can simply call
public void Success(T objectSuccess) {
    success(objectSuccess);
}

objectSuccess is of type T. That's exactly what Action<T> success expects as parameter. No conversion is required.
You can think of success as being a method declared like this:
void success(T arg)
{
}

And as  Jorn Vernee says, remove <T> from Success<T>. You don't need a generic type parameter for this method, as it uses the generic type parameter of the class. If for some reason you need different generic type parameters for class and method, you must give them different names. But that's not the case here.


Q: How to speedup the Chromium loading process under puppeteer, bypass the proxy check When using puppeteer, the Chromium page loading speed is sensibly slow than loading in a normal Chrome.
I can notice some text on the status bar about proxy, which is not seen in a normal Chrome.
Any way to speedup the puppeteer Chromium page laoding? It is a few seconds, but many times.

A: puppeteer Chromium do the proxy check by default, which is a waste of time if you do not use proxy.
Can disable it by
const browser = await puppeteer.launch({
  headless: false,
  args: ["--proxy-server='direct://'", '--proxy-bypass-list=*'],
});

then it will as fast as normal Chrome


Q: OpenWRT - Openconnect VPN on isolated SSID I'm trying to add a third SSID to my OpenWRT router which only connects users to an Openconnect VPN network.
The router has two existing SSIDs which connect to the LAN+internet on 2.4 and 5.0 GHz antenna arrays. I'm able to connect directly to the VPN network via NetworkManager on my Linux PC.
When connecting to my new SSID, I get an IP but no internet connection. I'm also unsure whether the VPN connection is succeeding or not.
I followed the instructions at https://github.com/openwrt/packages/tree/master/net/openconnect as well as tried to understand what's going on in this question but with no success.
Below are the additions to the config files I made:
/etc/config/network:
# VPN SSID Interface
config interface 'vpn'
    option proto 'static'
    option ipaddr '192.168.34.1'
    option netmask '255.255.255.0'
    option ipv6 '0'

# Openconnect
config interface 'myvpn'
    option proto 'openconnect'
    option interface 'wan' # Is this right? Was on github's openconnect example
    option server 'myvpn.com'
    option port '4443'
    option username 'user'
    option password 'password'
    #option serverhash '' # Don't need this?
    option defaultroute '0'
    option authgroup 'DEFAULT'
    option token_mode 'rsa'
    option token_secret 'http://127.0.0.1/securid/ctf?ctfData=...'
    option ipv6 '0'

/etc/config/wireless
config wifi-iface
    option device 'radio1' # My 5.0 GHz antenna
    option network 'vpn'
    option mode 'ap'
    option ssid 'myVPN'
    option hidden '1'
    option encryption 'psk2'
    option key 'some super secret key'

/etc/config/dhcp
config dhcp 'vpn'
    option interface 'vpn'
    option start '100'
    option limit '150'
    option leasetime '12h'

/etc/config/firewall
config zone
    option name     vpn
    list   network      'vpn'
    option input        ACCEPT
    option output       ACCEPT
    option forward      ACCEPT

config zone
    option name     myvpn
    list   network      'myvpn'
    option input        ACCEPT
    option output       ACCEPT
    option forward      ACCEPT

config forwarding
    option src      vpn
    option dest     myvpn

I also restart all of the components:
# /etc/init.d/network restart
# /etc/init.d/dnsmasq restart
# /etc/init.d/firewall restart
# wifi
# ifup myvpn

I do get the following messages when running # /etc/init.d/firewall restart:
Warning: Section @zone[2] (myvpn) cannot resolve device of network 'myvpn'
Warning: Section @zone[2] (myvpn) has no device, network, subnet or extra options


Q: How many ways to pick a committee of 5, out of 12 seniors and 8 juniors, which contains at least 3 seniors and 1 junior? This is my reasoning:
First we choose 3 seniors out of 12, then we choose 1 junior out of 8, then we have 12 - 3 + 8 - 1 = 16 students left. The last spot can be taken by either a senior or junior so we choose 1 out of 16. Hence there are $ { 12 \choose 3 } { 8 \choose 1 } { 16 \choose 1} = 28160  $ combinations.
However, this is the solution:
We can have either 4 seniors and 1 junior or 3 seniors and 2 juniors. So the total number of combinations is $ { 12 \choose 4 }{ 8 \choose 1} + {12\choose 3}{8 \choose2} = 10120. $
Where did my reasoning go wrong?

A: You are double counting. Notice that when you split your sets like that, suppose there is a senior called $A,$ there is the possibility that you have chosen $A$ using your $\binom{12}{3}$ as some of those members. But also, there is the possibility that you chose $A$ as the person in the remaining $16.$ When, in the right answer, they completely split the sum into two sums in which the people of each group is chosen, they eliminate that possibility.


Q: Rewrite Api - Invalid Api Path i'm new with magento, but i need help with API rewrite.
I've added some methods up to Catalog_Product_Api_V2 which are working well.
I can also call them with SOAPv2.
Now i want to add product attributes product "catalogProductAttributeCreate(...)" but now  i'm getting this error message:
Fatal error: Uncaught SoapFault exception: [3] Invalid api path. ...
Here's my SOAPv2 Call:
$data = array(
    "attribute_code" => "test_attribute",
    "frontend_input" => "text",
    "scope" => "1",
    "default_value" => "1",
    "is_unique" => 0,
    "is_required" => 0,
    "apply_to" => array("simple"),
    "is_configurable" => 0,
    "is_searchable" => 0,
    "is_visible_in_advanced_search" => 0,
    "is_comparable" => 0,
    "is_used_for_promo_rules" => 0,
    "is_visible_on_front" => 0,
    "used_in_product_listing" => 0,
    "additional_fields" => array(),
    "frontend_label" => array(array("store_id" => "0", "label" => "some label"))
   );

   $result10 = $client->catalogProductAttributeCreate($session, $data);

Here's my config.xml
<catalog>
    <rewrite>
        <product_api_v2>MyCompany_MyModule_Model_Catalog_Product_Api_V2</product_api_v2>
    </rewrite>
</catalog>

Do I overwrite all the standard methods like "create, update, info, etc."?
Please help me... :)


Q: enumerate days of week in t-sql Is anybody to know how to enumerate all week's days in T-SQL, so that we have in the ouput a string like: 'Sunday, Monday, Tuesday, ...'

A: WITH    week (dn) AS
        (
        SELECT  1
        UNION ALL
        SELECT  dn + 1
        FROM    week
        WHERE   dn < 7
        )
SELECT  DATENAME(dw, dn + 5)
FROM    week

Replace dn + 5 with dn + 6 if your week starts from Monday.
If you need a single comma separated string instead of a set, use this:
WITH    week (dn, dname) AS
        (
        SELECT  1, CAST(DATENAME(dw, 6) AS NVARCHAR(MAX))
        UNION ALL
        SELECT  dn + 1, dname + ', ' + DATENAME(dw, dn + 6)
        FROM    week
        WHERE   dn < 7
        )
SELECT  dname
FROM    week
WHERE   dn = 7

A: A straight select that will work with any SET DATEFIRST setting
select
    datename(dw,   6-@@datefirst) + ', ' +
    datename(dw, 1+6-@@datefirst) + ', ' +
    datename(dw, 2+6-@@datefirst) + ', ' +
    datename(dw, 3+6-@@datefirst) + ', ' +
    datename(dw, 4+6-@@datefirst) + ', ' +
    datename(dw, 5+6-@@datefirst) + ', ' +
    datename(dw, 6+6-@@datefirst)

If you don't care about region (Monday or Sunday as first day of week), then just
select
    datename(dw, 0) + ', ' + datename(dw, 1) + ', ' +
    datename(dw, 2) + ', ' + datename(dw, 3) + ', ' +
    datename(dw, 4) + ', ' + datename(dw, 5) + ', ' +
    datename(dw, 6) + ', '

It will perform much better than going through CTE and will also work in 2000 should you ever need it.

A: The fastest means is to statically define the comma separated list. I don't know if SET DATEFIRST affects only the database -- if it's the entire instance, I would really hesitate to use SET DATEFIRST.
Rather than using recursion, you can use the values from MASTER..SPT_VALUES, and a combination of the STUFF and FOR XML PATH functions (Caveat: SQL Server 2005+):
Week starting on Sunday:
SELECT STUFF((SELECT ', ' + x.wkday_name
                FROM (SELECT DISTINCT DATENAME(dw, t.number) AS wkday_name,
                             t.number
                        FROM MASTER.dbo.SPT_VALUES t
                       WHERE t.number BETWEEN -1 AND 5) x
                    ORDER BY x.number
                     FOR XML PATH ('')), 1, 2, '')

Week starting on Monday:
SELECT STUFF((SELECT ', ' + x.wkday_name
                FROM (SELECT DISTINCT DATENAME(dw, t.number) AS wkday_name,
                             t.number
                        FROM MASTER.dbo.SPT_VALUES t
                       WHERE t.number BETWEEN 0 AND 6) x
                    ORDER BY x.number
                     FOR XML PATH ('')), 1, 2, '')

Comparison:
The statically defined list won't return a query plan for me on SQL Server 2005.  Quassnoi's recursion example on 2005 has a subtree cost of 0.0000072; SPT_VALUES has a subtree cost of 0.0158108.  So the recursive approach is appears more efficient than SPT_VALUES -- possibly due to the very small size?


Q: Divergence Theorem for 1D As all of us know, in divergence theorem we have This:

this means instead of integrating a divergence of a vector over a volume, you can integrate that vector over the surface.
But I'm wondering what can we do with This:

I'm looking for it's concept and formula.
EDIT:
in other words I want to know how we use divergence theorem when we have only one partial derivative for 3D vector and what is its intuition.

A: Consider $\vec{A}=(f_x(x,y,z),0,0)$ then divergence $${\rm div}\,\vec{A} =\frac{\partial f_x}{\partial x}$$
Then using divergence theorem gives $$\iiint \frac{\partial f_x}{\partial x}\, dV=\oint f_x (\vec{i}\cdot \vec{n}) dS$$
$f_x$ is dumb function here, we can take $f_x=\vec{F}=f_x \vec{i}+f_y \vec{j}+f_z \vec{k}$ and obtain $$\iiint \frac{\partial \vec{F}}{\partial x}\,dV=\oint \vec{F} (\vec{i}\cdot \vec{n}) \, dS$$


Q: Преобразование строки в переменную Доброго времени суток, возник следующий вопрос, допустим у нас есть javascript код, типа:
// какоето пространство имен...
var myNameSpace = {
    someFunc: function() {
        // какой-то код...
    }
};

И javascript код типа
//  на вход получаем строковые значения
var nameSpaceName = 'myNameSpace';    // имя пространства
var nameSpaceFuncName = 'someFunc';   // и имя функции

//  как вызвать nameSpaceName.nameSpaceFuncName()?
//  на ум приходит только что-то очень страшное типа
eval(nameSpaceName + '.' + nameSpaceFuncName + '()');

A: Можно вот так, но только если "пространство имен" определено в контексте window (т.е "глобально")
window[nameSpaceName][nameSpaceFuncName]()


Q: Docker - failed to compute cache key: not found - runs fine in Visual Studio I've generated a Dockerfile with Visual Studio. It runs in Visual Studio just fine and now I'm trying to build it from Windows itself (docker build ., and I tried many combinations). Yet I get the following error:

When I change copy to ./client.csproj it does continue and then I get:

What am I doing wrong? I changed Docker Linux to Windows, changed WSL, and restarted everything.
Dockerfile client

A: The following command was failing with failed to compute cache key: not found:
docker build -t tag-name:v1.5.1 - <Dockerfile

Upon changing the command to the following it got fixed:
docker build -t tag-name:v1.5.1 -f Dockerfile .

A: In my case I found that docker build is case sensitive in directory name, so I was writing /bin/release/net5.0/publish in the COPY instruction and failed with the same error, I've just changed to /bin/Release/net5.0/publish and it worked

A: Error : failed to compute cache key: "src" not found: not found
in my case , folder/file excluded in .dockerignore

*

*after resolving file from dockerignore able to create image.

A: In my case, I had something like this:
  FROM mcr.microsoft.com/dotnet/aspnet:5.0
  COPY bin/Release/net5.0/publish/ app/
  WORKDIR /app
  ENTRYPOINT ["dotnet", "MyApi.dll"]

And I finally realized that I had the bin folder in my .dockerignore file.

A: Check your .dockerignore file. Possible it ignores needed files for copy command and you get failed to compute cache key error.
.dockerignore may be configured to minimize the files sent to docker for performance and security:
*
!dist/

The first line * disallows all files.  The second line !dist/ allows the dist folder
This can cause unexpected behavior:
FROM nginx:latest

# Fails because of * in .dockerignore
# failed to compute cache key: "/nginx.conf.spa" not found: not found
# Fix by adding `!nginx.conf.spa`  to .dockerignore
COPY nginx.conf.spa /etc/nginx/nginx.conf

RUN mkdir /app

# Works because of !dist/ in .dockerignore
COPY dist/spa /app

Belts and suspenders.

A: I had the same issue, I set the Docker environment to Windows in when adding Docker support. Even running in Visual Studio threw error to that. I changed the environment to Linux as my Docker is running in the Windows Subsystem for Linux (WSL).
Then I moved back to the terminal to run the commands.
I was able to resolve this by moving to the Solutions folder (Root folder).
And I did docker build like this:
docker build -t containername/tag -f ProjectFolder/Dockerfile .

Then I did docker run:
docker run containername/tag

A: The way Visual Studio does it is a little bit odd.
Instead of launching docker build in the folder with the Dockerfile, it launches in the parent folder and specifies the Dockerfile with the -f option.
I was using the demo project (trying to create a minimal solution for another question) and struck the same situation.
Setup for my demo project is
\WorkerService2  ("solution" folder)
   +- WorkerService2.sln
   +- WorkserService2  ("project" folder)
       +- DockerFile
       +- WorkerService2.csproj
       +- ... other program files

So I would expect to go
cd \Workerservice2\WorkerService2
docker build .

But I get your error message.
 => ERROR [build 3/7] COPY [WorkerService2/WorkerService2.csproj, WorkerService2/]                                                                                0.0s
------
 > [build 3/7] COPY [WorkerService2/WorkerService2.csproj, WorkerService2/]:
------
failed to compute cache key: "/WorkerService2/WorkerService2.csproj" not found: not found

Instead, go to the parent directory, with the .sln file and use the docker -f option to specify the Dockerfile to use in the subfolder:
cd \Workerservice2
docker build -f WorkerService2\Dockerfile --force-rm -t worker2/try7 .

docker run -it worker2/try7

Edit (Thanks Mike Loux, tblev & Goku):
Note the final dot on the docker build command.
For docker the final part of the command is the location of the files that Docker will work with. Usually this is the folder with the Dockerfile in, but that's what's different about how VS does it. In this case the dockerfile is specified with the -f. Any paths (such as with the COPY instruction in the dockerfile) are relative to the location specified. The . means "current directory", which in my example is \WorkerService2.
I got to this stage by inspecting the output of the build process, with verbosity set to Detailed.
If you choose Tools / Options / Projects and Solutions / Build and Run you can adjust the build output verbosity, I made mine Detailed.
Edit #2 I think I've worked out why Visual Studio does it this way.
It allows the project references in the same solution to be copied in.
If it was set up to do docker build from the project folder, docker would not be able to COPY any of the other projects in the solution in.  But the way this is set up, with current directory being the solution folder, you can copy referenced projects (subfolders) into your docker build process.

A: Asking for a directory that does not exist throws this error.
In my case, I tried
 > [stage-1  7/14] COPY /.ssh/id_rsa.pub /.ssh/:
------
failed to compute cache key: "/.ssh/id_rsa.pub" not found: not found

I had forgotten to add the /.ssh folder to the project directory. In your case you should check whether /client is really a subfolder of your Dockerfile build context.

A: I had the same issue. In my case there was a wrong directory specified.
My Dockerfile was:
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS publish
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o publish/web src/MyApp/MyApp.csproj

FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=publish publish/web .
EXPOSE 80
CMD ASPNETCORE_URLS=http://*:$PORT dotnet MyApp.dll

Then I realised that in the second build stage I am trying to copy project files from directory publish/web:
COPY --from=publish publish/web .

But as I specified workdir /app in the first stage, my files are located in that directory in image filesystem, so changing path from publish/web to app/publish/web resolved my issue.
So my final working Dockerfile is:
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS publish
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o publish/web src/MyApp/MyApp.csproj

FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=publish app/publish/web .
EXPOSE 80
CMD ASPNETCORE_URLS=http://*:$PORT dotnet MyApp.dll

A: In my case there was a sneaky trailing whitespace in the file name.
------
 > [3/3] COPY init.sh ./:
------
failed to compute cache key: "/init.sh" not found: not found

So the file was actually called "init.sh " instead of "init.sh".

A: I had a similar issues: Apparently, docker roots the file system during build to the specified build directory for security reasons. As a result, COPY and ADD cannot refer to arbitrary locations on the host file system. Additionally, there are other issues with syntax peculiarities. What eventually worked was the following:
COPY ./script_file.sh  /
RUN /script_file.sh

A: I had faced the same issue.
The reason was the name of the DLL file in the Docker file is case sensitive.
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY MyFirstMicroService.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c release -o /app

FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "**MyFirstMicroService.dll**"]

This .dll name should match your .csproj file.

A: This also happens when you don't provide the proper path to your COPY command input. The most important clue I had is that WORKDIR command opens a folder for the container, not in the windows explorer (so it doesn't affect the path you need to specify for the COPY command).

A: In my Case,
i was doing mistake in '/' and ''. Let me explain
Open your dockerfile (it should be named as dockerfile only, not DockerFile or Dockerfile).
You may have something like this-
FROM mcr.microsoft.com/dotnet/runtime:5.0
COPY bin\Release\net5.0\publish .
ENTRYPOINT ["dotnet", "HelloDocker.dll"]
Replace COPY bin\Release\net5.0\publish . to COPY bin/Release/net5.0/publish .

A: in my case, it was a wrong Build with PATH configuration e.g. Docker build context

*

*Simple docker script
docker build .

where . is path to build context

*Gradle+Docker
docker {
    dependsOn build
    dependsOn dockerFilesCopy
    name "${project.name}:${project.version}"
    files "build" // path to build context
}

*Gradle+GitHub action
name: Docker build and push

on:
  push:
    branches: [ main ]

# ...

jobs:
  build:
    runs-on: ubuntu-latest

    # ...

    steps:
      - name: Checkout
        uses: actions/checkout@v2

     # ...

      - name: Build and export to Docker
        uses: docker/build-push-action@v2
        with:
          # ...
          file: src/main/docker/Dockerfile
          context: ./build                      # path to build context

A: In my case, with Angular project, my project was in the folder called ex: My-Folder-Project and I was putting on Dockerfile COPY --from=publish app/dist/My-Folder-Project .
But of course the correct thing is put the "name" in your package.json like COPY --from=publish app/dist/name-in-package.json .

A: In my case I changed context, and path of Dockerfile within docker-compose.yml config:
services:
    server:
        # inheritance structru
        extends:
            file: ../../docker-compose.server.yml
        # I recommend you to play with this paths
        build:
            context: ../../
            dockerfile: ./apps/${APP_NAME}/Dockerfile
        ...


Q: Is it possible to create Realm class without default values for parameters? I understand that this is not possible with Kotlin because Realm needs an empty constructor.
However, this creates an issue that we may accidentally create a RealmObject without setting all the required fields. Hence, the purpose of required fields is lost.
I was wondering if someone has found a way around this Realm limitation.


Q: How to convert an audio file like mp3 to an mo3 file? I am trying to make a game and I need to convert an audio file like mp3, ogg or whatever to an mo3 file.

A: You can compress XM, S3M, IT and MOD files to MO3.
There is no way to convert MP3, WAV, OGG or FLAC to MO3, because the way of saving the audio is fundamentally different. It's like giving your computer a cd and asking it to write out the notes for all instruments, the lyrics and special effects.
Maybe this can help you, as somebody finds some hackings... http://www.un4seen.com/forum/?topic=1953.0


Q: How To Prevent Replication Failure If I become a MySQL DBA, will I had to deal all day with those kind of issues or do you have tips to prevent from breaking the whole replication?
I received this message because I removed manually the database, and after that the php script remove it.
Last_SQL_Errno: 1133`
Error 'Can't find any matching row in the user table' on query.`

A: I found this.
slave-skip-errors=1133


Q: how to convert the numeric into indian currency format in oracle sql suppose i have column money say its value is eg:880856.00 i need a query to format this money column like this 8,80,856.00

A: You can use to_char to format characters.
So, for the format you have specified
to_char(money, '9,99,999.99' );

Would return 8,80,856.00
example
It should be noted that this is simply the length of the string provided in the first answer, and a longer second argument can be provided to properly format the number as desired.
So:
to_char(11111111111111.11, '9,99,999,99,9,99,999.99')

Would return 1,11,111,11,1,11,111.11
extra length example
This will also automatically adjust for the number of digits provided in the first argument, for instance:
to_char(5856.00, '9,99,999.99');

Would return 5,856.00
example 2
From the Oracle docs:
https://www.oradev.com/oracle_number_format.jsp
Here's an old stackoverflow post on the topic: oracle sql query to format number by comma


Q: How can I create different captions for each image using StaggeredGridView? Under each image I would like the caption/card to say something different.
How can I achieve this?
I saw someone add ['url', "Some text"], in their String to have the text overlay the image but I can't find it now and I couldn't get it to work either.
This is what I've managed to do...
class Water extends StatefulWidget {
  const Water({Key key}) : super(key: key);

  @override
  _WaterState createState() => _WaterState();
}

class _WaterState extends State<Water> {

  List<String> imageList = [
        'https://i.pinimg.com/564x/bf/49/c6/bf49c6b37ab4be93bb77895ab777cee1.jpg',
        'https://i.pinimg.com/564x/4e/4e/72/4e4e72a411e829ee47dd3e3c96450b1a.jpg',
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
                child: Text(
              'Water',
              style: TextStyle(
                  fontSize: 30,
                  color: Colors.blue),
            )),
          ],
        ),
        AnimatedContainer(
          duration: Duration(milliseconds: 500),
          width: Profile.width,
          child: Expanded(
            child: Container(
              child: StaggeredGridView.countBuilder(
                shrinkWrap: true,
                primary: false,
                crossAxisCount: 2,
                crossAxisSpacing: 10,
                mainAxisSpacing: 12,
                itemCount: imageList.length,
                itemBuilder: (context, index) {
                  return Card(
                      color: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.zero,
                      ),
                      child: Column(
                        children: [
                          FadeInImage.memoryNetwork(
                              placeholder: kTransparentImage,
                              image: imageList[index],
                              fit: BoxFit.cover),
                          Text(
                            'Some Text',
                          ),
                        ],
                      ),
                  );
                },
                staggeredTileBuilder: (index) {
                  return StaggeredTile.fit(1);

A: define a model
class ImageItemModel{
  String imagePath;
  String title;
  ImageItemModel(this.imagePath, this.title)
  ///other things you want.
}

and use it like below
  List<ImageItemModel> list = [
       ImageItemModel("Url0","title0"),
       ImageItemModel("Url1","title1"),
       ImageItemModel("Url2","title2"),
  ];

and you can access each item like this
print(list[1].title) /// prints title1

so this part of your code will changes like this
  FadeInImage.memoryNetwork(
    placeholder: kTransparentImage,
    image: list[index].imagePath,
    fit: BoxFit.cover),
  Text(
    list[index].title,
   )


Q: Visual Studio Code exit button position Does someone know why the Exit button is on the left where's the Menu Bar? Someone know how to fix this?


Q: Identify last group in a LOOP AT ... GROUP BY? I'm looking for the equivalent of the AT LAST statement within the LOOP AT ... GROUP BY statement.
I'm looping using group by, and for performance reasons, I execute a call method every few groups, when a certain amount of records has been accumulated into an internal table. But I would like to add an extra condition to run this call at the end of the loop, if I'm in the last group.
Below I wrote a piece of executable code simulating my problem, I would like to process my last material before exiting the loop.
constants: processing_size_threshold type i value 10.
types: begin of ty_material,
         material_num type c length 3,
       end of ty_material.
data:  materials type standard table of ty_material,
       materials_bom type standard table of ty_material.

materials = value #( for i = 1 then i + 1 while i <= 3
                     ( material_num = conv #( i ) ) ).

loop at materials reference into data(material_grp) group by material_grp->material_num.

    loop at group material_grp reference into data(material).
      materials_bom = value #( base materials_bom (
                               lines of value #( for j = 1 then j + 1 while j <= 5
                                               ( material_num = |{ material->material_num }{ j }| ) ) ) ).
    endloop.

   "The 2nd condition of this IF is what I'm not able to figure out, I need material 3 BOM to be processed here
    if lines( materials_bom ) >= processing_size_threshold. "or group_num = last_group.
      "me->process_boms(materials_bom).
      clear materials_bom.
    endif.
endloop.

A: First: it is better to put real-world examples than just nonsensical tables filled with random numeric buzz like you did. You may just get the wrong answers that way.
If you want to process just the last group, you can use the GROUP INDEX for this:
SELECT matnr AS matno
  FROM vbap UP TO 100 ROWS
  INTO TABLE @DATA(materials)
  ORDER BY matnr.

TYPES: ty_mats LIKE materials.
DATA: bom LIKE materials.

DATA(uniques) = lines( VALUE ty_mats( FOR GROUPS value OF <line> IN materials GROUP BY ( matno = <line>-matno ) WITHOUT MEMBERS ( value ) ) ).
LOOP AT materials REFERENCE INTO DATA(refmat) GROUP BY ( id = refmat->matno size = GROUP SIZE gi = GROUP INDEX ) ASCENDING REFERENCE INTO DATA(group_ref).
  CHECK group_ref->*-gi = uniques.
  bom = VALUE ty_mats( BASE bom FOR <mat> IN GROUP group_ref ( matno = <mat>-matno ) ).
  me->process_boms( bom ). "<--here comes the drums
ENDLOOP.

Note: the table must be sorted for INDEX to show correct values.
In this snippet very simple approach is utilized: first we calculate the total number of unique groups and then check each group index whether it is the last one.
Note, that what is last in your dataset depends only on sort order, so you may easily end up with the inaccurate values for your requirement.

A: did you mean this ?
sy-tabix current loop index may help here.
Otherwise You may need to calculate the number of groups prior.
constants: processing_size_threshold type i value 10.
types: begin of ty_material,
         material_num type c length 3,
       end of ty_material.
data:  materials type standard table of ty_material,
       materials_bom type standard table of ty_material.

materials = value #( for i = 1 then i + 1 while i <= 3
                     ( material_num = conv #( i ) ) ).

loop at materials reference into data(material_grp) group by material_grp->material_num.

    loop at group material_grp reference into data(material).
      materials_bom = value #( base materials_bom (
                               lines of value #( for j = 1 then j + 1 while j <= 5
                                               ( material_num = |{ material->material_num }{ j }| ) ) ) ).
    endloop.

   "The 2nd condition of this IF is what I'm not able to figure out, I need material 3 BOM to be processed here
    if lines( materials_bom ) >= processing_size_threshold
    or lines( materials ) = sy-tabix.
      "me->process_boms(materials_bom).
      clear materials_bom.
    endif.
endloop.


Q: Comma Operator with indexing 2D arrays I have this algorithm that is pseudocode for the dijkstra algorithm for graph theory. The first thing that goes on is a basic for loop.
visitedSet[0] = true //visitedSet is a array of bools
for (int i = 1; i <= numberNodes; ++i)
{
    distanceArray[i] = adjacencyMatrix[0,i];
    //distanceArray is 1D with size of fifty
    //adjacencyMatrix is 2D with size of fifty
    //Both arrays hold values of unsigned ints
}

Here are the array definitions
enum GraphLimit300 {MAX_NODES = 50};
unsigned int adjacencyMatrix[MAX_NODES][MAX_NODES];
unsigned int distanceArray[MAX_NODES];

Visual studio is giving me an array saying that I can't assign an array of unsigned integers to a pointer. I have looked up online that with the comma operator basically in this case throws out the first case, 0, and treats it as distanceArray[i] = adjacencyMatrix[i]; Which doesn't make sense to me since adjacenyMatrix is a 2D array. I am just wondering what is giving me this compile error and get more information on why, because I basically just copying in variable names where the pseudo code basically says to.
Pseudo code:
    S = { 1 }
for ( index = 2; index <= N; ++ index )
    D[ index ] = C[ 1, index ]
for ( index = 1; index <= N – 1; ++ index )
    Choose a vertex v in V – S such that D[ v ] is a minimum
    Add v to S
    for each vertex w in V – S do
        D[ w ] = min( D[ w ], D[ v ] + C[ v, w ] )

The above pseudo code uses lists to represent their arrays they for some reason start at 1 so I modified it to start at 0 in my code.

A: You have to review how to access elements of 2D array. Also, take look at what comma operator does. You have to use [] twice:
adjacencyMatrix[0][i]

The following:
adjacencyMatrix[0, i]

is equivalent to:
adjacencyMatrix[i]

Which will still leave you with 1D array. And, as the error message says:
   distanceArray[i] = adjacencyMatrix[i];
// ^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^
//   unsigned int   array of unsigned ints

You can not possibly expect this assignment to happen.


Q: Need help in finding exception "javax.xml.bind.UnmarshalException - with linked exception:" I tried to store a resume in an online CRM on trying to save that i got the following exception

javax.xml.bind.UnmarshalException
   - with linked exception: [javax.xml.stream.XMLStreamException:
  ParseError at [row,col]:[73,12]
  Message: Character reference "&#x18"
  is an invalid XML character.]

i can store the resumes using the apis which they have exposed .The Resume which i am sending is in simple text format

A: &#x18 is a representation of the character with hex value 18, and this is not a character permitted by the XML specification (it's an ASCII control code of some form). JAXB is quite rightly refusing to parse it.
You need to find out what is writing that data in the first place, and fix it, because it's not writing valid XML.

A: &#x18 appears to be the CANCEL character . Is there some way the keyboard signal to stop the program could be ended up being read in to the input on resumption?


Q: How to generate n random numbers with a sum of m in public static void main (scanner)? I'm trying to generate 4 different numbers for the second else if statement (life_1.equals(a) and another random integer for the third else if statement (life_1.equals(c) without changing the public static void main for myscanner. Thanks for answering and sorry if my question doesnt make any sense at all :/
System.out.println("Do you want to use a lifeline now? (y - yes or n - no)");
answer =myScanner.nextLine();

boolean life=false;

if (answer.equals("y")) {
do {

    System.out.println("Alright. Which one of your lifelines would you like to use?( f-fifty-fifty  , a-ask the audience, c-call a friend)");
    life_1= myScanner.nextLine();
    if (life_1.equals("f") && lifeline_5050 !=0){
      System.out.println(" The answer is not b or d");
      lifeline_5050 = lifeline_5050 - 1;

    life=true;
    }
    else if (life_1.equals("a") && lifeline_ask != 0) {
      System.out.println("The audeince say the answers are: a."+randomNum1+ "b. "+randomNum2+"c. "+randomNum3+ "d. "+randomNum4 );
      lifeline_ask= lifeline_ask -1 ;
     life=true;
    }
    else if (life_1.equals("c") && lifeline_call !=0 ){

      System.out.println("Your friend says the answer a is "+RandomNum+" possible.");
      lifeline_call = lifeline_call -1;
      life=true;}
    else {
      System.out.println("Invalid answer. You can't use this lifeline."); }
    }     while (life==false);
}

A: To generate n numbers whose sum is m, you can think permutation of m o and n - 1 |, then count o between | and the number of o will be the numbers generated.
For example, given that m = 10 and n = 4, the permutation may be
o|oooo|ooo|oo

Then, the results are 1, 4, 3, 2.
To generate this permutation, you should do shuffle.
You only have to consider position of |, so the implementation may be like this:
int[] generateNumbers(int m, int n) {
    if(m < 0 || n <= 0) throw new IllegalArgumentException();
    if (n == 1) return new int[]{m};
    int separatorNum = n - 1;
    int permutationLength = m + n - 1;
    int[] positions = new int[separatorNum];
    int[] result = new int[n];
    // shuffle array of o and |
    for (int i = 0; i < separatorNum; i++) {
        int p = (int)(Math.random() * (permutationLength - i)) + i;
        if (p >= separatorNum) {
            // o will be swapped with | if the number was not swapped to | before
            boolean dupe = false;
            for (int j = 0; j < i; j++) {
                if (positions[j] == p) {
                    dupe = true;
                    break;
                }
            }
            positions[i] = (dupe ? i : p);
        } else {
            // another | will be swapped with |, so | will be here
            positions[i] =i;
        }
    }
    // sort the positions
    for (int i = positions.length - 1; i > 0; i--) {
        for (int j = 0; j < i; j++) {
            if (positions[j] > positions[j + 1]) {
                int temp = positions[j];
                positions[j] = positions[j + 1];
                positions[j + 1] = temp;
            }
        }
    }
    // decode the positions
    result[0] = positions[0];
    for (int i = 1; i < n - 1; i++) {
        result[i] = positions[i] - positions[i - 1] - 1;
    }
    result[n - 1] = permutationLength - positions[n - 2] - 1;
    return result;
}