text:
Q: Create multiple DMN using Java Camunda Springboot starter I would like to create a Java service that would build a Camunda DMN via code. I'm using camunda-springboot-starter dependency and I'm able to generate the DMN DecisionTable and output of one decision is used in another. I'm using InformationRequirement for same but when I write the model to file and open that file in modeler the arrow is not coming for information requirement and after deploying the decision is not able to get that output.
<
public String generateDMN(String name, String title) throws FileNotFoundException {
    DmnModelInstance modelInstance = initializeEmptyDmnModel();

    Decision decision = modelInstance.newInstance(Decision.class);
    decision.setId(title);
    decision.setName(name);
    modelInstance.getDefinitions().addChildElement(decision);

    List<String[]> rules = new ArrayList<>();
    try (CSVReader reader = new CSVReader(new FileReader("/Users/rahulnehete/IdeaProjects/java-rules-engine/src/main/resources/file.csv"))) {
        rules = reader.readAll();
    } catch (Exception e) {
        log.error("Error reading CSV file ", e);
    }

    DecisionTable decisionTable = modelInstance.newInstance(DecisionTable.class);
    decisionTable.setId("DecisionTable_"+name+"_"+title);
    decisionTable.setHitPolicy(HitPolicy.COLLECT);
    decision.addChildElement(decisionTable);

    Decision decision2 = modelInstance.newInstance(Decision.class);
    decision2.setId(title + "_2");
    decision2.setName(name + "_2");
    modelInstance.getDefinitions().addChildElement(decision2);

    DecisionTable decisionTable2 = modelInstance.newInstance(DecisionTable.class);
    decisionTable2.setId("DecisionTable_"+name+"_"+title+"_2");
    decisionTable2.setHitPolicy(HitPolicy.COLLECT);
    decision2.addChildElement(decisionTable2);

    InformationRequirement infoRequirement = modelInstance.newInstance(InformationRequirement.class, "info1");
    decision2.getInformationRequirements().add(infoRequirement);
    infoRequirement.setRequiredDecision(decision);

    String[] header = rules.remove(0);
    String[] varTypes = rules.remove(0);
    String[] variables = rules.remove(0);

    Long numOfInputs = Arrays.stream(header).filter(k -> k.equalsIgnoreCase("input")).count();
    Long numOfOutputs = Arrays.stream(header).filter(k -> k.equalsIgnoreCase("output")).count();
    for(int i=0; i<numOfInputs; i++) {
        Input ip = generateElement(modelInstance, Input.class, "Input_"+i);
        InputExpression inputExpression = generateElement(modelInstance, InputExpression.class);
        Text text = modelInstance.newInstance(Text.class);
        inputExpression.setText(text);
        inputExpression.setTypeRef(varTypes[i]);
        ip.setLabel("Input " + i);
        ip.setCamundaInputVariable(variables[i]);
        ip.setInputExpression(inputExpression);
        decisionTable.addChildElement(ip);
    }
    for(int i=numOfInputs.intValue(); i<=numOfOutputs; i++) {
        Output op = generateElement(modelInstance, Output.class, "Output_"+i);
        op.setLabel("Output " + i);
        op.setName(variables[i]);
        op.setTypeRef(varTypes[i]);
        decisionTable.addChildElement(op);
    }

    for(int i = 1; i<rules.size(); i++) {
        String[] rule = rules.get(i);
        Rule dmnRule = createRule(modelInstance, numOfInputs.intValue(), numOfOutputs.intValue(), rule);
        decisionTable.addChildElement(dmnRule);
        log.info("Rule {} added", i);
    }

    Input ip = generateElement(modelInstance, Input.class, "Input_A");
    InputExpression inputExpression = generateElement(modelInstance, InputExpression.class);
    Text text = modelInstance.newInstance(Text.class);
    inputExpression.setText(text);
    inputExpression.setTypeRef("string");
    ip.setLabel("Input A");
    ip.setCamundaInputVariable("minPlafond");
    ip.setInputExpression(inputExpression);
    decisionTable2.addChildElement(ip);

    Output op = generateElement(modelInstance, Output.class, "Output_A");
    op.setLabel("Output A");
    op.setName("FinalOutput");
    op.setTypeRef("string");
    decisionTable2.addChildElement(op);

    // TODO: variable names
    String[] rule = new String[] {"-", "$(minPlafond + " + "\"_Success\")"};
    Rule dmnRule = createRule(modelInstance, 1, 1, rule);
    decisionTable2.addChildElement(dmnRule);
    log.info("Rule {} added", "new");

    Dmn.validateModel(modelInstance);
    try {
        FileOutputStream fos = null;
        fos = new FileOutputStream(name + "_" + title + ".dmn");
        Dmn.writeModelToStream(fos, modelInstance);
        fos.close();
    } catch (IOException e) {
        log.error("Error writing model instance ", e);
        return REConstants.FAILED;
    }
    return "DMN GENERATED";
}

private DmnModelInstance initializeEmptyDmnModel() {
    DmnModelInstance dmnModel = Dmn.createEmptyModel();
    Definitions definitions = generateNamedElement(dmnModel, Definitions.class, "definitions", "definitions");
    definitions.setNamespace(DmnModelConstants.CAMUNDA_NS);
    dmnModel.setDefinitions(definitions);
    return dmnModel;
}

private <E extends DmnElement> E generateElement(DmnModelInstance modelInstance, Class<E> elementClass, String id) {
    E element = modelInstance.newInstance(elementClass);
    element.setId(id);
    return element;
}
private <E extends NamedElement> E generateNamedElement(DmnModelInstance modelInstance, Class<E> elementClass, String name, String id) {
    E element = generateElement(modelInstance, elementClass, id);
    element.setName(name);
    return element;
}
private <E extends DmnElement> E generateElement(DmnModelInstance modelInstance, Class<E> elementClass) {
    String generatedId = elementClass.getSimpleName() + UUID.randomUUID();
    return generateElement(modelInstance, elementClass, generatedId);
}

private Rule createRule(DmnModelInstance dmnModelInstance, int numberOfInputs, int numberOfOutputs, String[] ruleInput) {
    Rule rule = dmnModelInstance.newInstance(Rule.class);
    for(int i=0; i<numberOfOutputs; i++) {
        OutputEntry outputEntry = createOutputEntry(dmnModelInstance, ruleInput[numberOfInputs + i]);
        rule.getOutputEntries().add(outputEntry);
    }
    for (int i = 0; i < numberOfInputs; i++) {
        InputEntry inputEntry = createInputEntry(dmnModelInstance, ruleInput[i]);
        rule.getInputEntries().add(inputEntry);
    }
    return rule;
}

private InputEntry createInputEntry(DmnModelInstance dmnModelInstance, String expression) {
    Text text = dmnModelInstance.newInstance(Text.class);
    text.setTextContent(expression);
    InputEntry inputEntry = dmnModelInstance.newInstance(InputEntry.class);
    inputEntry.setText(text);
    return inputEntry;
}

private OutputEntry createOutputEntry(DmnModelInstance dmnModelInstance, String expression) {
    Text text = dmnModelInstance.newInstance(Text.class);
    text.setTextContent(expression);
    OutputEntry outputEntry = dmnModelInstance.newInstance(OutputEntry.class);
    outputEntry.setText(text);
    return outputEntry;
}

}

A: You implemented the decisions, decisions table, input and output as well as info requirement correctly on model level (xmlns="https://www.omg.org/spec/DMN/20191111/MODEL/"). (Dmn.writeModelToFile(new File("src/main/resources/my.dmn"), modelInstance); is little more compact than writing the stream yourself.)
When you compare to a model created by the Modeler, you see that it uses additional namespaces such as xmlns:dmndi="https://www.omg.org/spec/DMN/20191111/DMNDI/". This namespaces defines the diagram information separately from the model, e.g:
  <dmndi:DMNDI>
    <dmndi:DMNDiagram id="DMNDiagram_12sfwjw">
      <dmndi:DMNShape id="DMNShape_1m8k4eq" dmnElementRef="Decision1">
        <dc:Bounds height="80" width="180" x="150" y="80" />
      </dmndi:DMNShape>
      <dmndi:DMNShape id="DMNShape_15h0omx" dmnElementRef="Decision2">
        <dc:Bounds height="80" width="180" x="240" y="200" />
      </dmndi:DMNShape>
      <dmndi:DMNEdge id="DMNEdge_15fnvnh" dmnElementRef="InformationRequirement_0a97hay">
        <di:waypoint x="330" y="200" />
        <di:waypoint x="240" y="180" />
        <di:waypoint x="240" y="160" />
      </dmndi:DMNEdge>
    </dmndi:DMNDiagram>
  </dmndi:DMNDI>

Unfortunately, the Camunda API currently offers no way of auto-generating or creating this diagram information.You would have to approach this a level lower with an XML library.
The model is executable without the diagram information. So, you will have a working model. Maybe that is acceptable and only if a human cares about the DRD it can be created manually?
An alternative would be to abandon the Java approach and try https://bpmn.io/toolkit/dmn-js/.


text:
Q: How to structure teams, projects and specialties in JIRA We have a department team section in JIRA setup as a project and I have been asked to create Kanban boards and set the section up ready to use but I'm not sure the best way to apply the work the department team is managing into JIRA.
We want to have Kanban boards for two different specialties and for e.g. one of the specialties we have two projects and one of the projects has a subproject and also one of the projects may sometimes overlap with both specialties.
For example:
Build team
    Development Kanban Board
        Project A
            Project Sub Project/Stream A
            Project Sub Project/Stream B
        Project B
    Test Kanban Board
        Project A

My current thoughts are:

*

*Project = Team

*Component = Project A

*Epic = Project Sub
Project/Stream

*Labels = Specialty Kanban Board

Is the above correct or is there another approach that would be best practice for this scenario?  At the moment I think we are tied into having the Project in JIRA set as the team

A: Usual practice is to make your projects correspond to JIRA projects (thus the name). You can set up the filters for Kanban boards to bring in issues from multiple projects according to whatever criteria you want. This will make it easier if issues need to flow from the dev team to the test team. The "Team" can be defined by assignee, status, or another field if you prefer. Epics are good for time-bounded subprojects, components are good for ongoing subelements (e.g. UI, database, etc.).

redpajama_set_name: RedPajamaStackExchange


text:
Q: '(String) -> String' is not convertible to 'SQLHandler' The line below, at SQLHandler.translateQuery("Do mysql stuff"), is throwing the error: '(String) -> String' is not convertible to 'SQLHandler'. Why is it doing this? Thank you in advance.
Code 1 (Used wherever and whenever needed)
var query: String = "mysql stuff"
SQLHandler.sendQuery(SQLHandler.translateQuery("domain and \(query)"))

Code 2, SQLHandler.swift (Called whenever needed)
import Foundation

class SQLHandler {

func translateQuery(queryToTranslate: String) -> String{
    println(queryToTranslate)
    return queryToTranslate.stringByReplacingOccurrencesOfString(" ", withString: "_", options: NSStringCompareOptions.LiteralSearch, range: nil)
}

func sendQuery(query: String){
    println(query)
    let url = NSURL(string: "url and query goes here")

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in })
    task.resume()

}
}

A: You are calling an instance method on the class itself.
Either create an instance and call the method:
var sqlHandler = SQLHandler()
sqlHandler.translateQuery("domain and \(query)")

or define the methods as class methods :
class func translateQuery(queryToTranslate: String) -> String ...
class func sendQuery(query: String) ...


text:
Q: Abbreviate states in Geocomplete Is there a way to abbreviate the states in geocomplete?
I am currently using the data-geocode administrative_area_level_1 to show the sate but need it to be abbreviated - not the full name.

A: You just add short to short to the end of the administrative_area_level_1 as follows:
    <label>State</label>
    <input name="administrative_area_level_1_short" type="text" value="">

I tried it for Colorado and it gave CO. I think this is what you wanted. All the best.


text:
Q: Angular 6/7 circular dependency between libraries I'm working on a project that's using Angular 7 and I have various angular libraries for the respective modules of the application that I build then publish on (a private) npm to be used by the application. So all angular libraries are imported in the app through their npm package.
The problem I'm facing is that I now have 2 modules that import each other because they need to show a component from the other module. I cannot move said components elsewhere because they depend on services and other components in their own module.
To try and make it a little bit clearer I will give you an example of my situation.
I already have a SharedModule with some independent components that are used in other modules, then I also have a module for each API service. So I have a UsersModule, 'AdministrationModule' and such. My problem is with PlantModule and FleetModule.

*

*Plant as in power plant

*Fleet as in a group of plants and/or other
fleets, but also has own properties

PlantModule has a component for the list of plants (as in power plants not organic plants) and a component for the details of the plant. In the detail component there are also other external components that show for example all users assigned to it as well as the fleets.
FleetsModule also has a component for the list of fleets and one for the details. In this detail component there are also external components like the users assigned, a list of sub-fleets and a list of plants that are part of the fleet.
What I'm trying to do is to have reusable components to be used in other modules so that I don't need to copy-paste all the API services, components and such everywhere.
Any ideas on what I'm doing wrong or how to solve it?
UPDATE
In order to solve it I changed the structure of the "pages" where those components are needed. So instead of importing the reusable components inside other components in the libraries I create a wrapper view in the main app and import all I need.

A: So you have three modules, DeskModule, UsersModule, and OfficeSuppliesModule.
The DeskModule imports UsersModule and OfficeSuppliesModule as it has two show their components in a Component of this module.
And the problem is that in OfficeSuppliesModule you have a component from the DeskModule to show which desk it belongs to.
I didn't quite get as to why do you have a component just to show that? Instead of a component, you could have leveraged a service that you could use in the CoreModule. From this service, you could expose a method to tell the template of the component in the OfficeSuppliesModule which desk those office supplies belong to. Since there wouldn't be a Component that needs to be re-used, you wouldn't face this issue.
Another thing you can do is to move the component that you're using both in your DeskModule and your OfficeSuppliesModule to the SharedModule and then add the SharedModule to the imports array of both the DeskModule and the OfficeSuppliesModule
UPDATE
Since Angular 6, you can add providedIn: 'root' to the @Injectable decorator instead of adding the service name to the providers array of the module. That way, the service is registered to the root injector and is available throughtout the App.
So you can change all those services you'd want in the multiple modules by adding providedIn: 'root' to the @Injectable decorator of those services:
@Injectable({
  providedIn: 'root'
})

And then as suggested above this update, move the components used in the PlantModule and the FleetsModule to the SharedModule.


text:
Q: Spring MVC + Hibernate: Partial model update from browser When only displaying a part of a Spring MVC model bean, is there a way to only update in the model what comes back from the browser?
Let's say we have a User class (public properties only in this example, of course):
public class User {
  public String firstName;
  public String lastName;
  public String email;
  public Date subscriptionExpiration;
}

Now I display the first three properties as input fields in a JSP and want to update the object in the database accordingly. Only these 3 parameters should be updated, NOT the fourth one. One way to accomplish this would be
@RequestMapping("/user/{userId}", method=RequestMethod.POST)
public String saveChanges(@PathVariable userId, User user, Model model) {
  User oldUser = User.loadFromDB(userId);
  oldUser.firstName = user.firstName;
  oldUser.lastName = user.lastName;
  oldUser.email = user.email;
  oldUser.saveToDB();

  model.addAttribute("user", oldUser);
}

but this would mean hardcoding all properties that could change, which I don't like too much.
Is there any way to determine what fields to update based on what the user was allowed to change? That mechanism should be smarter than just assuming that everything that's in the request parameters may be changed, otherwise any savvy user could manually inject additional fields into a request.
Using @Entity(dynamicUpdate=true) does not solve the problem either in my eyes, as I'm not getting the whole User object back in the request, and doing so would open up many security holes.
Am I missing a nice feature in Spring or is there any other way to conceptually solve for this problem? Any hints are greatly appreciated!

A: See this question to know how to use @InitBinder to allow/prevent some model fields to be bound by Spring to request parameters. This allows making sure that the subscriptionExpiration can't be modified by injecting a request parameter.
And see the documentation for how to use the @ModelAttribute annotation on methods and on method arguments to load a user from the database and add it to the model before the @RequestMapping method is called, and to populate this user with request parameters when the @RequestMapping method is called. This allows getting a user from the DB and have Spring populate it with ne values coming from the request. All you have to do is validate the new state of the user and save it to the database.

A: I think the method
BeanUtils.copyProperties(Object source, Object target, String[] ignoreProperties)

does what you want. It copies all properties from one object to another without touching the properties defined in String[] ignoreProperties.

Copy the property values of the given source bean into the given target bean, ignoring the given "ignoreProperties".
Note: The source and target classes do not have to match or even be derived from each other, as long as the properties match. Any bean properties that the source bean exposes but the target bean does not will silently be ignored.
This is just a convenience method. For more complex transfer needs, consider using a full BeanWrapper.

API Documentation

A: You can read the object from the database first and bind then the request. You can find an example at FuWeSta-Sample.
It uses a helper-bean which must be initialized by Spring.

A: one option is to make use of hidden fields in your form. an option with draw backs but it works for some cases

A: The nice feature you are looking for is @ModelAttribute. I assume that your form will also post the user id.
public class UserController {

    @ModelAttribute
    public User getUser(@RequestParam(value = "id", required = false) Long id) {
        return User.loadFromDB(id);
    }

    @RequestMapping("/user/{id}", method=RequestMethod.POST)
    public String saveChanges(@ModelAttribute User user, BindingResult bindingResult, Model model) {

        if (bindingResult.hasErrors()) {
            // return ...
        }

        //  model.asMap().clear();

        user.saveToDB();
        // return ...
    }
}

A: I have the same issue and finally resolve it by just adding a Type Converter.
public class AbstractDocumentConverter implements Converter<String, AbstractDocument> {

    private AbstractDocumentRepository abstractDocumentRepository;

    public AbstractDocumentConverter(AbstractDocumentRepository abstractDocumentRepository) {
        this.abstractDocumentRepository = abstractDocumentRepository;
    }

    @Override
    public AbstractDocument convert(String id) {
        return abstractDocumentRepository.findOne(id);
    }
}

I use mongodb,  AbstractDocument is the super class for all my Documents, in the controller I add @ModelAttribute("id") .
@RequestMapping("save")
public String save(@ModelAttribute("id") SportGame game) {
    sportGameService.save(game);
    return "redirect:/game/list";
}

It will first convert id to model(In my converter it find one from db by id), and then fill model fields from the request parameters.


text:
Q: How can I swap two elements in one array? I have an array like :
a=np.array([2,7])

a=[2,7]

and I want to swap the same array like 7,2 is there anyway to do?
answer should be like 7,2
a=[7,2]

A: Try np.flip(a,0) See this for more information.

A: #a=np.array([2,7])
a=[2,7]

# Reversing a list using slice notation
print (a[::-1]) # [7, 2]

# The reversed() method
print (list(reversed(a))) # [7, 2]

swap two elements in a list:
# Swap function
def swapPositions(list, pos1, pos2):
    list[pos1], list[pos2] = list[pos2], list[pos1]
    return list

a=[2,7]
pos1, pos2 = 0, 1

print(swapPositions(a, pos1 - 1, pos2 - 1))


text:
Q: exception in input in python When running the following code:
try:
   key=int(input())
except ValueError as string:
   print("Error is within:",string)

for example, if one puts 'rrr' this exception will rise, since 'rrr' does not support (int)
However, instead ot putting the actual string, it puts: "invalid literal for int() with base 10: 'rrr' "
How do I make it work so that the variable 'string' actually gets the wrong input that the user gave (in this example, I want it to print: 'Error is within: rrr')
Thanks a lot

A: Store the input and convert it to an int separately.
key_str = input()
try:
    key = int(key_str)
except ValueError:
    print("Error is within:", key_str)

A: Your issue comes from the fact that the variable string is the error message for a ValueError exception. If you wanted to print out the user's invalid input, you would need to create a variable that stores the user's input before your try/except. For example:
userInput = input()
try:
   key=int(userInput)
except ValueError:
   print("Error is within:",userInput)

A: You can just parse the error msg :D
print("Error is within:", string.args[0][41:-1])


text:
Q: Java ScheduledExecutorService standard practice I am using ScheduledExecutorService in a J2EE application to schedule a task every x seconds taken from a config file (picks up data from a database and sends them to a external server).  My code is:
try{
    final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleWithFixedDelay(new Runnable(){
    public void run(){
                RsaBaseAction rsa = RsaBaseAction.getInstance();//class that does all the work
                rsa.rsaBaseAction();
            }
          }, 0, timeInterval, TimeUnit.SECONDS);
     }
     catch(Exception ex){
         ex.printStackTrace();
     }

My question is is there any extra code I should be writing?  Should I write a while loop to make sure thread is completed then do a service.shutdown() or does ScheduledExecutorService take care of that for me?

A: You would call shutdown if you wanted the scheduler to stop scheduling the events. You don't need to explicitly do this as if you want it to run for the lifetime of your application. You would use the shutdown method if for some reason the scheduling no longer made any sense.
An example. You're writing a CMS that offers integration with google shopping to upload product information. If the user removes their upload information (ie turned it off), you could call shutdown to stop the service doing the synchronization.

A: As the Javadoc on the shutdown method clearly states:

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.
  This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

I.e. previous tasks are going to be finished, no new ones are going to be done, however a previous task may continue past the shutdown command if it takes a while.
As for the code you have - I do not see any reason for the try-catch block. Scheduling tasks does not throw any exceptions. It looks like you want to actually try-catch the rsaBaseAction instead of the scheduling (if an exception is thrown by the runnable, no more executions are scheduled and the exception is handled by the thread group exception handler)


text:
Q: Can't get nested key from env to override yaml config file using viper This is my simplified config:
stripe:
  secret_key: sk_fromconfig

Why viper don't take value from env?
% echo $STRIPE_SECRET_KEY
sk_fromenv
% go run main.go
sk_fromconfig

I expect it takes value from env because I have one like this:
% echo $STRIPE_SECRET_KEY
sk_fromenv
% go run main.go
sk_fromenv

Here is the code:
package main

import (
    "fmt"

    viper "github.com/spf13/viper"
)

type Config struct {
    Stripe Stripe
}

type Stripe struct {
    SecretKey string `mapstructure:"secret_key"`
}

func main() {
    viper.SetConfigName("config")
    viper.SetConfigType("yaml")
    viper.AddConfigPath(".")

    viper.AutomaticEnv()
    _ = viper.ReadInConfig()

    var config Config
    _ = viper.Unmarshal(&config)

    fmt.Println(config.Stripe.SecretKey)
}

I tried viper.BindEnv("STRIPE_SECRET_KEY") and viper.SetEnvPrefix("STRIPE") but didn't work.

A: Use viper.SetEnvKeyReplacer, because it wasn't automatically replaced from . to _
viper.SetEnvKeyReplacer(strings.NewReplacer(`.`,`_`))

so it was looking for environment variable STRIPE.SECRET_KEY but since most shell doesn't allow dot in the environment variable name, we have to replace it with underscore.


text:
Q: testdisk - partition : write error Today I bought a SATA-to-usb convertor to copy my data from old hard drive that had been abandoned for few months. When I connected to PC, the partition didn't show up so I decided to fix the partitions. I was trying to recover the damaged parition from my WD hard disk drive using testdisk. I can see my 3 paritions when I 'Analyse' but when I Write those paritions it returns error:
Parition: Write Error.
I tried both Linux and Windows, both show same error. Now how do I sort this out , if not then is there another way to fix my partition tables?
   interface_write()
 1 * HPFS - NTFS              0   4  5  7230  82 20  116154880 [STR1]
 2 P HPFS - NTFS           7230  90 29 15120 113 33  126754304 [Local Disk]
 3 P Linux                15120 113 34 15200  30 62    1280000 [_Fedora-16-i686-]
write!

write_mbr_i386: starting...
write_all_log_i386: starting...
No extended partition

Partition: Write error


text:
Q: Is it possible to get a list of users in a Youtube Live Stream I am using youtube data api.
But I have not found anywhere to fetch the list of users who participated in youtube liveStream.
I know how to get the number of viewers :
Is it possible to get a list of users in a Youtube Gaming Live Stream
I want to get a list of participating users, not Number of participants.
Is there a way?


text:
Q: How to get string representation of cassandra timestamp column? I'm querying a timestamp column from datastax php diver for cassandra
select name , x_date from table;

The result is returned in json format
name: "name"
x_date: {type: {name: "timestamp"}, seconds: 1561645740, microseconds: 0}

I want to get simple string representation of date formatted like YYYY-mm-dd as it appears on cql client not json.
I've tried TODATE function but same result is returned.

A: After some search i found that class Cassandra\Timestamp included in datastax driver for php has a function toDateTime() that convert the json into php datetime format
 $datetime = x_date->toDateTime();

then i used format() to get my date formatted
 $myPhpDate = $datetime->format('d/m/Y H:i:s');


text:
Q: Firebase Null object Reference When running updateList(), it works as it loads up the already-entered data from Firebase. This is a chat app so when someone types a message, Firebase updates in real time, which works as well.
The problem is I get a NullPointerException (Which shouldn't be the case) where I create a new Message object (Message mess = new Mess....). Why am I receiving this error and why is everything I tried not working?
Error = java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference.
I tried a lock, a boolean, and tried making the variables global variables.
public void sendButtonClicked(View view) {

    final String messageValue = userMessage.getText().toString().trim();
    final String date = "4:20";
    final String userName = "Rob";
        if (!TextUtils.isEmpty(messageValue)) {
            final DatabaseReference newPost = reference.push();
            newPost.child("Content").setValue(messageValue);
            newPost.child("Date").setValue(date);
            newPost.child("userName").setValue(userName);
        }
    }

private void updateList() {
    reference.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Message mess = new Message(dataSnapshot.child("Content").getValue().toString(), dataSnapshot.child("Date").getValue().toString(),dataSnapshot.child("userName").getValue().toString());
            result.add(mess);
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            Message message = dataSnapshot.getValue(Message.class);

            int index = getItemIndex(message);

            result.set(index, message);
            adapter.notifyItemChanged(index);
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            Message message = dataSnapshot.getValue(Message.class);

            int index = getItemIndex(message);

            result.remove(index);
            adapter.notifyItemRemoved(index);
        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

Snapshot of how the data looks in Firebase
FireBase Screesnhot

A: I think I was running into a similar issue and this response from Frank helped me: https://groups.google.com/forum/#!topic/firebase-talk/-cdTDFBOmMw.
When you are creating the new record within Firebase, it looks like you are doing setValue() individually for each property:

          newPost.child("Content").setValue(messageValue);
          newPost.child("Date").setValue(date);
          newPost.child("userName").setValue(userName);

So what is happening is the value for Date might be set which immediately triggers onChildAdded, but content is still missing. Try instead to set them as a single message object.


text:
Q: add class to navbar li tag

#nav a:after {
    -webkit-transition: 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    transition: 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
    position: absolute;
    z-index: 1;
    content: "";
    left: 50%;
    right: 50%;
    height: 3px;
    bottom: 13px;
    background-color: #24252f;
}

HOME

PRODUCTS

ABOUT

PARTNERSHIPS

*This is my code, here i have navbar and i have to active li when user go on perticular page. My problem is i seprated the header(navbar) so how can i add or remove active classes to li *

A: Try this:
It will add 'active' class to the clicked element.
You can provide any styling you want in the active class.
You can check the DOM for clarity
HTML:

HOME

PRODUCTS

ABOUT

PARTNERSHIPS

Script:
$('#nav').on('click','ul > li',function(){
$('li').removeClass('active');
$(this).closest('li').addClass('active');
})

CSS
.active {
// Add styles
}

Codepen

A: you better add a class called active to a li tag also write some css to .active class and make use of it to whichever li you need to have for the pages respectively.

A: Considering you will include your nav div in index.html for every menu and index.html is separate for every menu, you can do the following :
1) give ids to your each li like

HOME

PRODUCTS

ABOUT

2) and on each index.html add the following script

A: You could just try putting the .active when you're in that particular page, like if you're in the home page:

HOME

PRODUCTS

ABOUT

PARTNERSHIPS

Then if you're in the products:

HOME

PRODUCTS

ABOUT

PARTNERSHIPS


text:
Q: Django DEBUG mode to only apply for a set of whitelisted IPs I have some strange bug that seems to only occur on my production environment, not even on staging.
The limited trace that django emails is insufficient for effectively debugging (no local vars etc) but I can't set the entire production server to DEBUG=True since any accidental arrival by a visitor to an error page would expose much sensitive data.
Is there any elegant way in which I could whitelist a few IPs of my team and only for requests arriving from these IPs django will behave as if DEBUG is True?

A: The one option is to "runserver" at the same environment your production works
The other option is to use sentry which besides a lot of cool stuff provides local vars for exceptions


text:
Q: CreateFile() Error in console (powershell and CMD) after Anaconda installed After Anaconda installed, there are some error messages always displayed in my console, including CMD and PowerShell.
these error messages would be disappeared after Anaconda removed.
who encounters the same issue and know how to resolve it?
thanks very much!
Environment:

*

*Windows 10 64bits v1903

*Anaconda3-2019.10-Windows-x86_64

*or Anaconda3-2019.10-Windows-x86

The error message when PowerShell started
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

CreateFile() Error: 5
CreateFile() Error: 5
PS C:\windows\system32> CreateFile() Error: 5
CreateFile() Error: 5

The error message when debugging python file with python interpreter installed by Anaconda
Microsoft Windows [Version 10.0.18362.175]
(c) 2019 Microsoft Corporation. All rights reserved.

c:\xm\github\python-study>C:/ProgramData/Anaconda3/Scripts/activate
CreateFile() Error: 5
CreateFile() Error: 5
CreateFile() Error: 5
CreateFile() Error: 5
CreateFile() Error: 5
CreateFile() Error: 5
CreateFile() Error: 5
CreateFile() Error: 5


text:
Q: Need to combine all csv data into single file of nested folder using batch script I need to combine all csv files data into single csv file using batch script
the folder structure is as follows
C:\Users\username\Desktop\DLog\Export\20200727\AL-Comp_Outbound\20200726\ (multiple csv's present here)
So under "Export" there are multiple folders like "20200727...20200678" and in those folders the common sub folder name is  AL-Comp_Outbound which further has a sub folder  "20200728...20200728" that contain csv files.
I need to find the folder with name AL-Comp_Outbound navigate to it and then parse through all the sub folders that has csv files and combine it together.
i tried to do but it with below query but it search for all the folders present in the directory, I need only need csv files from all folders having common name as "AL-Comp_Outbound". Also need to remove repetition header
@echo off

SETLOCAL ENABLEDELAYEDEXPANSION
PUSHD "%~dp0"

SET "SUMMARY_FILE=sumfile.csv"
DEL /F "%SUMMARY_FILE%" 2>nul

SET "LINE_COUNT=1"

FOR /F "usebackq delims=" %%p IN (`dir c:\ /s /b /ad ^| find "AL-Comp_Outbound"`) DO (

FOR /F "tokens=*" %%f IN ('DIR /S /B *.csv 2^>nul') DO (
    FOR /F "usebackq tokens=* eol=ÿ" %%s IN ("%%~f") DO (
        >>"%SUMMARY_FILE%" ECHO !LINE_COUNT!%%s
        SET /A LINE_COUNT+=1
    )
)
)

    POPD

    ENDLOCAL

Any help is truly appreciated !!!
===============================================================
Below is the code which i tried to get it work but it keeps on going to another folder  "AL-Comp_NetworkShare" to fetch CSV file while i only need csv files from sub directories in "AL-Comp_Outbound"
REM @echo off

SETLOCAL ENABLEDELAYEDEXPANSION
PUSHD "%~dp0"

SET "SUMMARY_FILE=sumfile.csv"
DEL /F "%SUMMARY_FILE%" 2>nul

SET "LINE_COUNT=1"

For /D %%G In ("%UserProfile%\Desktop\DLPLog\Export\*") Do For /D %%H In ("%%G\AL-Comp_Outbound\*")Do (PushD %%H,

FOR /F "tokens=*" %%f IN ('DIR /S /B *.csv 2^>nul') DO (
    FOR /F "usebackq tokens=* eol=ÿ" %%s IN ("%%~f") DO (
        >>"%SUMMARY_FILE%" ECHO !LINE_COUNT!%%s
        SET /A LINE_COUNT+=1
    )
)
,POPD)

ENDLOCAL

==================================output=================
PS C:\Users\username\Desktop\DLPLog\Export> .\me.bat

C:\Users\username\Desktop\DLPLog\Export>REM @echo off

C:\Users\username\Desktop\DLPLog\Export>SETLOCAL ENABLEDELAYEDEXPANSION

C:\Users\username\Desktop\DLPLog\Export>PUSHD "C:\Users\username\Desktop\DLPLog\Export\"

C:\Users\username\Desktop\DLPLog\Export>SET "SUMMARY_FILE=sumfile.csv"

C:\Users\username\Desktop\DLPLog\Export>DEL /F "sumfile.csv"  2>nul

C:\Users\username\Desktop\DLPLog\Export>SET "LINE_COUNT=1"

C:\Users\username\Desktop\DLPLog\Export>For / %G In ("C:\Users\username\Desktop\DLPLog\Export\*") Do For / %H In ("%G\AL-Comp_Outbound\*") Do (
PushD %H,
 FOR /F "tokens=*" %f IN ('DIR /S /B *.csv 2>nul') DO (FOR /F "usebackq tokens=* eol= " %s IN ("%~f") DO (
ECHO !LINE_COUNT!%s 1>>"sumfile.csv"
 SET /A LINE_COUNT+=1
) )
 POPD
)

C:\Users\username\Desktop\DLPLog\Export>For / %H In ("C:\Users\username\Desktop\DLPLog\Export\20200722\AL-Comp_Outbound\*") Do (
PushD %H,
 FOR /F "tokens=*" %f IN ('DIR /S /B *.csv 2>nul') DO (FOR /F "usebackq tokens=* eol= " %s IN ("%~f") DO (
ECHO !LINE_COUNT!%s 1>>"sumfile.csv"
 SET /A LINE_COUNT+=1
) )
 POPD
)

C:\Users\username\Desktop\DLPLog\Export>For / %H In ("C:\Users\username\Desktop\DLPLog\Export\20200723\AL-Comp_Outbound\*") Do (
PushD %H,
 FOR /F "tokens=*" %f IN ('DIR /S /B *.csv 2>nul') DO (FOR /F "usebackq tokens=* eol= " %s IN ("%~f") DO (
ECHO !LINE_COUNT!%s 1>>"sumfile.csv"
 SET /A LINE_COUNT+=1
) )
 POPD
)

C:\Users\username\Desktop\DLPLog\Export>For / %H In ("C:\Users\username\Desktop\DLPLog\Export\20200724\AL-Comp_Outbound\*") Do (
PushD %H,
 FOR /F "tokens=*" %f IN ('DIR /S /B *.csv 2>nul') DO (FOR /F "usebackq tokens=* eol= " %s IN ("%~f") DO (
ECHO !LINE_COUNT!%s 1>>"sumfile.csv"
 SET /A LINE_COUNT+=1
) )
 POPD
)

C:\Users\username\Desktop\DLPLog\Export>For / %H In ("C:\Users\username\Desktop\DLPLog\Export\20200725\AL-Comp_Outbound\*") Do (
PushD %H,
 FOR /F "tokens=*" %f IN ('DIR /S /B *.csv 2>nul') DO (FOR /F "usebackq tokens=* eol= " %s IN ("%~f") DO (
ECHO !LINE_COUNT!%s 1>>"sumfile.csv"
 SET /A LINE_COUNT+=1
) )
 POPD
)

C:\Users\username\Desktop\DLPLog\Export>(
PushD C:\Users\username\Desktop\DLPLog\Export\20200725\AL-Comp_Outbound\20200715,
 FOR /F "tokens=*" %f IN ('DIR /S /B *.csv 2>nul') DO (FOR /F "usebackq tokens=* eol= " %s IN ("%~f") DO (
ECHO !LINE_COUNT!%s 1>>"sumfile.csv"
 SET /A LINE_COUNT+=1
) )
 POPD
)
The system cannot find the path specified.

C:\Users\username\Desktop\DLPLog\Export>(FOR /F "usebackq tokens=* eol= " %s **IN ("C:\Users\username\Desktop\DLPLog\Export\20200722\AL-Comp_NetworkShare\20200702\20200702_Ncomp-fjt03063.csv")** DO (
ECHO !LINE_COUNT!%s 1>>"sumfile.csv"
 SET /A LINE_COUNT+=1
) )

A: This simple and straightforward Batch file should work:
@echo off
setlocal EnableDelayedExpansion

rem Go to base folder
cd C:\Users\username\Desktop\DLog\Export

rem Process all folders here
for /D %%a in (*) do (

   rem Enter to each folder AND to the desired subfolder
   pushd "%%a\AL-Comp_Outbound"

   rem Parse through all subfolders here
   for /D %%b in (*) do (

      rem Combine all .csv files in each subfolder
      for %%f in ("%%b\*.csv") do (
         if not exist sumfile.tmp (
            copy "%%f" sumfile.tmp
         ) else (
            more +1 "%%f" >> sumfile.tmp
         )
      )

   )

   rem Go back to base folder
   popd

)


text:
Q: Long distance communication between two Android phones I'm looking to develop an Android app which resides on both phones, sends location data and receives the same to know the distance and absolute direction of the other device, and shows whether the user is going in the right direction(i.e. distance decreasing) or not.
How can the devices communicate? Would 2G/3G internet or SMS be a good choice? Is it hard to implement this idea? Any suggestions would be helpful.

A: You have three choices to automatically acquire a devices position: GPS, Cell Signal Triangulation and WiFi directional location. You can read about their individual strengths and weaknesses in this guide: Location Strategies
As for communicating over long distances you have 2-3 options to push and pull data from a device: Mobile Data, WiFi, and under the right circumstances Bluetooth. Here is an article on WiFi Direct.
These are all involved topics that are too complex for one question, under the FAQ:

Your questions should be reasonably scoped. If you can imagine an entire book that answers your question, you're asking too much.

However you can accomplish your goal by taking it on subject at a time.


text:
Q: Changing QWidget object scope changes the CSS Consider this two parts of code

*

*NotifWidget* notifWidget_ = new NotifWidget();
 notifWidget_->show();
 notifWidget_->move(computePosition(notifWidget_));

*notifWidget_->show();
 notifWidget_->move(computePosition(notifWidget_));
In first case the NotifWidget (which is inherited from QFrame) the notifWidget_ object is local object and the corresponding widget is show like this

In the second case the notifWidget_ object is the class member and and here is the image for that case

Both widgets have same CSS style sheet and same objectName. Does anyone know what's the problem for the second case? Why in second case the inner widgets are overlapped?
update
including css(if any)
QWidget#NotifWidget_actions
{
    border:0px solid;
}
QWidget#AccessGiven, QWidget#AccessGiven[onhover="false"]
{
    background: white;
}
QWidget#AccessGiven[onhover="true"]
{
    background: #f2f2f2;
}

QLabel#AccessGiven_icon, QLabel#AccessGiven_message, QLabel#AccessGiven_icon[onhover="false"], QLabel#AccessGiven_message[onhover="false"]
{
    background: white;
    padding-bottom: 0px;
    qproperty-wordWrap: true;
    max-height: 48px;
    min-height: 48px;
}
QLabel#AccessGiven_message
{
    font: 12px;
    max-width: 200px;
    min-width: 200px;
}
QLabel#AccessGiven_icon
{
    max-width: 64px;
    min-width: 64px;
}
QLabel#AccessGiven_icon[onhover="true"], QLabel#AccessGiven_message[onhover="true"]
{
    background: #f2f2f2;
}

QPushButton#AccessGiven_action, QPushButton#AccessGiven_action[onhover="true"]
{
    font: 12px;
    color: rgba( 35, 35, 35, 0% );
    padding-bottom: 0px;
    background-color: rgba( 35, 35, 35, 0% );
    margin-left: 0px;
}
QPushButton#AccessGiven_action[onhover="true"]
{
    color: rgba( 35, 35, 35, 50% );
}

QPushButton#AccessGiven_action:hover
{
    background: rgba( 35, 35, 35, 20% );
}
QPushButton#AccessGiven_action:pressed
{
    background: rgba( 35, 35, 35, 10% );
    padding-bottom: 2px;
}
QPushButton#NotifWidget_settings
{
    background-image: url(./media/settings.png);
    height: 24px;
    width: 24px;
    background-repeat: no-repeat;
    background-position: center center;
    border: 0px;
}
QPushButton#NotifWidget_settings:hover
{
    background-color: lightgray;
}
QPushButton#NotifWidget_settings:pressed
{
background-color: silver;
}

QPushButton#NotifWidget_help
{
    background-image: url(./media/help.png);
    height: 24px;
    width: 24px;
    background-repeat: no-repeat;
    background-position: center center;
    border: 0px;
}
QPushButton#NotifWidget_help:hover
{
    background-color: lightgray;
}
QPushButton#NotifWidget_help:pressed
{
    background-color: silver;
}

QPushButton#NotifWidget_toWeb
{
    height: 24px;
    width: 24px;
    background-image: url(./media/web.png);
    background-repeat: no-repeat;
    background-position: center center;;
    border: 0px light ;
}
QPushButton#NotifWidget_toWeb:hover
{
    background-color: lightgray;
}
QPushButton#NotifWidget_toWeb:pressed
{
    background-color: silver;
}

QPushButton#NotifWidget_exit
{
    height: 14;
    padding:2px;
    margin-left:5px;
    background-color: rgb(255,0,0, 0%);
    border: 1px light ;
}
QPushButton#NotifWidget_exit:hover
{
    background-color: rgb(255,0,0, 25%);
}
QPushButton#NotifWidget_exit:pressed
{
    background-color: rgb(255,0,0, 35%);
}
QScrollArea#NotifWidget_scrollArea
{
/*    background: transparent;
    border: 0px solid;*/
}
QFrame#NotifWidget
{
    background-color: #F5F5F5;
    /*min-width: 345;
    max-width: 345;
    min-height: 400;*/
    border: 1px solid rgb(37, 76, 241);
}


text:
Q: Will Sergius Turrianus ever stop giving you quests? In the College of Winterhold, the professor Sergius Turrianus can give you a quest where you go to a random person and pick up an item (as well as a quest where you give him some soul gems). My question is: is it possible to ever "complete" these quests, or will he continue to give you them forever (even after he starts giving you the same people over again)? By complete I mean he will have no more fetch quests left for you to do and will never give you the chat option to do them again.
Also, if it is possible, what is the "ending" dialouge he gives you in congragulations (if there is one)?

A: No, he won't stop. These are Radiant quests and are part of why Bethesda advertised "infinite quests" in the hype for Skyrim's release. They are infinitely generated, though repetitive.

A: There's no end. Same as Delvin's and Vex's quests.


text:
Q: Ctags not working with .inc-files I would love to use tags inside Emacs, like Vim does. However, I have some problems to set it ## Setup:
GNU Emacs GUI version 25.0.5.1 (x86_64-w64-mingw32)
Compiled from Harroogan Emacs.
Projectile and Helm, using the latest version of Projectile/Helm from MELPA
Exuberant Ctags binary 58 for Windows
Windows 7 x64 bit.
Actions:
The binary ctags.exe is in the PATH, and respons when I call it from command line in Windows with ctags --help.
I tried various things to create a TAGS file, without any result. One thing that I seem to have results, is with the help of the package projectile. But it gives me weird results.
When I'm inside a project, currently the buffer index.php is being opened. Inside that buffer, I regenate tags file with projectile-regenate-tags, with C-c p R.
The messages buffer gives me the following:
Starting a new list of tags tables
Making tags-file-name local to Dev/digiloket3/TAGS while let-bound!

I see the file TAGS is being created in the project root.
The directory root structure is like this:
index.php
.projectile
|- INCLUDE
    |- AJAX
    |- SCRIPTS
    |- PHP

Issue:
Then I visit the tag list with find-tag (g C-]). When  I notice I don't get all variables and class/functions that are defined in the project.
When I call the helm-etags-select, I see the directory/file next to the tag. And what confuses me, is that only functions/classes and variables from files in the directory AJAX are being visible in the tag list, and not the variables/classes/functions from the files in the directory PHP.
Then I manually creating the TAGS file with in the command prompt with the right directory on ctags -R.
With no help.
All files in the folder PHP are called ****.inc.
When I renamed one of the files to ****.php, then they're popping up in my ctags table.
So the real issue here is how I could tell projectile/ctags to recognize .inc files as PHP-files, or index it
But I'm also open for another things to create a TAGS table on Windows platform with the ctags available on command line.
Any suggestion?

A: man ctags for starters (if you can do so in Windows? There is documentation available in any case.)
Assigning file extensions for a language is done with --langmap. Run the following command to see how that argument works:
ctags --langmap=php:+.inc.foo.bar --list-maps=php
So in your case, you would probably use something like this to generate your TAGS file:
ctags -e -R --langmap=php:+.inc
Tangentially, note also the options listed when you run ctags --list-kinds=php. You can then control which of those will be used: ctags --php-kinds=-v-j --list-kinds=php


text:
Q: Implementing State Pattern using references I'm trying to refactor my code, among other things, applying state pattern. I'm more of a Java programmer, so please, be nice ;)
So, here I've got my base state class, nothing fancy:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include "FaceRegion.hpp"

class AlghorithmState {
public:
    AlghorithmState(FaceRegion context);
    virtual ~AlghorithmState();
    virtual cv::Mat processImage(cv::Mat frame) = 0;

private:
    FaceRegion CONTEXT;

};

and one of child states:
class HaarClassifierState : public AlghorithmState {
public:
    HaarClassifierState(FaceRegion context);
    virtual ~HaarClassifierState();
    cv::Mat processImage(cv::Mat frame);
};

And, then there's Context class, which holds current state and invokes processImage on it inside of its fromImage method/function:
#include "AlghoritmState.hpp"
using namespace cv;

class FaceRegion {
public:
    FaceRegion();
    virtual ~FaceRegion();
    Mat fromImage(Mat& image);
    void setAlghoritmState(AlghorithmState state); // line 10
private:
    AlghorithmState alghoritm; //line
}

The problem is, when I try compiling this code, I get following error on line 10
In file included from AlghoritmState.hpp:15:0,
                 from FaceRegion.hpp:10,
                 from newmain.cpp:93:
FaceRegion.hpp:35:28: error: 'AlghorithmState' has not been declared
FaceRegion.hpp:39:5: error: 'AlghorithmState' does not name a type

What did I do wrong? I tried adding incomplete class declaration of AlghoritmState in the CONTEXT class header file but it only throws another error:
In file included from AlghoritmState.hpp:15:0,
                 from FaceRegion.hpp:10,
                 from newmain.cpp:93:
FaceRegion.hpp:40:21: error: field 'alghoritm' has incomplete type
FaceRegion.hpp:36:10: error: cannot declare parameter 'state' to be of abstract type 'AlghorithmState'
In file included from FaceRegion.hpp:10:0,
                 from newmain.cpp:93:
AlghoritmState.hpp:17:7: note:   because the following virtual functions are pure within 'AlghorithmState':
AlghoritmState.hpp:21:21: note:     virtual cv::Mat AlghorithmState::processImage(cv::Mat)

Any hints appreciated.

A: You have circular includes here:
AlghoritmState.hpp is #includeing FaceRegion.hpp and vice versa. With include guards this means that one header will see the other, but not the other way.
Your problem is that you use both AlghoritmState in the FaceRegion and the other way around. The AlghoritmState is a interface, so you should drop the member variable there and add it to the implementation, the HaarClassifierState
In that way you include like this:

*

*FaceRegion include AlghoritmState

*HaarClassifierState include FaceRegion and AlghoritmState
as you can see, you have no more cycles and you compilation problems will be gone.
Important:
You are currently storing objects by value. When you do that with inherited objects they are prone to slicing which means that you might end up with a object that is smaller that it should be, leading to nasty stuff happening (UB). So you should in all cases stop storing objects super classes as values, and store them as pointers instead.
(which ofcourse leads us to the problems of ownership of the variable, but that is for another question). So only have member variables of a super type if it is the actual super type that is stored there.


text:
Q: Module structure of base extension via tensor product Let $A,B$ be commutative rings.
Defining a product of $B\otimes_{A}B$ as $(b_1 \otimes b_2)\cdot (b_3 \otimes b_4)=(b_1b_3)\otimes(b_2b_4)$, this becomes a commutative ring.
Defining $b\cdot(b_1 \otimes b_2)=(bb_1)\otimes b_2$ for $b,b_1,b_2 \in B$, this becomes a $B$-module.
Then, my textbook says, if I define as $b\cdot(b_1 \otimes b_2)=b_1\otimes (bb_2)$ instead, it defines a different $B$-module structure. I don't understand this.
Isn't the homomorphism defined by $\phi(b_1\otimes b_2)=b_2\otimes b_1$ an  isomorphism of them?

A: Let $B$ be an $A$-algebra and $M$, $N$ be $B$-modules. Here is an example in which $M \otimes_A N$ and $N \otimes_A M$ are isomorphic as $A$-modules, but not as $B$-modules. $\mathbb Z[x]$ is a $\mathbb Z$-module via the inclusion $\mathbb Z \hookrightarrow \mathbb Z[x]$. Let $M = \mathbb Z[x]$ be a $\mathbb Z[x]$-module via the identity. Let $N = \mathbb Z[x]$ be a $\mathbb Z[x]$-module via evaluation at $0$. Then $M \otimes_\mathbb Z N \cong N \otimes_\mathbb Z M$ as $\mathbb Z$-modules. However, they aren't isomorphic as $\mathbb Z[x]$-modules, since one is annihilated by $x$ while the other isn't.

A: The ring $B\otimes _A B$ has a canonical $A$-algebra structure and TWO different structures of $B$-algebra,  which I'll call $(B\otimes _A B)_l$ and $(B\otimes _A B)_r$, according as multiplication by elements of $B$ happens on the left or on the right.
These $B$-algebra structures are in general different since  if we denote by $\bullet $ and $\circ$ the actions of $B$ on  $(B\otimes _A B)_l$ and $(B\otimes _A B)_r$, we have  $$b\bullet (b_1\otimes b_2)=bb_1\otimes b_2\stackrel {\text{in general}}{\neq} b_1\otimes bb_2=b\circ (b_1\otimes b_2)$$ However, as you correctly noticed the swapping morphism of $A$-algebras $$\mu:B\otimes _A B\to B\otimes _A B:b_1\otimes b_2\mapsto b_2\otimes b_1$$ is indeed  an isomorphism of $B$-algebras $$\mu:(B\otimes _A B)_l\to (B\otimes _A B)_r$$ as shown by the following trivial calculation : $$\mu(b\bullet (b_1\otimes b_2))=\mu(bb_1\otimes b_2)=b_2\otimes bb_1=b\circ(b_2\otimes b_1)=b\circ\mu(b_1\otimes b_2)$$
SUMMARY
The $B$-algebras $(B\otimes _A B)_l$ and $(B\otimes _A B)_r$ are different but isomorphic.


text:
Q: C# | Changing the size of the consoles buffer below what was initially set I'm wondering if its possible to change the size of the consoles buffer, as the included Console.SetBufferSize function will not allow you to shrink the buffer. bonus points if I don't need a external library.

A: According to the MSDN documentation of Console.SetBufferSize it is not limited to growing the buffer. However you have to adjust the console window size before shrinking the buffer.
This example works:
Console.WriteLine($"Current buffer size: {Console.BufferWidth}x{Console.BufferHeight}");
Console.SetWindowSize(1, 1);
Console.SetBufferSize(80, 80);
Console.SetWindowSize(40, 20);
Console.WriteLine($"New buffer size: {Console.BufferWidth}x{Console.BufferHeight}");

Output:

Current buffer size: 120x9001
  New buffer size: 80x80


text:
Q: Including header files of base-classes and sub-classes (derived classes) correctly? Lets say I have 2 base classes, Base1 and Base2.
// Base1.h
#ifndef BASE1_H
#define BASE1_H
#include "Base2.h"

class Base2;

class Base1 {
    ...
    void func(Base2* b);
    virtual void subfunc(Base2* b) = 0;
    ...
};
#endif

// Base2.h
#ifndef BASE2_H
#define BASE2_H
#include "Base1.h"

class Base1;

class Base2 {
    ...
    void func(Base1 *b);
    virtual void subfunc(Base1* b) = 0;
    ...
};
#endif

and I include each other's header file in each header file since Base1 has functions that has Base2 as parameter and Base2 has functions that has Base1 as parameter.
Then lets say I have 5 subclasses (derived classes) for both Base1 and Base2;
Base1_Sub1, Base1_Sub2, Base1_Sub3, Base1_Sub4, Base1_Sub5 for Base1
Base2_Sub1, Base2_Sub2, Base2_Sub3, Base2_Sub4, Base2_Sub5 for Base2.
I want to be able to have 5 derived classes of Base1 as parameter of class function in, lets say Base2_Sub1.
// Base2_Sub1.h
#ifndef BASE2_SUB1_H
#define BASE2_SUB1_H
#include "Base2.h"
// What else to include!?

class Base2_Sub1 : public Base2 {
    ...
    void subfunc(Base1_Sub1 *b);
    void subfunc(Base1_Sub2 *b);
    void subfunc(Base1_Sub3 *b);
    void subfunc(Base1_Sub4 *b);
    void subfunc(Base1_Sub5 *b);
    ...
};
#endif

In what file should Base1_Sub1.h to Base1_Sub5.h be included?
I also need subclasses of Base2 (such as Base2_Sub1) to have subclasses of Base1 as function parameter the same way.
I found it extremely confusing to include these headers correctly and I have no idea how. Please help me.

A: If you can avoid including headers by introducing a forward declaration, you do not need to include the header. Both your Base1.h and Base2.h headers provide good examples: Base1 can compile with only a forward declaration of Base2, because it uses only pointers to Base2; same goes for Base2's use of Base1 pointers. Therefore, the mutual inclusions can be safely removed.

In what file should Base1_Sub1.h to Base1_Sub5.h be included?

The inclusion would be mandatory in their corresponding Base1_Sub1.cpp to Base1_Sub5.cpp. Other cpp files should include them as necessary.

I also need subclasses of Base2 (such as Base2_Sub1) to have subclasses of Base1 as function parameter the same way.

As far as header files including header files go, if headers for your subclasses can be defined using pointers to Base1 and Base2, do not include headers at all. This will shrink the time it takes to compile your code.
Of course you need to include headers for classes that you instantiate, and for classes on which you call member functions or access their data members.


text:
Q: Json module error for saving dictionary I'm coding a program to oraganise my homework.
I got an error while trying to save my dicts with json and i have no idea what to do. I'm really lost. Also I'm kind of a noob so don't post anything to complex if you can. Thanks
Here's the error
    Traceback (most recent call last):
  File "Homework.py", line 12, in <module>
    json.load(f1)
  File "F:\Software\Python\lib\json\__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "F:\Software\Python\lib\json\__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "F:\Software\Python\lib\json\decoder.py", line 343, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "F:\Software\Python\lib\json\decoder.py", line 361, in raw_decode
    raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)

If you want my whole code (not finished yet, it's missing a lot)
#insert date to rate urgency of the tasks
#BLOCK 1:1
print("today's date, month(insert month number)")
ThisMonth = input(">>>")
print("today's date, day(insert day number)")
ThisDay = input(">>>")

#BLOCK 1:2
#import dictionaries
import  json
with open('LessonOut.txt', 'r') as f1:
 json.load(f1)
with open('ExercisesOut.txt', 'r') as f2:
 json.load(f2)
with open('AssignmentOut.txt', 'r') as f3:
 json.load(f3)
#BLOCK 1:5
#everything will be in a while true loop for it to run smoothly until stopped
while True:
 Input = input('>>>')

 #This is used to add a task
 #BLOCK 2:1
 if Input == 'add':
  print('Name of task?')
  Name = input('>>>')
  print('Description of task?')
  Desc = input('>>>')
  print('Rate the time it takes you to do the task on a scale from 1 to 20')
  Time = input('>>>')
  print('>>>')
  Imp = input('>>>')
  print("Rate how much you want to do it on a scale from 1 to 5 (1= want to do it, 5= don't want to")
  Want = input(">>>")
  print("enter deadline (month)")
  TimeMonth = input(">>>")
  print("enter deadline (day)")
  TimeDay = input(">>>")
  print("what type of homework is it? (Lesson/Exercises/Assignment)")
  Type = input(">>>")
  #determines what type of task it is and puts it in the right dictionary

  #BLOCK 2:2
  #Used to calculate time left to finish assignment
  DayLeft = 0
  if ThisMonth > TimeMonth:
   TimeMonth = TimeMonth + 12
  if ThisMonth == ( 1 or 3 or 5 or 7 or 8 or 10 or 12 ) and TimeDay < ThisDay:
   ThisMonth = ThisMonth + 1
   DayLeft = DayLeft + ( 31 - ThisDay )
  elif ThisMonth == 1 or 3 or 5 or 7 or 8 or 10 or 12:
   ThisMonth = ThisMonth + 1
   DayLeft = DayLeft + ( TimeDay - ThisDay )

  #BLOCK 2:3
  while ThisMonth < TimeMonth:
   if ThisMonth == 1 or 3 or 5 or 7 or 8 or 10 or 12:
    ThisMonth = ThisMonth + 1
    DayLeft = DayLeft + 31
   elif ThisMonth == 4 or 6 or 9 or 11 or 16 or 18 or 21 or 23:
    ThisMonth = ThisMonth + 1
    DayLeft = DayLeft + 30
   elif ThisMonth== 2 or 14:
    ThisMonth = ThisMonth + 1
    DayLeft = DayLeft + 28

  #BLOCK 2:4
  if Type == Lesson:
   Rating = Time + Imp + Want
   Lesson.update = {DayLeft:(Name,Desc,Rating,TimeDay,TimeMonth)}
  if Type == Exercises:
   Rating = Time + Imp + Want
   Exercises.update = {DayLeft:(Name,Desc,Rating,TimeDay,TimeMonth)}
  if Type == Assignment:
   Rating = Time + Imp + Want
   Assignment.update = {DayLeft:(Name,Desc,Rating,TimeDay,TimeMonth)}

 #BLOCK 5:1
 if Input == 'quit':
  print ("are you sure you want to quit?")
  Input = input('>>>')
  if Input == 'Yes' or 'yes' or 'y' or 'Y' or 'Yse' or 'yse':
   #BLOCK 5:2
   #Save an output dictionaries
   with open('LessonOut.txt', 'w') as f1:
    json.dump(Lesson, f1)
   with open('ExercisesOut.txt', 'w') as f1:
    json.dump(Exercises, f1)
   with open('AssignmentOut.txt', 'w') as f1:
    json.dump(Assignment, f1)
   break
   break
   break


text:
Q: Change DataStax java driver User and Password in runtime I am running a Java app with DataStax Java driver version 3.3.0 and I am trying to change Cassandra user and password at runtime. According to this issue by calling setUser and setPassword in this object it should reuse it for future calls to the DB, so I did in my code something like
PlainTextAuthProvider authProvider = (PlainTextAuthProvider) cluster.getConfiguration().getProtocolOptions().getAuthProvider();

authProvider.setUsername(user);
authProvider.setPassword(pwd);

But even after this change I find that it still use the user/pass I set on startup.
This docu indicates that in versions > 4.x you can force a config reload at runtime.
So my question is, Is there a way to force all new calls to Cassandra start using the new User and Pass provided via PlainTextAuthProvider in version 3.x ?
Extra: I am doing this to try to rotate Vault passwords when they expire and update the driver accordingly. Something like what is described in this post for relational DB accessed by Spring Boot but on Cassandra

A: The question was also asked on https://community.datastax.com/questions/11846/ and I'm reposting my response here:
I'm not familiar with this API but I think the credentials are used just for new connections initiated after the credentials are set. I suspect it doesn't apply to existing connections which continue to use the old credentials.
I'm going to reach out to the Driver devs here at DataStax and will either get them to respond directly or I will update my answer. Cheers!


text:
Q: Yii required validation based on condition I want to validate field based on condition in Yii model.
I've two fields in my view
type (radiobutton): standard & special
term (textfield) : any text data
Current I am showing term textbox based on type condition i.e. if type is special then show o/w hide.
I want to validate it using Yii required rule that is if user select radio button special then he must have to fill term textfield data o/w its not mandatory.
If I use required for special then its validating in case of type = standard which is wrong. I've did following custom validation but its not working.
public function rules() {
     array('type', 'required'),
     array('term', 'checkTerm', 'trigger' => 'type'),
}

public function checkTerm($attribute, $params) {
     if ($this->$params['trigger'] == "Special") {
        if (empty($attribute))
           $this->addError($attribute, 'Special term cannot be blank.');
     }
}

Where I am going wrong? Need Help. Thanks

A: Try this :
public function rules() {
     array('type', 'required'),
     array('term', 'checkTerm'),
}

public function checkTerm() {
     if ($this->type == "Special") {
        if (empty($this->term))
           $this->addError("term", 'Special term cannot be blank.');
     }
}

A: Instead of
 if (empty($attribute))
       $this->addError($attribute, 'Special term cannot be blank.');
 }

use
 if (empty($this->term))
       $this->addError($attribute, 'Special term cannot be blank.');
 }


text:
Q: Timeout requests during Solr Commit If an update request sent to solr times out without a response is that request still fullfilled?

A: You could query the server to find out if your document arrived. But if it does not answer, chances are, there has been some problem on the way to the server. If you can see the solr logs, you could find problems there.


text:
Q: ios - simulator looks different from the layout on the storyboard screen I am having a strange situation. I created a very simple screen with some buttons on the storyboard, then when I ran the emulator (is it correct to say simulator or emulator?) it got the spacing wrong for one of the buttons.
I am adding a screenshot. The emulator is to the right of the storyboard screen.
Any idea why this may happen?

I thought it was a problem with the button. And it might have been. But when I took out two lower buttons, I got something even weirder as shown on this screenshot:

Thanks!

A: It looks like you are using Autolayout, and all your buttons except Investment has a Top constraint while Investment has a Bottom constraint, causing Investment's distance to bottom to stay the same when the screen grows taller.
Click on Investment button, click [Editor -> Pin -> Top space to Superview] in the top menu.
Click Investment button again. Click the second tab from the right in the right panel (the one where you can set frame). Look for a Top Space to Superview constraint, right click and delete. If there isn't one, then XCode did its job. Try running simulator again.
Edit: I just want to say that XCode has a habit of adding Top constraints for you when the view you just dragged into the xib is in the upper half of its container, and Bottom constraints when it's in the bottom half. I know XCode is trying to help but it drives me crazy sometimes.

A: It looks like you're using a 3.5" simulator and laying out for a 4" device, so the view will be resized.
If you're using autoresize masks, are some of the autoresize masks on your buttons incorrect? You probably want them all to stick to the top of the screen. Check to make sure the autosizing for each of your buttons matches this image. (You'll need to click the "ruler" icon to see these settings.)

A: I assume that you're using the XCode4 which provides NSAutoLayout as default. When you place an object to the storyboard NSAutolayout automatically creates constrains which layouts the object on the screen automatically for different devices(iPhone4,iPhone5) or orientations(portrait/landscape). Please check NSAutolayout class and constrains. if you want you can remove the NSAutolayout and your objects will be displayed on the simulator normal but in that case you have to manually adjust your objects for different orientations and screens
Hope helps.


text:
Q: Who commanded or executed this action in Game of Thrones S8E5? It seems that Cersei just stands in her fortress without giving any orders. Despite that,

 the bells start to ring.

It also seems that she doesn't have any will to surrender.
So who commanded that?
Or (if no one), who actually did it (maybe they decided by themselves to do it)?

A: The first one to surrender (on screen) was the Lannister Captain that was facing down Jon, Grey Worm, a street full of Unsullied and Northmen, and a rather angry looking dragon on the tower.

Once someone with a position of authority set the precedent of surrender, the cry to "ring the bells!" spread through the army. We don't see who first uttered the cry, but we can safely assume it was the captain (or a lieutenant nearby) calling out to signal that the city surrendered.
Ringing the bells was apparently a culturally known sign, and since it was something a city's people would do, instead of something requiring the Lord/Lady/General to do (like a parley), it would seem it was somewhat common. This would make sense in a world where random towns would be used to various armies "conquering" them regularly. Like Tyrion said:

What is the realm? A vast continent, home to millions of people, most of whom don't care who sits on the Iron Throne.
Game of Thrones - S08E04: Last of the Starks

The random citizens would rather pay taxes to the next Lord over, than die in defense of their current one. So once the army started surrendering, they raised the cry to "ring the bells!" and signal the surrender so that no one else had to die from the massive dragon who was actively burning down their city.
In short, and to answer the question directly, it was a general consensus based on cultural norm and prompted by the Lannister Captain who realized he was going to lose his battle.

A: The forces on the ground decided to ring the bells
After Dany lands and the Lannister forces in the stand off against Jon and Grey Worm surrender and chuck down their weapons you start to hear men shouting.

Ring the bells

It goes on for a while until someone finally manages to get there and to ring the bells. The ground forces and presumably a Captain in them decided to ring the bells, the order does not come from the Red Keep there just wasn't time. The order just comes from within when they realise all is lost.


text:
Q: Please, do all these sentences have the same meaning, or does the preposition used after spend affect the meaning?
*

*The US government spends billions of dollars to develop vaccines and drugs each year.

*The US government spends billions of dollars on developing vaccines and drugs each year.

*The US government spends billions of dollars developing vaccines and drugs each year.

A: With the Present tense verb (spends), there isn't really any difference in meaning between OP's 3 examples. But that's not true if we switch to Past tense (and discard "each year" to avoid connotations of continuity through Present and Future)...

1: They spent billions of dollars to develop their own Covid vaccine.
2: They spent billions of dollars on developing their own Covid vaccine.
3: They spent billions of dollars developing their own Covid vaccine.

...where #1 very strongly implies they did in fact develop their own vaccine, but there's no particular implication regarding success/failure with #2 and #3 (which imho are always 100% equivalent in meaning; it's entirely an optional stylistic choice1 whether to include preposition on in such contexts).
To illustrate this distinction, I'll point out that #2 and #3 could quite reasonably be continued with...

2/3a: ... but all their efforts failed, and eventually they bought a vaccine developed by AstraZeneca.

...but that continuation is unlikely with #1, which implies they were successful.

1 Whenever there's a "stylistic choice" involved, it's likely that at least some people will assign different meanings to the choices made. In the cited context, some (certainly not most) people might say that #3 (without on) is closer in meaning to #1 than to #2.


text:
Q: Flutter: How to pass parameter to FutureBuilder future instance? For prevent rebuild, I use a future instance _futureInstance in FutureBuilder:
var _futureInstance;

Future _loadData() async {
    // ...
}

@override
void initState() {
    super.initState();
    _futureInstance = _loadData();
}

@override
Widget build(BuildContext context) {
    body: FutureBuilder(
        future: _futureInstance,
        // ...
    )
}

It works well, now if the _loadData method has a parameter, such as _loadData(int i), how can I pass the parameter i to _futureInstance?

A: I solved this problem in another way, use MaterialApp.onGenerateRoute.
As this answer: Flutter: Get passed arguments from Navigator in Widget's state's initState
I get the parameter in initState method:
  @override
  void initState() {
    super.initState();
    _futureInstance = _loadData(widget.parameter_key);
    // ...

and in build, the code not change:
@override
Widget build(BuildContext context) {
    body: FutureBuilder(
        future: _futureInstance,
        // ...
    )
}

In this way, the method _loadData can use various parameters, and the widget is not rebuild when setState is called.

A: @override
void initState() {
    super.initState();
    _futureInstance = (int i) => _loadData(i);
}

@override
Widget build(BuildContext context) {
    body: FutureBuilder(
        future: _futureInstance(1), // pass your number here
        // ...
    )
}

A: wasn't sure the purpose of _futureInstance, perhaps you don't need to define the instance?
Future _loadData(val) async {
    // ...
}

@override
void initState() {
    super.initState();
}

@override
Widget build(BuildContext context) {
    body: FutureBuilder(
        future: _loadData(1),
        // ...
    )
}

A: i would approach like this

var _lastInt = 0;
var _lastFuture;

Future _loadData(int i) async {
  if(_lastInt!=i||_lastFuture==null){
    //do work
    _lastInt = i;
    _lastFuture = ;
  }
  return _lastFuture;
}

@override
Widget build(BuildContext context) {
  body: FutureBuilder(
    future: _loadData(1),
    // ...
  );


text:
Q: Set Body Parameter in Angular HttpClient I have an Asp.Net Core Web API with Angular framework.
I have an action to get value as below:
    [HttpGet]

    public ActionResult<IEnumerable<MyModel>> Get([FromBody] MyParameter parameter) { ... }

And my client application is called API as follow:
return this.httpClient.get<MyModel[]>(`${environment.api}values`);

How I can set Body in API call?
Thanks

A: It is not possible to send body as param in Get request. Please use POST
API
[HttpPost]

public ActionResult<IEnumerable<MyModel>> Get([FromBody] MyParameter parameter) { ... }

UI
return this.httpClient.post<MyModel[]>(`${environment.api}values`);

If you want to user get, you can pass the params properties as querystring

A: In HttpGet of Angular you can not set body you can only set the url and the http options like this
getConfigResponse(): Observable<HttpResponse<Config>> {
  return this.http.get<Config>(
    this.configUrl, { observe: 'response' });
}

So if you want to submit the body you have to use post request like this
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)


text:
Q: List of Objects as RequestParam in Spring MVC I want to send a list of object id's (generated by the user selecting checkboxes) by POST to an action, so I can get a java.util.List<MyObject> converted using an MyObjectEditor.
So, is it possible to do this?
@InitBinder
public void initBinder (WebDataBinder binder) {
    binder.registerCustomEditor(MyObject.class, new MyObjectEditor());
}
@RequestMapping (value = "", method = RequestMethod.POST)
public String action (@RequestParam List<MyObject> myList, Model model) {
    // more stuff here
}

And my POST would be like this:
myList[0] = 12
myList[1] = 15
myList[2] = 7

Thanks!

A: This kind of binding is not supported by @RequestParam, so you have to use @ModelAttribute:
class MyObjects {
    private List<MyObject> myList;
    ...
}

public String action (@ModelAttribute MyObjects myObjects, Model model) { ... }


text:
Q: Getting the last commit hash from a remote repo without cloning I want to get the hash of last commit that has happened in a remote repo without cloning it. Is there a way to do this ? I found several methods but for all of them to work, I need to clone the repo first and then issue the commands to get the last commit hash.
Is there a way I can get the last commit hash from a remote git without cloning it ?
Note:

A: $ git ls-remote https://github.com/gturri/dokuJClient.git
2fb540fc8c7e9116791638393370a2fa0f079737    HEAD
2fb540fc8c7e9116791638393370a2fa0f079737    refs/heads/master

This command can be run from any directory.
If you only want the last sha1, eg to use it in a script, you could then do:
git ls-remote https://github.com/gturri/dokuJClient.git HEAD | awk '{ print $1}'

A: One way would be the following:

*

*Initialize your local repo: git init

*Add your the remote to it: git remote add myRemote "https://myremoterepo"

*Fetch the repo and check the history for the last commit: git fetch remote
Alternatively, you could also go to the repo page on github (I assume from your tag) and check the commits tab. It will show you the latest commit and its sha.

A: Just a note in addition to @gturri's answer, that you can also use the name of the remote (as opposed to the url).
E.g. if you push with something like: git push heroku master, then you could use
git ls-remote heroku

This example assumes the name of your remote is 'heroku'.
You can replace 'heroku' above with whatever your remote is called.


text:
Q: Infrequent measurements in Gekko with extra simulation points I'm solving a more complex dynamic data reconciliation problem that is similar to the example problem posted in the APMonitor dynamic optimization course. Similar to this problem, I have infrequent measurements at irregular intervals. Instead of using the more accurate NODES=5 (for increased accuracy), I would like to have more frequent simulation points with NODES=2 at [0,0.1,0.2,0.3,0.4,0.5,0.6.0.7,0.8,0.9,1.0] that also includes the infrequent measurements for the objective at [0, 0.1, 0.2, 0.4, 0.8, 1].
from gekko import GEKKO
t_data = [0, 0.1, 0.2, 0.4, 0.8, 1]
x_data = [2.0,  1.6,  1.2, 0.7,  0.3,  0.15]
m = GEKKO(remote=False)
m.time = t_data
x = m.Var(value=x_data)     # fit to measurement
xd = m.Param(x_data)
k = m.FV(); k.STATUS = 1    # adjustable parameter
m.Equation(x.dt()== -k * x) # differential equation
m.Minimize((x-xd)**2)
m.options.IMODE = 5   # dynamic estimation
m.options.NODES = 2   # collocation nodes
m.solve(disp=False)   # display solver output
k = k.value[0]

One of the reasons for this is that the simulation model needs to solve more frequently than the measurements to maintain integration accuracy with NODES=2. The exact solution deviates from the numerical solution if I only solve at the measurement points.

import numpy as np
import matplotlib.pyplot as plt  # plot solution
plt.plot(m.time,x.value,'bo',\
         label='Predicted (k='+str(np.round(k,2))+')')
plt.plot(m.time,x_data,'rx',label='Measured')
# plot exact solution
t = np.linspace(0,1); xe = 2*np.exp(-k*t)
plt.plot(t,xe,'k:',label='Exact Solution')
plt.legend()
plt.xlabel('Time'), plt.ylabel('Value')
plt.show()

How can I use a lower order collocation mode with more frequent simulation points and infrequent measurements in Gekko?

A: You can combine infrequent measurements with more frequent simulation steps in Pandas with the join() function:
from gekko import GEKKO
import numpy as np
import pandas as pd
# measurements
t_data = [0,0.1,0.2,0.4,0.8,1]
x_data = [2.0,1.6,1.2,0.7,0.3,0.15]
df1 = pd.DataFrame({'time':t_data,'x':x_data})
df1.set_index('time', inplace=True)
# simulation time points
df2 = pd.DataFrame({'time':np.linspace(0,1,51)})
df2.set_index('time', inplace=True)
# merge dataframes
df = df2.join(df1,how='outer')
# get True (1) or False (0) for measurement
df['meas'] = (df['x'].values==df['x'].values).astype(int)
# replace NaN with zeros
df0 = df.fillna(value=0)
print(df.head(15))

This gives the combined set with NaN for the missing data points.
        x  meas
time
0.00  2.0     1
0.02  NaN     0
0.04  NaN     0
0.06  NaN     0
0.08  NaN     0
0.10  1.6     1
0.12  NaN     0
0.14  NaN     0
0.16  NaN     0
0.18  NaN     0
0.20  1.2     1
0.22  NaN     0
0.24  NaN     0
0.26  NaN     0
0.28  NaN     0

You can then create a modified objective function that uses meas to control when to minimize the simulation and measurement only at the defined points.
m = GEKKO(remote=False)
m.time = df.index.values
x = m.Var(value=x_data[0])     # fit to measurement
xd = m.Param(df0['x'].values)
meas = m.Param(df0['meas'].values)
k = m.FV(); k.STATUS = 1    # adjustable parameter
m.Equation(x.dt()== -k * x) # differential equation
m.Minimize(meas*(x-xd)**2)
m.options.SOLVER = 1  # APOPT solver
m.options.IMODE = 5   # dynamic estimation
m.options.NODES = 2   # collocation nodes
m.solve(disp=True)   # display solver output
k = k.value[0]

A plot shows the results. I included more data points because NODES=2 isn't very accurate. A switch to NODES=3 helps to improve the accuracy much more than adding more points.

import numpy as np
import matplotlib.pyplot as plt  # plot solution
plt.plot(m.time,x.value,'bo',\
         label='Predicted (k='+str(np.round(k,2))+')')
plt.plot(m.time,df['x'].values,'rs',label='Measured')
# plot exact solution
t = np.linspace(0,1); xe = 2*np.exp(-k*t)
plt.plot(t,xe,'k:',label='Exact Solution')
plt.legend()
plt.xlabel('Time'), plt.ylabel('Value')
plt.ylim([-0.2,2.2])
plt.show()


text:
Q: Пропорциональное масштабирование в фигмовском макете Верстаю макет Фигмовский макет. Интересует пропорциональное масштабирование изображения в макете

Также на макете (для полноты картины контента)

Вот что наверстал

.techno-articles {
  margin-top: 104px;
}

.techno-articles__container {}

.techno__block_container {}

.techno-articles__items {}

.techno-article__item {}

.item__techno-article {}

.item__techno-article_example {}

.item__techno-article_content {
  display: flex;
  /*flex-wrap: wrap;
    justify-content: center;
    flex-direction: row;*/
}

@media (max-width: 696px) {
  .item__techno-article_content {
    flex-wrap: wrap;
  }
  .item__techno-article_image {
    flex: 1 1 100%;
  }
  .item__techno-article_body {
    flex: 1 1 100%;
    padding-left: 0;
  }
}

/*
.item__techno-article_image {
    flex: 0 0 calc(735 / 1441 * 100%);
    position: relative;
    padding: 0px 0px calc(550 / 1441 * 100%) 0px;
}
*/

.item__techno-article_image {
  /*
  background-image: url('../img/futurearticlesimages/technoDVD.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  */
  width: 50%;
  display: block;
  position: relative;
  overflow: hidden;
  resize: horizontal;
}

.item__techno-article_image::before {
  content: '';
  display: block;
  width: 100%;
  height: 0;
  padding-top: calc(550 / 1440 * 100%);
}

/*
.item__techno-article_image {
    background-image: url('../img/futurearticlesimages/technoDVD.png');
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    flex: 0 0 calc(735 / 1440 * 100%);
    position: relative;
    padding: 0px 0px calc(550 / 1440 * 100%) 0px;
}
*/

.item__techno-article_image img {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  object-fit: cover;
}

.item__techno-article_body {
  flex: 1 1 auto;
  padding-top: 80px;
  padding-left: calc(96/1441*100vw);
  /*136*/
  padding-right: calc(133/1441*100vw);
  /*110*/
}

.item__techno-article_title {
  color: rgba(77, 83, 60, 1);
  font-family: 'Poppins';
  font-style: normal;
  font-weight: 700;
  font-size: 36px;
  line-height: 48px;
  /* or 133% */
  color: #4D533C;
}

.item__techno-article_text {
  padding-top: 24px;
  color: rgba(33, 56, 66, 0.6);
  font-family: 'Poppins';
  font-style: normal;
  font-weight: 400;
  font-size: 16px;
  line-height: 26px;
  /* or 162% */
  color: rgba(33, 56, 66, 0.6);
}

.item__techno-article_link {
  color: rgba(33, 56, 66, 0.6);
}

.item__techno-article_comment {
  color: #4D533C;
  background-color: #fff;
  box-shadow: 50px 50px 100px rgba(0, 0, 0, 0.145947);
  border-radius: 8px;
  position: relative;
  z-index: 400;
  margin: -158px calc(664/1441*100vw) 0px calc(323/1441*100vw);
  /*604*/
  width: calc(453/1441*100vw);
}

.item__techno-article_comment_ownership {
  display: flex;
  align-items: center;
  padding-left: 30px;
}

.item__techno-article_comment_author_image {
  width: 90px;
  height: 90px;
}

.item__techno-article_comment_text {
  font-family: 'Poppins';
  font-style: italic;
  font-weight: 400;
  font-size: 16px;
  line-height: 26px;
  padding-top: 30px;
  padding-left: 30px;
  padding-right: 33px;
}

.item__techno-article_comment_author {
  font-family: 'Poppins';
  font-style: normal;
  font-weight: 700;
  font-size: 16px;
  line-height: 24px;
}

.item__techno-article_comment_author_position {
  font-family: 'Poppins';
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 21px;
  /* identical to box height */
  color: #152934;
}

.item__techno-article_text>*:not(:last-child) {
  margin-bottom: 36px;
}

.item__techno-article_link {
  margin-top: 90px;
}

The wall new Balenciaga.com

This article is floated online with an aim to help you find the best dvd printing solution.

Dvd printing is an important feature used by large and small DVD production houses to print information on DVDs.

See Case Study

              "In my history of working with trade show vendors, I can honestly say that there is not one company that I've ever worked with that has better service than Exhibit Systems."

Angel Armstrong

Founder & CEO, Google

Подскажите как добиться пропорционального масштабирования вышеуказанного изображения (да и всего контента вместе с текстом) при изменении размеров экрана. Подобный вопрос уже задавался и я пытался применить приведенные методы (см. Масштабирование и Средства пропорицонального масштабирования) в этих вопросах (см. закомментированный css код), но у меня не получилось.
P.S. Желательно, чтобы весь контент пропорционально масштабировался.


text:
Q: Multiple threads to find prime factors of integers, segmentation fault I can't figure out what I am doing wrong with my pointers. It is causing a segmentation fault. I am convinced the problem is rooted in my use of the array of pointers I have and the pthread_join I am using.
The goal is to read multiple integers into a gcc compiler, then print out the integer with all its factors, like this, 12: 2 2 3
I created a struct containing an int array to store the factors of each integer as the factor function pulls it apart and a counter(numfact) to store how many factors there are stored in the array.
I commented out the section at the bottom that prints out the factors.
I think the problem is how I am trying to store the output from the pthread_join in the pointer array, ptr[]. Whenever I comment it out, it does not get the segmentation error.
Either I have my pointers screwed up in a way I don't understand or I can't use an array of pointers. Either way, after many hours, I am stuck.
Please help.
#include <stdio.h>
#include <pthread.h>
#include <math.h>
#include <stdlib.h>

struct intfact
{
    long int factors[100];
    int numfact;
};

struct intfact *factor(long int y)
{
    struct intfact threadfact;
    threadfact.numfact = 0;

        // Store in struct the number of 2s that divide y
        while (y % 2 == 0)
        {
        threadfact.factors[threadfact.numfact] = 2;
        threadfact.numfact++;
            y = y/2;
        }

        // Store in struct the odds that divide y
        for (int i = 3; i <= floor(sqrt(y)); i = i+2)
        {
            while (y % i == 0)
            {
            threadfact.factors[threadfact.numfact] = i;
            threadfact.numfact++;
                y = y/i;
            }
        }

        // Store in struct the primes > 2
        if (y > 2)
    {
        threadfact.factors[threadfact.numfact] = y;
        threadfact.numfact++;
    }
    struct intfact *rtnthred = &threadfact;
    return rtnthred;
}

/* Trial Division Function */
void *divde(void *n)
{
    long int *num = (long int *) n;
    struct intfact *temp = factor(*num);
    return temp;
}

/* Main Function */
int main(int argc, char *argv[])
{
    pthread_t threads[argc-1];
    void *ptr[argc-1];

    /* loop to create all threads */
    for(int i=0; i < argc; i++)
    {
        long temp = atol(argv[i+1]);
        pthread_create(&threads[i], NULL, divde, (void *) temp);
    }

    /* loop to join all threads */
    for(int i=0; i < argc; i++)
    {
        pthread_join(threads[i],(void *) ptr[i]); //THIS POINTER IS THE PROBLEM
    }

    /* loops to print results of each thread using pointer array*/
    //for(int i = 0; i < argc; i++)
    //{
    //  printf("%s: ", argv[i+1]); /* print out initial integer */
    //  struct intfact *temp = (struct intfact *) ptr[i]; //cast void pointer ptr as struct intfact pointer
    //  printf("%d", temp->numfact);
        //for(int j = 0; j < temp->numfact; j++) /*(pull the numfact(count of factors) from the struct intfact pointer??)*/
        //{
        //  printf("%d ", temp->factors[j]); /* print out each factor from thread struct */
        //}
    }

}

In my Linux) terminal this code is stored in p3.c
"./p3 12" should yeild "12: 2 2 3"

A: For starters:
Here
    long temp = atol(argv[i+1]);
    pthread_create(&threads[i], NULL, divde, (void *) temp);

you define a long int and pass it as argument to the thread. For example 12
Inside the thread function then
void *divde(void *n)
{
  long int *num = (long int *) n;

you treat the long int passed in as pointer to long int.
And then here dereference it
    ... = factor(*num);

So this *num for example would become *12. That is referencing memory address 12 to read out its content and pass it to factor). Aside the fact that this mostly likely is an invalid address, there would be nothing relevant store, at least nothing your code defined.
To (more or less fix) this do
void *divde(void *n)
{
  long int num = (long int) n;
 ... = factor(num);

The second issues is mentioned in the comment: Multiple threads to find prime factors of integers, segmentation fault

The problem you are trying to solve is a special case of parallel programming, namely that the tasks to be run in parallel are completely independent. In such cases it makes sense to give each task its own context. Here such a context would include the

*

*thread-id,

*the thread specific input

*as well as its specific output.

In C grouping variables can be done using structures, as your implementation already comes up with for the output of the tasks:
struct intfact
{
  long int factors[100];
  int numfact;
};

So what is missing is thread-id and input. Just add those for example like this.
/* group input and output: */
struct inout
{
  long int input;
  struct intfact output;
};

/* group input/output with thread-id */
struct context
{
  pthread_t thread_id;
  struct inout io;
};

Now before kicking off the threads define as many contexts as needed:
int main(int argc, char *argv[])
{
  size_t num_to_process = argv - 1;
  struct context ctx[num_to_process];

then create the threads passing in what is needed, that is input along with space/memory for the output:
  for (size_t i = 0; i < num_to_process ; i++)
  {
    ctx[i].io.input = atol(argv[i]);
    pthread_create(&ctx[i].thread_id, NULL, divide, &ctx[i].io);
  }

Inside the thread function convert the void-pointer received back to its real type:
void *divide(void * pv)
{
  struct inout * pio = pv; /* No cast needed in C. */

Define the processing function to take a pointer to the context specific input/output variables:
void factor(struct inout * pio) /* No need to return any thing */
{
  /* Initialise the output: */
  pio->output.numfact = 0;

  /* set local copy of input: */
  long int y = pio->input; /* One could also just use pio->input directly. */

Replace all other occurrences of threadfact by pio->output.
Use
  return;
}

to leave the processing function.
Then inside the thread function call the processing function:
  factor(pio);

Use
  return NULL;
}

to leave the thread function.
In main() join without expecting any result from the threads:
  /* loop to join all threads */
  for (size_t i = 0; i < num_to_process; i++)
  {
    pthread_join(ctx[i].thread_id, NULL);
  }

Putting this all together:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <math.h>

struct intfact
{
  long int factors[100];
  size_t numfact;
};

/* group input and output: */
struct inout
{
  long int input;
  struct intfact output;
};

/* group input/output with thread-id */
struct context
{
  pthread_t thread_id;
  struct inout io;
};

void factor(struct inout * pio)
{
  /* Initialise the output: */
  pio->output.numfact = 0;
  /* set local copy of input: */
  long int y = pio->input; /* One could also just use pinout->input directly. */

  if (0 == y)
  {
    return; /* Nothing to do! */
  }

  // Store in struct the number of 2s that divide y
  while (y % 2 == 0)
  {
    pio->output.factors[pio->output.numfact] = 2;
    pio->output.numfact++;
    y = y/2;
  }

  // Store in struct the odds that divide y
  for (int i = 3; i <= floor(sqrt(y)); i = i+2)
  {
    while (y % i == 0)
    {
      pio->output.factors[pio->output.numfact] = i;
      pio->output.numfact++;
      y = y/i;
    }
  }

  // Store in struct the primes > 2
  if (y > 2)
  {
    pio->output.factors[pio->output.numfact] = y;
    pio->output.numfact++;
  }

  return;
}

void *divide(void * pv)
{
  struct inout * pio = pv; /* No cast needed in C. */

  factor(pio);

  return NULL;
}

int main(int argc, char *argv[])
{
  size_t num_to_process = argc - 1;
  struct context ctx[num_to_process];

  for (size_t i = 0; i < num_to_process; i++)
  {
    ctx[i].io.input = atol(argv[i+1]);
    if (!ctx[i].io.input)
    {
      fprintf(stderr, "COnversion to integer failed or 0 for '%s'\n", argv[i]);
    }
    pthread_create(&ctx[i].thread_id, NULL, divide, &ctx[i].io);
  }

  /* loop to join all threads */
  for (size_t i=0; i < num_to_process; i++)
  {
    pthread_join(ctx[i].thread_id, NULL);
  }

  /* loops to print results of each thread using pointer array*/
  for(size_t i = 0; i < num_to_process; i++)
  {
    printf("%ld: ", ctx[i].io.input); /* print out initial integer */
    printf("%zu factors --> ", ctx[i].io.output.numfact);

    for(size_t j = 0; j < ctx[i].io.output.numfact; j++)
    {
      printf("%ld ", ctx[i].io.output.factors[j]); /* print out each factor from thread struct */
    }

    putc('\n', stdout);
  }
}


text:
Q: Extreme values(maximum,minimum is special cases), multivariable calculus We know that $ x,y,z >0$ and $x+y+z=1$
(i)For which $x,y,z$ will be $xyz$ maximum?
(ii)For which $x,y,z$ will be $x^2+y^2+z^2$ minimum?
I still have no idea, how to start the solution of these problems, can I maybe use somehow the Lagrange multiplier method?

A: for (i) use that $$\frac{x+y+z}{3}\geq \sqrt[3]{xyz}$$
for (ii) use that $$\frac{x+y+z}{3}\le \sqrt{\frac{x^2+y^2+z^2}{3}}$$

A: For $(i)$ use  Proofs of AM-GM inequality
For $(ii)$
$$3(x^2+y^2+z^2)-(x+y+z)^2=(x-y)^2+(y-z)^2+(z-x)^2\ge0$$


text:
Q: Access to WCF service with service client generated on different developer computer I work together with a different developer on a WCF service
if the service client reference is generated by the other developer, after I update from SVN and I try to run, the application accessing the service fails with exception:

The caller was not authenticated by the service.
InnerException Message:
  The request for security token could not be satisfied because authentication failed.

I noticed, when the client reference is generated on other pc, in client's app.config I have
<endpoint address="http://MyService.svc/ws"
   binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ISqlService"
   contract="OneTestModel.ISqlService" name="WSHttpBinding_ISqlService">
   <identity>
      <servicePrincipalName value="host/alabala" />
   </identity>
</endpoint>

If I generate/update the client on my pc, I get
      <identity>
        <servicePrincipalName value="host/my-pc-name" />
      </identity>

and I can access the service
Service uses wsHttpBinding, and in it's web.config I have
<bindings>
   <wsHttpBinding>
      <binding name="ConfigBinding">
         <security mode="Message">
            <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"  algorithmSuite="Default" establishSecurityContext="false" />
         </security>
      </binding>
   </wsHttpBinding>
</bindings>

The service is supposed to run anonymously.
What change should I do in service config to ignore client side's <identity>?
Thanks