text:
Q: bytebuddy: annotate already builded class I have super class and some childs of this superclass.
I need annotate superclass as @XmlSeeAlso, that require as param array of child classes.
But for create childs classes, i need loaded super, that not build yet.
Having circle dependency.
It is possible, that build all classes without this annotation, and annotate after that? as next phase, when all classes available, but not annotated?
@XmlSeeAlso(value = {ExtFoo.class, ExtFoo1.class})
class Foo {
    //...
}

class ExtFoo extends Foo {
    //..
}

class ExtFoo1 extends Foo {
    //...
}

public static void main(String[] args) {
    new ByteBuddy()
            .subclass(Object.class)
            .annotateType(new XmlSeeAlso(){

                @Override
                public Class<? extends Annotation> annotationType() {
                    return XmlSeeAlso.class;
                }

                @Override
                public Class[] value() {
                    return new Class[0];//how to get childs of foo classes, when self foo not ready???
                }
            }).make().load(...);
            ....;
}

A: You can use AnnotationDescription.Builder and use TypeDescriptions to represent the types. You can use a TypePool.Default to resolve these descriptions.


text:
Q: why fields like limit and base is separately stored in gdt in os? rt,
for example, in xv6 code mmu.h,
segdesc is designed like this
struct segdesc {
  uint lim_15_0 : 16;  // Low bits of segment limit
  uint base_15_0 : 16; // Low bits of segment base address
  uint base_23_16 : 8; // Middle bits of segment base address
  uint type : 4;       // Segment type (see STS_ constants)
  uint s : 1;          // 0 = system, 1 = application
  uint dpl : 2;        // Descriptor Privilege Level
  uint p : 1;          // Present
  uint lim_19_16 : 4;  // High bits of segment limit
  uint avl : 1;        // Unused (available for software use)
  uint rsv1 : 1;       // Reserved
  uint db : 1;         // 0 = 16-bit segment, 1 = 32-bit segment
  uint g : 1;          // Granularity: limit scaled by 4K when set
  uint base_31_24 : 8; // High bits of segment base address
};

why base is defined as base_15_0, base_23_16, base_31_24, but not 'uint base'?
I guess it's partly due to the fact that each sub-field has special meaning, so store them separately rather than as a whole is convenient for access.
But I'm not sure the guess is complete or right

A: Because it is not an arbitrary nice-to-read internal data structure but exact description of data structure used by the hardware

Source: Intel® 64 and IA-32 Architectures Software Developer Manuals
See also: http://wiki.osdev.org/Global_Descriptor_Table

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multi-website setup. website code in all generated urls I've got several websites running on magento 1.8.1 and I recently noticed something has changed. I have no idea how this change happened, or how long it has been like this. I do know that it was behaving correctly at some point and now it's different.
In the configuration and store management, I set up the following websites with the following website codes:
Website 1:
Name: Site A
Code: site_a
Base URL: httq://site-a,com/

Website 2:
Name: Site B
Code: site_b
Base URL: httq://site-b,com/

Website 3:
Name: Site C
Code: site_c
Base URL: httq://site-c,com/

Now when I visit the sites, the urls that magento is generating look like this:
httq://site-a,com/site_a/product-1.html
httq://site-a,com/site_a/product-2.html

httq://site-b,com/site_b/product-1.html
httq://site-b,com/site_b/product-2.html

httq://site-c,com/site_c/product-1.html
httq://site-c,com/site_c/product-2.html

They should look like this:
httq://site-a,com/product-1.html
httq://site-a,com/product-2.html

httq://site-b,com/product-1.html
httq://site-b,com/product-2.html

httq://site-c,com/product-1.html
httq://site-c,com/product-2.html

Anyone know what might have caused this? Or what I can do to fix it? Maybe just point me in the right direction to start looking and change the code that generates the urls?
ps. sorry the urls look funky, the site wouldn't allow me to post a comment with lots of links. just replace the qs with ps and the commas with periods. you get the idea :)

A: Check this setting out from Magento admin:
System Configuration -> Web -> Url Options -> Add Store Code to Urls

This setting should be set to no.


text:
Q: Dedugging a sort check function in a Linked List Background: it is a Linked List (ordering task for delivery), which involves different shopping carts (Node). i need to write a function to check if the carts are sorted according to the totalprice in the Class ShoppingCart.
My questions are:

*

*Compiler does not have error message, but my function is false. May I know how or where should i change the code?

*Any articles about debugging are recommendable for the beginners?
Thanks for the kindness.
Code as below:
1.
class OrderProcessing {

    var first: OrderNode? = null

    // Node for linked List
    data class OrderNode(val order: Order, var next: OrderNode?)

....

    fun isSorted(): Boolean {
        var run = first
        var sort = false
        while (run != null) {
            if(run.order.shoppingCart.totalPrice  > run.next!!.order.shoppingCart.totalPrice)
                run = run.next
                sort = true
        }
        return sort
    }

2.
  Class ShoppingCart () {
        private val shoppingList = mutableListOf<Pair<Product, Int>>
      // totalprice = sum of item price in each cart
       val totalprice : double
    ... }

3.
  data class Order(
        val shoppingCart: ShoppingCart,
        val address: Address
    )

4.
  fun main(){

        // while loop until "exit", Menu with functions to add goods to cart, clear cart, show shopping list

A: *

*I think in your case you need to start debugging your code and step by step check your program flow.

*You can read this article - https://www.jetbrains.com/help/idea/debugging-code.html, it's about java but anyway it's a good starting point.


text:
Q: Drawing a line on an image I have stuck up in a problem. This question is with respect to processing. I have to draw a scratch on an image using this function

line(pmouseX, pmouseY, mouseX, mouseY);

How do I achieve this? I mean, wherever I draw a scratch, pixel corresponding to that image has to be updated.
Thanks for any assistance

A: I'm not sure what kind of effect do you want to achieve so here is basic usage of drawing line according to mouse position.
PImage  img;    //global variable for storing image

void setup(){
  img = loadImage("image.jpg");    //loading image
  size(img.width, img.height);    //setting size of sketch
}

void draw(){
  image(img, 0, 0);        //each time redraw background with Image

  line(pmouseX, pmouseY, mouseX, mouseY);  //draw line acc to mouse
}

If you want to draw big line just move image() function into setup().
If you want more complicated lines you will have to use mouse events.


text:
Q: How many total order relations on a set $A$? Let's define a set $T_A$ which is the set of all total order relations on $A$.
This set is a subset of the set of all $2$-adic relations on $A$: $$T_A \subset \mathcal P(A^2) $$
1-Which is the cardinality of $T_A$?
2-Which is the standard notation for the set $T_A$?

A: You can do this question yourself. There has to be a unique minimum in the order, then a unique element above that, and so on. So you get a bijection, form a standard chain $I_n$ on $n=\#A$ elements to $A$, which preserves order (you can take $I_n=\{1,\ldots,n\}$ for instance, then $i$ maps to the $i$-th smallest element). Moreover every bijection $f:I_n\to A$ defines a unique total ordering $\leq_f$ on $A$, by the rule $f(x)\leq_f f(y)$ whenever $x\leq y$ in $I_n$.
How many bijections $f:I_n\to A$ are there?

A: Hint: Note if $<$ is a total order on $A$ then for every permutation of $A$, $\pi$, the relation $\{\langle \pi a,\pi b\rangle\mid a<b\}$ is a total order on $A$ as well. In fact it is isomorphic to $<$.
Additional Hint: If $A$ is finite, then there is only one linear order of $A$ (up to isomorphism); if $A$ is infinite then there cannot be more orders than $2^A$, and there are $2^A$ permutations.


text:
Q: How is this interface and class being implemented? I am fairly new in this field.
Here is a code snippet:
JAXBContext jobj = JAXBContext.newInstance(Employee.class);
Marshaller mobj = jobj.createMarshaller();

Employee emp1=new Employee(1,"Jordan",50000);

mobj.marshal(emp1, new FileOutputStream("employee.xml"));

Now I know JAXBContext  is an abstract class and  Marshaller  is an interface.
Now  how can createMarshaller()(Return type Marshaller) return a Marshaller object?  Is JAXBContext implementing Marshaller? Even if implementing then how it is returning the object? Cuz I have tried to implement an Interface in a class and then created a method that returns the object of that Interface but it was throwing error.
Tried to simulate:
Interface:
public interface
 Marshall {

    public Marshall marshaller();

    public int m();

}

Class:
public class JaxB implements Marshall{

    @Override
    public Marshall marshaller() {

        return new Marshall(); //error

    }

    public int m(){
        return 1;
    }

}

Can you please correct my Class?

A: Simply create a method inside that class and add the return statement with the parameters you want to send and then create an object in the Class you want to call the method which will receive the output of the method

A: Here is how to have a method return an instance of an interface:
interface Foo {}

class FooImplementation implements Foo {}

class FooFactory {
    Foo getFoo() {
        return new FooImplementation();
    }
}


text:
Q: How can I run multiple instances of TeamCity on the same server? I am on Windows and trying to run multiple (currently two) instances of TeamCity on the same server. I chose not to install the Windows services and instead run the server via runAll.bat start command. When I ran the installer I chose different ports, names and paths for each one. The first server starts successfully, but the second one does not - I see the tomcat window showing up, but it's gone after a while, though the build agent window stays. Here's some output:
c:\Tools\TeamCity\bin>runAll.bat start
starting TeamCity server and agent...
Using CATALINA_BASE:   "c:\Tools\TeamCity\bin\.."
Using CATALINA_HOME:   "c:\Tools\TeamCity\bin\.."
Using CATALINA_TMPDIR: "c:\Tools\TeamCity\bin\..\temp"
Using JRE_HOME:        "c:\Tools\TeamCity\bin\..\jre"
Using CLASSPATH:       "c:\Tools\TeamCity\bin\..\bin\bootstrap.jar"
Starting TeamCity Build Agent Launcher...
Agent home directory is C:\Tools\TeamCity\buildAgent
Current JRE version is 1.6

c:\Tools\TeamCity\bin>cd c:\Tools\TeamCity2\bin

c:\Tools\TeamCity2\bin>runAll.bat start
starting TeamCity server and agent...
Using CATALINA_BASE:   "c:\Tools\TeamCity2\bin\.."
Using CATALINA_HOME:   "c:\Tools\TeamCity2\bin\.."
Using CATALINA_TMPDIR: "c:\Tools\TeamCity2\bin\..\temp"
Using JRE_HOME:        "c:\Tools\TeamCity2\bin\..\jre"
Using CLASSPATH:       "c:\Tools\TeamCity2\bin\..\bin\bootstrap.jar"
Starting TeamCity Build Agent Launcher...
Agent home directory is C:\Tools\TeamCity2\buildAgent
Current JRE version is 1.6

A: It is possible to make more than one TeamCity server run on the same Windows box as Windows services.
The following procedure assumes you want to install 3 instances of TeamCity named TeamCity1, TeamCity2, and TeamCity3 on ports 8080, 8081, and 8082 respectively. If you change any of these details, make sure you remain consistant with the change throughout the procedure. Each instance MUST run under a different Windows user account for this procedure to work. This was done with TeamCity 7.1, I am not sure if it works with other versions.
Here is the procedure:

*

*Install TeamCity, choose "C:\TeamCity1" as the destination folder.

*Uncheck the Build Agent (both Windows Service and Core) - these will be installed later.

*Uncheck the Windows Service for Server, but leave the Core checked.

*Use "C:\TeamCity1\TeamCityData\" as the configuration directory.

*Choose a unique port for this instance. I chose 8080, 8081, and 8082.

*Repeat steps 1-5 as many times as desired, changing the to TeamCity2, TeamCity3, etc. and changing the port each time.

*Go to Computer Management in Administrative Tools and create 1 unique Windows user account for each service (i.e. TeamCity1, TeamCity2, and TeamCity3). Make sure the passwords do not expire. For now, make sure each user has enough permission to log onto Windows.

*Open an elevated command prompt by going to All programs > Accessories > Command Prompt, right clicking, and choose "Run as Administrator".

*Run the commands at the end of this procedure for each instance of TeamCity, replacing the number 1 with the appropriate TeamCity instance.

*You need to add "Logon as a service" right for each account. The easy way to do this is to open Services from Administrative Tools, right click each service, go to the Log On tab, retype the password in both boxes, and click Apply.

*Logoff the machine and login as "TeamCity1".

*Go to Control Panel > User Accounts > User Accounts > Change my environment variables.

*Add a new User variable by clicking New... Name it TEAMCITY_DATA_PATH with a value of C:\TeamCity1\TeamCityData.

*Repeat steps 11-13 for each instance of TeamCity.

*Logoff and log back in with the Administrator account.

*Go back into the environment variables dialog and delete the System variable (not User variable) named TEAMCITY_DATA_PATH.

*If desired, change the permissions for each TeamCity user account so they do not have permission to log in.

*Open C:\TeamCity1\conf\server.xml and C:\TeamCity1\conf\server-standard.xml and change the server port=8105 to another port of your choosing. Ensure you use the SAME PORT in both files. Repeat for each instance of TeamCity.

*Start each service and connect with your browser to configure the data directory for each one. I had to stop all of the teamcity service instances except the current one or I got a "client not authenticated" error during the build process, but once completed they seem to work okay.

*Configure database access as appropriate.

*Use these instructions to install multiple build agents on the same machine. I don't believe it is possible to share an agent between TeamCity instances as communication is 2-way and there doesn't seem to be a way to configure more than one port, so it is probably best to install the agents to C:\TeamCity1\buildAgent1\ named TeamCity1BuildAgent1, C:\TeamCity1\buildAgent2\ named TeamCity1BuildAgent2, C:\TeamCity2\buildAgent1\ named TeamCity2BuildAgent1, etc.

*If you want to use standard ports for each TeamCity instance (80 and/or 443), follow these instructions to use IIS as a proxy for Tomcat.
Run these commands at step #9 above

sc create TeamCity1 binPath= "\"C:\TeamCity1\bin\TeamCityService.exe\" jetservice \"/settings=C:\TeamCity1\conf\teamcity-server-service.xml\" \"/LogFile=C:\TeamCity1\logs\teamcity-winservice.log\"" DisplayName= "TeamCity Server 1" start= auto obj= ".\TeamCity1" password= "Password1"

sc description "TeamCity1" "JetBrains TeamCity server service 1"

NOTE: teamcity is misspelled as "teamicty" as the name of the config file in some builds.
This is a TeamCity bug, make sure you correct the file name before
executing these commands.

A: You need to edit conf\server.xml for the second Tomcat/TeamCity instance so that it uses different ports or binds to different network interfaces, changing the following ports should be enough:

*

*Server port="8005"

*Connector port="8080"
Two servers cannot share the same database, so you must configure them to use different locations via TEAMCITY_DATA_PATH environment variable.
If you also want to run multiple agents on the same machine, refer to my answer here.


text:
Q: ASP.NET "one time cache" for file I'm trying to implement what I'd call a "one time cache" for specific files in my ASP.NET 3.5 site.  Upon request, the file is downloaded from a remote file server onto the web server, then served up by my page.  The problem arises when I go to delete it.  If I delete the file in the OnUnload method, the client doesn't have time to retrieve it.  Is there some way of detecting the download of a file and deleting it immediately after it is first accessed?  My code is like this:
    private bool _deleteFlag = false;
    private string _deleteFile = string.Empty;

    protected void Page_Load(object sender, EventArgs e) {
        if (!string.IsNullOrEmpty(Request.QueryString["file"])) {
            _deleteFlag = Request.QueryString["file"].Contains(@"cache/");
            _deleteFile = Request.QueryString["file"];
        }
    }

    protected override void OnUnload(EventArgs e) {
        if (_deleteFlag) {
            // Can't delete here; the client is still trying to retrieve it.
            System.IO.File.Delete(Server.MapPath(_deleteFile));
        }
        base.OnUnload(e);
    }

I'm leaning towards writing an IHttpHandler that overrides the file request, but that feels like overkill.

A: Try this:
When you add your file, insert it into the HttpRuntimeCache and set the Key to the FileName and set the TimeOut to say 10 seconds.  Then on the CacheItemRemoved callback, delete the file.  It's not exact, but it should roughly meet your use case.
public static object LoadFile()
{
    var filename = ParseFileNameFromHttpRequest();

    var a = loadFileSomeHow(filename);

    HttpRuntime.Cache.Insert(
        filename ,
        a,
        null,
        System.Web.Caching.Cache.NoAbsoluteExpiration,
        new TimeSpan(0, 0, 0,10,0,0),
        CacheItemPriority.Default,
        new CacheItemRemovedCallback(DeleteFile));

    return a;
}

public void DeleteFile(String key, object value,
    CacheItemRemovedReason removedReason)
{
    File.Delete(key);
}

For more info: http://msdn.microsoft.com/en-us/library/vstudio/7kxdx246(v=vs.100).aspx


text:
Q: MySQL : writing query for relational tables for strict categories I want to write a query that will select me the questions with specific countries ONLY, so when I select questions containing country 1 and 2 show me ONLY questions that have 2 countries and those countries are 1 and 2.
I have 3 tables - questions, countries, questions_has_countries

*

*questions : id, question

*countries : id, name

*questions_has_countries : questions_id, countries_id

I tried :
SELECT q.question, q.id , c.id
FROM questions as q, countries as c,  questions_has_countries as qhc
WHERE c.id = qhc.countries_id
AND qhc.questions_id = q.id
AND c.id IN (1,2)
GROUP BY q.question
HAVING COUNT( qhc.countries_id ) = 2

When i use line 5 ( AND c.id IN (1,2) ) my counter stops working correctly cuz it's narrowing down the search. I know i have to rewrite it but i don't know how. Pls help.

A: remove the WHERE clause and change the HAVING clause into
HAVING  SUM(c.id IN (1,2)) = 2 AND
        COUNT(DISTINCT c.id) = 2

*

*SQLFiddle Demo


text:
Q: Publishing Google Sheet to web as GeoJSON file? I am trying to create a map in Mapbox to be embedded on a website and have the embedded map automatically update every time the source data is updated. I have my source data in a Google sheet and have discovered how to manually convert that into a GeoJSON file and then manually import that file into Mapbox, so that the data populates my map. However, I would like to find a way to automate this process. My proposed solution is that I publish the sheet to the web as a GeoJSON file and then set it to automatically republish whenever changes are made. However, I don't see an option for publishing a sheet as a geoJSON file.
Does anyone know of a script for this?

A: Mapbox publishes something called Geo For Google Docs:
https://github.com/mapbox/geo-googledocs/
It's another google drive script-based solution.
From the repo:

Geo for Google Docs is a set of tools that make it easy to use data from Google Docs Spreadsheets in TileMill, an open source map design studio.
Uses

*

*Export spreadsheet data to GeoJSON Any spreadsheet with geocodes (longitude and latitude coordinates) can be exported to a TileMill-ready file.

It's not entirely automated, meaning you still have to manually download the geojson file (as far as I know you can't use curl or wget directly). But it does at least save a step of converting after downloading.

A: Here are a couple of Python library suggestions you could use to do the task:

*

*Get the data from the Google Spreadsheet
gspread should help you getting the data from the spreadsheet

*Generate a GeoJSON
Fiona will help you to generate the GeoJSON

*Publish the GeoJSON on the web
geojsonio.py will help you to push the GeoJSON to geojson.io
If you combine them nicely you should be able to do your task.

A: You might want to check out Sheetsee.js. It is a client-side library for connecting Google Spreadsheets to a website and visualizing the information in tables, maps and charts. It has a createGeoJSON function for creating geojson from your Google Spreadsheet data. You can also use one of its components, sheetsee-maps, which is built on Mapbox.js.
Using Sheetsee would look something like this:

*

*Link to Sheetsee.js, tabletop.js and jQuery in your HTML head.

*Create a placeholder  in your HTML for the map you want to have.

*Create templates for tables in  tags. This is for the info you want to see in the popups.

*Inside of a  tag initialize Tabletop.js. It waits for the document to load and then initializes tabletop and calls back a function when it has returned with the spreadsheet data.
document.addEventListener('DOMContentLoaded', function() {
 var gData
 var URL = "YOURSPREADSHEETSKEYHERE"
 Tabletop.init( { key: URL, callback: callback, simpleSheet: true } )
})

*Define the function that Tabletop.js calls when it returns with the data. This function will contain all the Sheetsee.js functions that you use for the maps, charts and tables you desire. Style it up with some CSS.
function callback(data) {
 // All the sheetsee things you want to do!
}
You can then just set it and forget it. Now all you need to do is edit the spreadsheet and visitors will get the latest information every time they load the page. Here are some demos and the documentation.
I hope that solves your problem. Good luck!
Disclaimer: I am not the author of the project. I just found it and think it's cool :)

A: I propose you first modify this Google Apps Script to create a URL that parses your Google Sheets into JSON.  Then use Mapbox to load the GeoJSON from the URL you created.
This is an interesting application and I hope you share with the community if you get it working.


text:
Q: inline static member variable struct sa
{
  struct sb { int a = 123;};
  inline static sb b;
};

The above code generates an error:
main.cpp:25:20: error: default member initializer for 'sa::sb::a' required before the end of its enclosing class
   inline static sb b;
                    ^
main.cpp:24:21: note: defined here
   struct sb { int a = 123;};
                     ^~~~~~

Removing the inline keyword or the default member initializer works. But just from the output, I don't understand why this usage is wrong.

A: I think this code is correct and should be accepted;  gcc and clang are erring on the side of caution in order to avoid the defect of Core Issue 1397.
That issue ruled that a program is ill-formed if a NSDMI (non-static data member initializer) causes the class's defaulted default constructor to be generated.
However your code doesn't do that. The NSDMI is just an integer literal.   The example that prompted this issue had code like int a = ( (sa(), 123) );
What I guess might be happening is:  The standard also says that , when processing the NSDMI, the class sa should be treated as complete. So perhaps the compilers are deferring the NSDMI processing until after the closing brace of sa is reached; and then flagging the error because inline static sb b; would generate sb::sb().
Possibly the standard is still defective and nobody thought of your example until now.
As a workaround you can explicitly provide the troublesome constructor:
struct sb { int a = 123; sb() {} };


text:
Q: Displaying error message from backend to the end user in the front end I have a general design based question regarding displaying error message from then backend to the end user in the front end. Not sure where to look for this.
So the error response would be something like this
Error Status: 400 (Bad Request)
{
    value: "+++",
    errorMessage: value "+++" fails to match alpha numeric pattern

}

Now in the front end I don't want to show message directly from the backend. Since it could be of technical nature
(I would log that error message from the backend). I want to display a better user friendly message something like.
"Invalid entry '+++' Numbers and texts are only allowed."

My question is how to go about this. One method I could think of is to return errorType in the response.
I will then check the error type in the front end, and then display message from the front end accordingly.
So my response from the backend would be something like this,
Error Status: 400 (Bad Request)
{
    value: "+++",
    errorMessage: value "++++" fails to match alpha numeric pattern
    errorType: INVALID_PATTERN
}

In the front end I would have some ENUM like
ERROR_TYPES: [
{
    INVALID_PATTERN: "Invalid entry <variable> Numbers and texts are only allowed."
}]

Is this a good approach? What is a best practice for something like this?
If you could provide some references that I could dig deeper into, would be much appreciated.
P.S. I am using the MEAN stack
Thanks


text:
Q: Put image in clipboard from command line I found this on SuperUser, to put text onto the clipboard from the command line:

On Windows, try: echo hello | clip
On Linux, try: echo hello | xclip
On Mac OS X, try: echo hello | pbcopy

Would it be possible to somehow use this same method to put an image on the clipboard?

A: Yes, it would be as simple as:
xclip <img_file

A more difficult question is whether any another application would be able to use the image in its raw file format. Where would you be looking to paste it?


text:
Q: Spot the error in this file reading code (C++) Can anyone please tell my why this method won't compile?
void Statistics::readFromFile(string filename)
{
    string line;
    ifstream myfile (filename);
    if (myfile.is_open())
    {
        while (! myfile.eof() )
        {
            getline (myfile,line);
            cout << line << endl;
        }
        myfile.close();
    }

    else cout << "Unable to open file";

}

Should work, right? Yet, I always get the following error message:

Line Location Statistics.cpp:15: error:
   no matching function for call to
   'std::basic_ifstream<char, std::char_traits<char> >::
      basic_ifstream(std::string*)'

any help would be greatly appreciated.

A: Read the compiler error:
no matching function for call to 'std::basic_ifstream >::basic_ifstream(std::string*)

No matching function for call to: It can't find the function you're trying to call
std::basic_ifstream >:: - a member function of ifstream
:basic_ifstream(std::string*) - the constructor which takes a string pointer as its argument
So you try to create an ifstream by passing a string pointer to its constructor. And it can't find a constructor that accepts such an argument.
Since you're not passing a string pointer in the above, the code you've posted must be different from your actual code. Always copy/paste when asking about code. Typos make it impossible to figure out the problem. In any case, as I recall, the constructor does not accept a string argument, but only a const char*. So filename.c_str() should do the trick
Apart from that, you can do this a lot simpler:
ifstream myfile (filename);
    std::copy(std::istream_itrator<std::string>(myfile),
              std::istream_itrator<std::string>(),
              std::ostream_iterator<std::string>(std::cout));
}

A: The ifstream constructor has the following signature
explicit ifstream ( const char * filename, ios_base::openmode mode = ios_base::in );

You need to pass in a constant char* and a mode, for example:
ifstream ifs ( "test.txt" , ifstream::in );

The mode is optional, since it has a default value defined, so you can just use:
ifstream myfile ( filename.c_str() );

A: You should use fileName.c_str() so that you pass the const char* pointer to the myFile construction.

A: ifstream myfile (filename);

should be:
ifstream myfile (filename.c_str() );

Also, your read-loop logic is wrong. It should be:
while ( getline( myfile,line ) ){
   cout << line << endl;
}

The eof() function that you are using is only meaningful after you have tried to read read something.
To see why this makes a difference, consider the simple code:
int main() {
    string s;
    while( ! cin.eof() ) {
        getline( cin, s );
        cout << "line is  "<< s << endl;
    }
}

If you run this and type ctrl-Z or ctrl-D to indicate EOF immediately, the cout will be performed even though no line has actually been input (because of the EOF). In general, the eof() function is not very useful, and you should instead test the return value of functions like getline() or the stream extraction operators.

A: The C++11 standard has resolved this defect. std::ifstream myfile(filename); should now compile, when filename has type std::string.


text:
Q: Lagrangian transformation
I want to prove that the Lagrangian transformation is covariant for $x_{i}\rightarrow q_{i}(x)$ and $x_{i}\rightarrow q_{i}(x,t)$.

So far I've proven that it holds for the first transformation as follows:
$$\frac{\partial L}{\partial x_{i}}=\frac{\partial \tilde{L}}{\partial q_{a}}\frac{\partial q_{a}}{\partial x_{i}}+\frac{\partial \tilde{L}}{\partial \dot{q}_{a}}\frac{\partial \dot{q}_{a}}{\partial x_{i}}$$
$$\frac{\partial L}{\partial \dot{x}_{i}}=\frac{\partial \tilde{L}}{\partial \dot{q}_{a}}\frac{\partial \dot{q}_{a}}{\partial x_{i}}\Leftrightarrow$$
$$\frac{\partial L}{\partial \dot{x}_{i}}=\frac{\partial \tilde{L}}{\partial \dot{q}_{a}}\frac{\partial q_{a}}{\partial x_{i}}$$
since $\dot{q}_{a}=\frac{\partial q_{a}}{\partial x_{i}}$
If I now try the second transformation ($x_{i}\rightarrow q_{i}(x,t)$) the last relation becomes
$$\dot{q}_{a}=\frac{\partial q_{a}}{\partial x_{i}}\dot{x_{i}}+\frac{\partial q_{a}}{\partial t}$$,
the second equation still holds but I'm not sure if the first equation holds, considering that $x_{a}=x_{a}(q_{i},t)$.
Any help is appreciated.


text:
Q: How to show a messagebox after a specified time? (using WMI) how to show a message box after a specified time?
i want to register a task into CIM. That task show a messagebox.

A: You are choosing the wrong tool for the job, The WMI is not for display messages.


text:
Q: Prove that the given sequence converges Prove that the given sequence $\{a_n\}$ converges:
$a_1 > 0, a_2 > 0$
$a_{n+1} = \frac{2}{a_n + a_{n-1}}$ for $n \geq 2$
As I observed, this sequence does not seem to be monotonic and that it could be bounded since the values of $a_1$ and $a_2$ are arbitrary positive numbers.
If the limit of the sequence existed, it would be equal to 1 by letting the limit of $a_n$ be x as n goes to infinity, and solving the equation x = $\frac{2}{x + x}$ => x = 1 or -1, from which we choose x = 1 since x must be positive.
The only idea that came to my mind is bounding the sequence using two other sequences that could be shown to converge to 1 (Let these sequences be $b_n$ and $c_n$):
$b_n <= a_n <= c_n$
If we could find such sequences,and prove that they converge to 1, the problem would be solved. So, I tried to bound the sequence from both sides, and try to show that the limits are equal to 1, but failed to find such sequences. I found that it is a little difficult to analyze sequences of the form presented in the problem since the sequence fluctuates a lot.
I am not sure how to start off, any ideas or tricks for such problems would be appreciated.

A: We can use the fact that for any $x>1$, if $\frac{1}{x}\leq a,b \leq x$ for some $a\neq b$, then $\frac{1}{x}< \frac{2}{a+b} < x$. This means that subsequent terms of the sequence will also be within the bound given by $\frac{1}{x}$ and $x$.
Now, we need to show that this boundary keeps shrinking as the sequence progresses. This can be argued as follows: For any two consecutive terms, $a_k$ and $a_{k+1}$ in the sequence, this bound will be given by either the pair $a_k,\frac{1}{a_k}$ or $a_{k+1},\frac{1}{a_{k+1}}$ (whichever gives the larger range). For the next two terms, the bound will similarly be given by either $a_{k+2},\frac{1}{a_{k+2}}$ or $a_{k+3},\frac{1}{a_{k+3}}$. However, from the inequality above, both $a_{k+2}$ and $a_{k+3}$ fall within the boundary determined by the previous two terms ($a_k$ and $a_{k+1}$), which means the new range will be smaller than that for $a_k$ and $a_{k+1}$.


text:
Q: Meteor - ViewModel link to collection This part right here is where I'm struggling.
Template.Calculator.viewmodel({
    a: 0,
    b: 0,
    c: 0,
    total: function(){
        return parseInt(this.a(), 10) + parseInt(this.b(), 10) + parseInt(this.c(), 10);
    }
})

instead of having the variables equal 0, how can I have them pull from the collection the value that was saved when either first submitted or after an update occurred? So for example, let's say I saved a as 7 last time and b as 6, it would load the page with a: 6 b:7 c:0 and calculate. I am having the hardest time trying to pull that data from the collection.
Thanks for any help you can provide!

A: There are many ways of doing it.
If you know the data subscription is going to be ready by the time the template is created you can just do:

Template.Calculator.viewmodel(
  function() {
    var dv = DefaultValues.findOne();
    return {
      a: dv.a,
      b: dv.b,
      c: dv.c,
      total: function () {
        return this.a() + this.b() + this.c();
      }
    }
  }
);

If you have many default values you can use the document when you create the view model:

Template.Calculator.viewmodel(
  function() {
    // Add all properties to the view model
    return DefaultValues.findOne(); // or pluck the values
  },
  {
    total: function () {
      // We're assuming the default document will have properties a, b, and c.
      return this.a() + this.b() + this.c();
    }
  }
);

If you don't know when the data is ready then you have the problem of maybe overwriting the user's values. It all depends on where you're subscribing to the data and when the subscription is ready. The following example subscribes when the template is created and updates the values as soon as the data is ready.

Template.Calculator.viewmodel({
  a: 0,
  b: 0,
  c: 0,
  total: function () {
    return this.a() + this.b() + this.c();
  },
  onCreated: function (template) {
    var that = this;
    template.subscribe('defaultData', function(){
      var dv = DefaultValues.findOne();
      that.a(dv.a);
      that.b(dv.b);
      that.c(dv.c);
    })
  }
});

Again, it all depends on how you're getting the data so you might end up doing something different than these.
See Defining View Models for more information.


text:
Q: Subtract 180 days from current date in Angular I'm using a KendoUI for Angular datepicker; to define todays date, I use:
public value: Date = new Date();

What do I do if I want to display the date as todays date, minus 180 days?
This is in typescript/angular 4, etc.. as in my component.ts file:
import { Component, OnInit } from '@angular/core';

@Component({
   selector: 'app-record-filter-from-date',
   template: `

      From Date:
        <kendo-datepicker class="k-widget k-datepicker k-header crowd-control k-input" style="width: 100%;"
            [(ngModel)]="value"
            [format]="'dd-MMM-yyyy'"
            #dateModel="ngModel"
        ></kendo-datepicker>

`,
 styleUrls: ['./record-filter-from-date.component.css']
})

export class RecordFilterFromDateComponent implements OnInit {
  public value: Date = new Date();

  constructor() {

 }

 ngOnInit() {

 }
}

A: JavaScript class Date may be constructed passing milliseconds since 1 January 1970 00:00:00 UTC, so you can use it like:

let date180DaysAgo = new Date(new Date().getTime() - 180 * 24 * 60 * 60 * 1000);
console.log(date180DaysAgo);

180 in the constructor is number of days to subtract, 180 * 24 * 60 * 60 * 1000 gives number of milliseconds within 180 days

A: I very much appreciate the replies from everyone, however, they did not function as expected with KendoUI for Angular. The currently undocumented way to manipulate the date in the Kendo datePicker object is:
You'll require the 'addDays' @progress module:
import { addDays } from '@progress/kendo-date-math';

THEN one can do the math to get the date they are expecting, in this case:
public value: Date = addDays(new Date(), -180);

Plunk: http://plnkr.co/edit/OIiCPfqnu4Nb4knZiPF1?p=preview

A: let today = new Date();
let day = this.today.getDate() - 180;
console.log(day);

A: Use Javascript's Date
var date180 = new Date(date.getTime());
date180.setDate(date.getDate() - 180);


text:
Q: How to set the x position of views in android I am creating a number of imageviews and textviews on runtime depending on the objects in my webservice. I'm creating linearLayout horizontal and adding imageviews and textviews to layout, now the issue is the text are against images, and images are of different width so i want to set x position of my textviews so they all look align how can this be done,
i tried absolutelayout(warning deprecated) , setx(no method showed)

A: I presume you mean this is a vertical LinearLayout, and each text/image combo is added below the previous one? In that case, you could have two LinearLayouts next to each other like two columns, adding the images to one and the text fields to the other. Then the widest image would stretch its layout to that width and all text fields would be just to the right of it.

A: you can use resized image on  runtime based on the pannel height and width for resizing image on runtime view this stack overflow thread
resizing image java getScaledInstance

A: Use weight property in your ImageView and TextView


text:
Q: Сan't handle form propper way In my plugin I'm trying to change the order data ($total particullary) depending on clicking duplicated buttons 'Place order' with custom value and name attributes which are in the form> element of the checkout page.
This  have url of checkout page as value of action attribute in the form-checkout.php file.
So I can't understand where is it processed. Where can obtain theese $_POST variables?
Is it real to imlement it via plugin? How? I will insanely happy for every piece of advice.
Wordpress version - 5.3.2. Woocommerce version - 3.5
<?php
/**
 * Plugin Name: 2buttonsplug
 * Description: Description
 * Plugin URI: http://#
 * Author: Author
 * Author URI: http://#
 */

/*
add_action('admin_post_get_for_price_2','mega_function');
add_action('admin_post_get_for_price_3','mega_function');
function mega_function() {
    global $gj;
    $gj=$_POST['get_for_price_2'];

}
*/
add_action( 'woocommerce_checkout_after_order_review', 'second_place_order_button', 5 );
function second_place_order_button() {
    $order_button_text = 'get_for_price_2';

    echo '<button type="submit" class="button alt" name="get_lucky_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '">' . esc_html( $order_button_text ) . '</button>';
    $order_button_text = 'get_for_price_3';
    echo '<button type="submit" class="button alt" name="get_extra_lucky_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '">' . esc_html( $order_button_text ) . '</button>';

}

//woocommerce_checkout_create_order

add_action( 'woocommerce_checkout_create_order', 'change_total_on_checking', 20, 1 );

function change_total_on_checking( $order ) {
    $total = $order->get_total();
    $new_total = $total * 1.12;
    $order->set_total( $new_total );

}

?>

And form-checkout.php line 32:
<form name="checkout" method="post" class="checkout woocommerce-checkout" action="<?php echo esc_url( wc_get_checkout_url() ); ?>" enctype="multipart/form-data">

A: I cannot yet comment.
From my experience the checkout is processed with a Ajax call to the server. Now I don't believe you can change the total the way you're doing it, since the order doesn't get recreated. If you look at the official Storefront theme you can see a loading animation. This means the order is being validated but it was already created so the woocommerce_checkout_create_order won't be called. You could implement a custom payment gateway.
Secondly, I don't think you can simply set the order total since it can get recalculated based on order items. Also if setting it you should call $order->save(); To save the details.
I recommend you apply a coupon if you're reducing price the price of the order or a fee if increasing it.
You probably could manipulate the order total at the cart page rather than the checkout page. Add your buttons to the cart page and based on that clicked button apply an action to the order.
Note:
in your code you have to specify global $gj outside the mega_function. Also the name of the button is get_lucky_order and get_extra_lucky_order not get_for_price_2 and get_for_price_3
...
global $gj;
$gj=0;
add_action('admin_post_get_for_price_2','mega_function');
add_action('admin_post_get_for_price_3','mega_function');
function mega_function() {
    global $gj;
    $gj=$_POST['get_for_price_2']; // value gets set after the action hook gets called, $gj will not have a new value

}

add_action( 'woocommerce_checkout_after_order_review', 'second_place_order_button', 5 );
function second_place_order_button() {
    $order_button_text = 'get_for_price_2';

    echo '<button type="submit" class="button alt" name="get_lucky_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '">' . esc_html( $order_button_text ) . '</button>';
    $order_button_text = 'get_for_price_3';
    echo '<button type="submit" class="button alt" name="get_extra_lucky_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '">' . esc_html( $order_button_text ) . '</button>';

}

//woocommerce_checkout_create_order

add_action( 'woocommerce_checkout_create_order', 'change_total_on_checking', 20, 1 ); // --> if $gj == 0 this doesn't have a valid callback, change_total_on_checking is never defined
if($gj){ --> this will always be 0 even if global is set, because mega_function is called way after this line of code
function change_total_on_checking( $order ) {
    $total = $order->get_total();
    $new_total = $total * 1.12;
    $order->set_total( $new_total );

}
}

if you need the validation skip the mega function.

add_action( 'woocommerce_checkout_after_order_review', 'second_place_order_button', 5 );
function second_place_order_button() {
    // you know the value don't sanitize it and use esc_html__('get_for_price_2',__YOUR__TEXT_DOMAIN); in case you want translations

echo '<button type="submit" class="button alt" name="get_lucky_order" id="place_order" value="get_for_price_2" data-value="get_for_price_2">' . esc_html__('get_for_price_2', __YOUR__TEXT_DOMAIN ) . '</button>';

    echo '<button type="submit" class="button alt" name="get_extra_lucky_order" id="place_order" value="get_for_price_3" data-value="get_for_price_3">' . esc_html__( 'get_for_price_3', __YOUR__TEXT_DOMAIN ). '</button>';

}

//woocommerce_checkout_create_order
$gj=false;
if(isset($_POST['get_lucky_order'])){ // use the name, not the value
  $gj=$_POST['get_lucky_order'];
} else if(isset($_POST['get_extra_lucky_order'])){
  $gj=$_POST['get_extra_lucky_order'];
}

if($gj){
 add_action( 'woocommerce_checkout_create_order', 'change_total_on_checking', 20, 1 );
 function change_total_on_checking( $order ) {
    $total = $order->get_total();
    $new_total = $total * 1.12;
    $order->set_total( $new_total );
    $order->save();
 }
}

Hope this helps!
EDIT 1:
You can set debugging to true and see what values are actually posted.
/wp-config.php
...
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );

/* That's all, stop editing! Happy publishing. */
...

Now you can use error_log($value);
Look at the /wp-content/debug.log for all the errors and notices
/wp-content/plugings/--your--pluging--/file.php
...
 //woocommerce_checkout_create_order

//add the action hook always
 add_action( 'woocommerce_checkout_create_order', 'change_total_on_checking', 20, 1 );
// might also want to use woocommerce_checkout_update_order_meta instead, since
// after woocommerce_checkout_create_order the order is saved by woocommerce based on the old instance
// not the new one from you
 function change_total_on_checking( $order ) {
  error_log(print_r($_POST,true)); // go to debug.log after checkout update and see what has been returned in the logs
  if(isset($_POST['get_lucky_order'])){
    $total = $order->get_total();
    $new_total = $total * 1.12;
    $order->set_total( $new_total );
    $order->save();
  } else if(isset($_POST['get_extra_lucky_order'])){
    ...
  }
 }
}


text:
Q: Limits as adjoint to constant functors Let us suppose that $C$ is a category where small limits are representable and $D$ is a small category.
Let $F:Hom(D,C)\rightarrow C$ be the functor defined by $F(f)=\varprojlim f$.
Is it true that $F$ has a right adjoint constant functor? Can someone please explain this to me? What about the unit and co-units here?
Also, could someone please suggest me some nice introductory books on this stuff? I am finding it very confusing.

A: No, $F$ has no right adjoint in general, but it has a left adjoint, which sends each object $c$ of $C$ to the constant functor in $\text{Hom}(D,C)$ that sends every object of $D$ to $c$.
I'm probably old-fashioned, but I still think the best introductory book on category theory is Saunders Mac Lane's "Categories for the Working Mathematician".

A: As Andreas already answered, $F$ has no right adjoint in general. Let's see why this is so on a simple example.
Take $C=\mathrm{Set}$, the category of sets and take $D$ a category with two objects, call them $*$ and $**$, and only identity morphisms. Then given an element $f \in \mathrm{Hom}(D, C)$ its limit is simply the product $f(*) \times f(**)$. Now limits and colimits in $\mathrm{Hom}(D, C)$ are given pointwise. Take $f, g : D \to C$ to be the constant $1$ (terminal object in $\mathrm{Set}$) functors. Then $F(f + g) = (1 + 1) \times (1+1)$ which is a set of cardinality $4$. On the other hand $F(f) + F(g) = 1 \times 1 + 1 \times 1$ which is a set of cardinality $2$, thus $F(f + g) \not\cong F(f) + F(g)$.
Now if $F$ were to have a right adjoint it would itself be a left adjoint and left adjoints preserve colimits. $F$ does not preserve colimits, thus it has no right adjoint.
Note however that in a quite a few cases $F$ will preserve colimits and will have a right adjoint.


text:
Q: Efficient way to transform array into encoding for ordinal regression I have this array
import numpy as np
array = np.array([2, 3, 4])

And I would like to map that to
[array([ 1.,  1.,  0.,  0.,  0.]), array([ 1.,  1.,  1.,  0.,  0.]), array([ 1.,  1.,  1.,  1.,  0.])]

This is the best solution I've found so far
def ordinal_array(where_max, array_len=5):
    return np.hstack((np.ones((where_max)), np.zeros((array_len-where_max))))

list(map(ordinal_array,[2,3,4]))

But I would like to know if there's something that scales better since I would like apply this to arrays that have a few million data points.

A: Leverage broadcasting with greater-than outer-comparison of input array against the range of array_len values -
In [14]: array
Out[14]: array([2, 3, 4])

In [15]: array_len = 5

In [16]: (array[:,None] > np.arange(array_len)).astype(float)
Out[16]:
array([[1., 1., 0., 0., 0.],
       [1., 1., 1., 0., 0.],
       [1., 1., 1., 1., 0.]])

With NumPy built-in -
In [23]: np.greater.outer(array, np.arange(array_len)).astype(float)
Out[23]:
array([[1., 1., 0., 0., 0.],
       [1., 1., 1., 0., 0.],
       [1., 1., 1., 1., 0.]])

For performance, consider converting to lower precision int or even keeping the output as boolean array (skip astype conversion for this).

A: I think creating whole matrix in the beginning can make it faster. Look at f2 function below.
import random
import numpy as np

def ordinal_array(where_max, array_len=5):
    return np.hstack((np.ones((where_max)), np.zeros((array_len-where_max))))

def f1(arr):
  return list(map(ordinal_array,arr))

def f2(arr):
  n = len(arr)
  retval = np.zeros((n, 5))
  for i in range(n):
    no = arr[i]
    retval[i, 0:no] = 1
  return list(retval)

a = [random.randint(0, 5) for i in range(100000)]

%timeit f1(a)
%timeit f2(a)

It seems faster for 100000 items.

1 loop, best of 3: 816 ms per loop
10 loops, best of 3: 95.7 ms per loop

It may even possible to reduce for loop in the f2 function.


text:
Q: Loop inside polygon shapefile to clip another shapefile using PyQGIS I'm a beginner in PyQGIS and need help to figure out how to automate a process in QGIS.
I want to write a script that enables me to loop inside a polygon shapefile (shown in brown) and use extent of each polygon to clip another shapefile (shown in yellowish).
Below is what I figured out so far:
    loc_brown= 'D:/Python_Calcs/SHP_PR/brown.shp'
    loc_yellow = 'D:/Python_Calcs/SHP_PR/yellow.shp'

    layer_brown = QgsVectorLayer(loc_brown,'','ogr')
    layer_yellow = QgsVectorLayer(loc_yellow,'','ogr')

            for feat in layer_brown.getFeatures():
                    attrs = feat.attributes()
                    print(attrs[0])
                    clip = processing.run("native:clip",'INPUT':layer_yellow,'OVERLAY':????,'OUTPUT':"D:/Python_Calcs/tmp/"+"clip_"+str(attrs[0])+".shp"})

A: it should be something like this one, it selects every feature before running the algorithm:
loc_brown= 'D:/Python_Calcs/SHP_PR/brown.shp'
loc_yellow = 'D:/Python_Calcs/SHP_PR/yellow.shp'

layer_brown = QgsVectorLayer(loc_brown,'','ogr')
layer_yellow = QgsVectorLayer(loc_yellow,'','ogr')

for feat in layer_brown.getFeatures():
    attrs = feat.attributes()
    print(attrs[0])
    alg_params = {'INPUT': layer_yellow,
            'OVERLAY' : layer_brown,
            'OUTPUT': 'D:/Python_Calcs/tmp/'+'clip_'+str(attrs[0])+'.shp'}
    layer_brown.selectByIds([feat.id()])
    result = processing.run("native:clip", alg_params)


text:
Q: Preselect first option on knockout.js generated radio list I am new to knockout.js and managed to generate a radio button list. But I don't know how to preselect the first radio button on the list. Here is (I think) a excerpt of the important part of the code:
knockout.js:
$.ajax({
    url: '/path/to/external/rest/api/' + zipCode,
    type: 'GET',
    context: document.body
}).done(
    function (response) {
        $.each(response, function(key, droppoint) {
            self.droppoints.push(droppoint);
        });
    }
).fail(

);

HTML:

    <input class="droppoint_radio" type="radio"
           name="droppoint_location"
           data-bind="attr: {value: number}" />

A: You can control a radio button in knockout with the checked binding. You can add an observable selectedPoint that represents the selected radio button and assign this observable the value of the first radio button.
Depending on your javascript, this might look like this:
viewModel.selectedPoint = ko.observable();

Adding the checked binding to the HTML:

        <input class="droppoint_radio" type="radio"
            name="droppoint_location"
            data-bind="attr: {value: number},
            checked: $parents[2].selectedPoint" />

Finally, set the number of the first droppoint as default value in the AJAX callback:
$.ajax({
    url: '/path/to/external/rest/api/' + zipCode,
    type: 'GET',
    context: document.body
}).done(
    function (response) {
        $.each(response, function(key, droppoint) {
            self.droppoints.push(droppoint);
        });
        self.selectedPoint(response[0].number);
    }
)


text:
Q: Ember ember-simple-auth override routeIfAlreadyAuthenticated in application route How do you override the routeIfAlreadyAuthenticated?
And once that happens, how can it transition to a route with a dynamic segment?
I realize I can override sessionAuthenticated; and in that ways override the functionality of routeAfterAuthentication.  However, routeIfAlreadyAuthenticated is a computed property that is executed in a beforeModel in the unauthenticated-route-mixin.js mixin.
Any help would be greatly appreciated.

A: In app/session/route.js, just do:
import Ember from 'ember';
import UnauthenticatedRouteMixin from 'ember-simple-auth/mixins/unauthenticated-route-mixin';

export default Ember.Route.extend(UnauthenticatedRouteMixin, {
  routeIfAlreadyAuthenticated: 'dashboard'
});

and it works, no more:

Error while processing route: session.login Assertion Failed: The route index was not found Error

The following works as well, but is deprecated
In config/environment.js:
var ENV = {
   ...
};

ENV['ember-simple-auth'] = {
   // authenticationRoute:          'login',
   // routeAfterAuthentication:     'dashboard',
   routeIfAlreadyAuthenticated:  'dashboard'
};


text:
Q: Prove that there is a solution to a Cauchy problem on a given segment.
There's a Cauchy problem:
  $$
y'=x+y^3,\ \ y(0)=0
$$
  Prove that there is a solution to this problem on the segment $\left[-\frac{1}{2},\frac{1}{2}\right]$

First, I tried to solve the given differential equation. But I got stuck, since the equation is non-linear. So, I thought that there must be a differet approach to this problem.
Could anyone give me a hint how I can deal with this task?

A: On the box $[-a,a]\times[-b,b]$, $a=\frac12$, the function value of the right side has a bound of $M=a+b^3$ and a Lipschitz constant $L=3b^2$.
The growth bound condition $Ma\le b$ and the contraction condition $La<1$, which written out are
$$
\frac12+b^3\le 2b ~\text{ and }~ b^2<\frac23,
$$
can be satisfied for $b=\frac13$. So indeed a solution exists on this interval.
This same method can be used to get larger intervals,
$$
a^2+ab^3\le b\land 3ab^2\le 1
$$
can still be satisfied with $a=b=\frac23$.
The numerical solution shows a pole at about $x=1.6475$


text:
Q: Learn Python the Hard Way - EX 41 - Invalid Syntax I keep receiving SyntaxError message on ex41.py OR oop_test.py, and I've run through the whole script, everything is exactly as it is in the book, but I keep getting this - the variable {answer} is seemingly only defined in the try: section, so I have no clue why I am getting this SyntaxError.
***:hardway ***$ python ex41.py english
  File "ex41.py", line 76
    print(f"ANSWER: {answer}\n\n")
                                ^
SyntaxError: invalid syntax
Here is the try: section, where the variable is at:
try:
    while True:
        snippets = list(PHRASES.keys())
        random.shuffle(snippets)

        for snippet in snippets:
            phrase = PHRASES[snippet]
            question, answer = convert(snippet, phrase)
            if PHRASE_FIRST:
                question, answer = answer, question

            print(question)

            input("> ")
            print(f"ANSWER: {answer}\n\n")

except EOFError:
    print("\nBye") `

The entirety of the code can be found here: Learning Python The hard way Ex. 41 - Learning to Speak Object-Oriented

A: Your code looks fine.  The problem is the Python version you are running.
As mentioned in the comments above f strings were first introduced in Python 3.6 (see official documentation). If you want to use this feature you need to update to Python 3.6.
If you do not (or cannot) switch version you can use format() instead:
  print("ANSWER: {}\n\n".format(answer))

OR use the old style %s (formatting string) operator:
  print("ANSWER: %s\n\n" %answer)

See: What does %s mean in Python?
I would suggest format() over the second method though.
If you are making code that will be run on Python versions before Python 3.6 it it a good idea to use the alternatives listed above.


text:
Q: excel vba userforms: user-defined type not defined My Excel book contains a user form called myUserForm.
I want to open it, fill it with data and programmatically press its buttons, but
Sub myUserFormShow()
 Dim muf As myUserForm
 muf.Show
End Sub

prompts an error User-defined type not defined. How to fix it? Thanks.

A: Use this code:
Sub myUserFormShow()
 myUserForm.Show
End Sub


text:
Q: Display some values in string Angular/Typescript I have json format like that. How can I display hobbies without the word "all" in Angular/TypeScript?
 {
    "Name": "Mustermann1",
    "Vorname": "Max1",
    "maennlich": true,
    "Hobbys": ["Reiten", "Golfen", "Lesen", "all"],
    "Alter": 42,
    "Kinder": [],
    "Partner": null
 }
 {
    "Name": "Mustermann2",
    "Vorname": "Max2",
    "maennlich": true,
    "Hobbys": ["Reiten", "Golfen", "Lesen"],
    "Alter": 42,
    "Kinder": [],
    "Partner": null
 }
 {
    "Name": "Mustermann3",
    "Vorname": "Max3",
    "maennlich": true,
    "Hobbys": ["Reiten", "Lesen", "all"],
    "Alter": 42,
    "Kinder": [],
    "Partner": null
  }

A: You can do it with two *ngFor loops and one *ngIf in your HTML, given that you have the data coming from your component. It might not be the ideal way to do it.
You loop through each person and each hobby to show, and filter out any hobby that is 'all'.
<ng-container *ngIf="hobby !== 'all'">
    {{ hobby }}
</ng-container>

A quick setup:
<ng-container *ngFor="let person of dataObject">

Name: {{ person.Vorname }}

      <ng-container *ngFor="let hobby of person.Hobbys">
        <ng-container *ngIf="hobby !== 'all'">
          {{ hobby }}
        </ng-container>
      </ng-container>

</ng-container>

And a working StackBlitz to validate your needs.

A: data = data.map((val) => {
      val.Hobbys = val.Hobbys.filter((x) => x !== 'all');
      return val;
    });

A: <ng-container *ngFor="let item of items">
  <ng-container *ngIf="item.Hobbys.indexOf('all') < 0">

        {{ item.Name }}

  </ng-container>
</ng-container>

stackblitz code link


text:
Q: Python 3, Problem with byteorder/wordorder output from packing Using:
Python 3, Endian, BinaryPayloadBuilder
Edit: This may be a known bug in pyModbus. I have heard mention of a similar problem with the byteorder-wordorder functions. For the time being, I have solved this with brute force coding and my payloads are working fine.
I have a problem with the BinaryPayloadBuilder output. I am trying to reproduce the correct byte order for a ModbusTCP transmission but the builder is giving me an unexpected result. I used Wireshark to sniff the proper order and tried to build the same message with python. The correct structure appears to be byteorder=Big.Endian, wordorder=Little.Endian according to the sniff but putting those setting into the builder doesn't change the output.
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadBuilder

def run_binary_payload_ex():
    print()
    builder = BinaryPayloadBuilder(byteorder=Endian.Big, wordorder=Endian.Little)
    bStrng = "<ID 30><CLR>"
    builder.add_string(bStrng)
    payload = builder.to_registers()
    print(payload)
    print("\n")
    payload = builder.build()
    print(payload)

if __name__ == "__main__":
    run_binary_payload_ex()

Output:
[15433, 17440, 13104, 15932, 17228, 21054]

[b'<I', b'D ', b'30', b'><', b'CL', b'R>']

but I expected:
18748,  8260,  12339,  15422,  19523,  15954

[b'I<',  b' D',  b'03',  b'<>',  b'LC',  b'<R']

Bit order should be swapped for each pair. Can someone show me what I'm doing wrong?


text:
Q: What extensions affect the fingerprint ja3? Many articles mention that the ja3 fingerprint depends on extensions. For example,
https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967/
Where can I find a list of extensions that affect the fingerprint?

A: All extensions affect ja3.
Details: https://scrapfly.io/blog/how-to-avoid-web-scraping-blocking-tls/


text:
Q: ASP.NET Response.Redirect URL parameter through ReverseProxy We have a web-based application that uses Response.Redirect

e.g. Response.Redirect("http://app_domain.com/userhome.aspx")

to redirect the web-browser to an appropriate home page right after form-based authentication. This works fine when the client and server are on the same network.
We have a use-case where this application needs to be accessed externally via a reverse proxy (we're using EZProxy). So the web-browser connects to the reverse proxy and the reverse proxy connects to the application server. In this case, the reverse proxy re-writes all requests and responses. The URL in the web-browser's address bar is something like http://app_domain.com.reverseproxy.com/. The user is able to browser to the sign-in page, put in the credentials and click the sign-in button. However, it seems that the Response.Redirect right after successful sign-in breaks the flow by redirecting the browser to http://app_domain.com/userhome.aspx. The browser cannot connect to this domain directly because it is behind a firewall.
This question is similar to Response.Redirect in ASP.NET AJAX calls. However I see that question doesn't have a satisfactory answer.
Is it possible to use relative paths like

Request.Redirect("~/Userhome.aspx")

or does that get resolved on the server-side before passing to the browser?
The desired outcome would be a redirection mechanism that would take into account the domain / url present in the web-browsers address bar.
Using fiddler, this is what I see. That last redirect is not reverse-proxy friendly.

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/plain; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.0
Set-Cookie: .ASPXAUTH=BE3D7796245FEEA18FF92C9BD4B3F68F08C9E22CA209A139FBDC45BD6633788E6E68EE30F2BAE7EB223CA8F492FA93DFE7AB2723A848C6E75DF87B613075AF418D517921E81B2741224D702B9; path=/; HttpOnly
Set-Cookie: .ASPXAUTH=693B8AC69ABB53F7468466C6D10C9BF5BAFB860F76FC557E3DAD9C733223957E3A46FF8E21E6822CD5420F1724C61809DC83FDE7C8E3DF9D4E972E61F7DDEE05C61E8D8AA97107B5B68412AFC347; path=/; HttpOnly
X-Powered-By: ASP.NET
Date: Fri, 15 Jun 2012 20:41:32 GMT
Content-Length: 64
46|pageRedirect||http://app_domain.com/UserHome.aspx|


text:
Q: hibernate secondary table with one to many relationship One of our goals is to follow the object oriented design and come up with business objects and then take the trouble to create the appropriate mappings for the persistence. It seems to work for most part, but I am getting stuck in the following scenario:
Rule table
RuleId (PK),
name,
Desc,
Type
RuleDetail table
RuleDetailId (PK),
RuleId (FK),
Type,
StartDate,
EndDate
....10 other columns
The important thing here is that these objects follow an inheritence relationship (governed by Type) and one to many between the Rule and RuleDetail.
@Entity
@Table(name="RULE")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name = "TYPE",
    discriminatorType=DiscriminatorType.INTEGER
)
@SecondaryTable(name="RULE_DETAIL", pkJoinColumns={
    @PrimaryKeyJoinColumn(name="id", referencedColumnName="RULEID")})
public abstract class RuleBO extends BaseBO<Long> implements IRuleBO {
    @Id @Column(name = "RULEID")
    private Long id;
    @Column(name="name")
    private String name;
    @Column(name = "desc")
    private String desc;
    @Enumerated(EnumType.ORDINAL)
    @Column(name= "TYPE")
    private RuleType type;

    @Embedded
    @Column(table="RULE_DETAIL")
    private Effectivity effectivity;

    @Column(name="AMOUNT", table="RULE_DETAIL")
    private Double Amt;
    @Column(name="PERCENTAGE", table="RULE_DETAIL")
    private Double percentage;

    @Column(name="PERCENTAGEOF", table="RULE_DETAIL")
    private Integer percentageOf;

    ......specify all the remaining columns
}

I am struggling to come up with where to specify the OneToMany relationship. Should I specify for all the secondary table columns or just the foreign key column? I am not even sure if this approach is going to work.
When I create multiple BOs and use the join criteria, it works as expected, but I was given the challenge to make it work with just one BO and am struggling to make it work. Can someone please guide me in the right direction? At a basic level, secondary table seems straight forward, but I dont know if I am over complicating the solution. I am not sure if I can specify the ID on the secondary table as well. Any help is greatly appreciated.

A: I would not join across the tables in Hibernate like that as you're forcing a 1:1 as the parent class RuleBO has precisely one instance of "Amount", "Percentage" and "percentageOf" which is in the child table (which you want to be 1:n).
Instead, create a RuleDetail class and map it back onto the RuleBO class using the @OneToMany annotation.
Also, don't abbreviate variables and be consistent in your use of camelCase (i.e. use "amount" not "Amt")
private List<RuleDetailBO> ruleDetails;

@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="ruleid")
public List<RuleDetailBO> getRuleDetails() {
    return ruleDetails;
}


text:
Q: Convert two string to the same byte length I have 2 strings in my PHP code, 1 is a parameter to my method and 1 is a string from an ini file.
The problem is that they are not equal, although they have the same content, probably due to encoding issues. When using var_dump, it is reported that the first string's lenght is 23 and the second string's length is 47 (see the end of my question for the reason behind this)
How can i make sure they are both encoded the same way and have the same length in the end so comparison won't fail? Preferably, i would like them to be utf8 encoded.
For reference, this is an excerpt from the code:
static function getString($keyword,$file) {

$lang_handle = parse_ini_file($file, true);

var_dump($keyword);
    foreach ($lang_handle as $key => $value) {
        var_dump($key);
        if ($key == $keyword) {
            foreach ($value as $subkey => $subvalue) {
                var_dump("\t" . $subkey . " => " . $subvalue);
            }
        }
    }
}

with the following ini:
[clientcockpit/login.php]
header = "Kunden Login"
username = "Benutzername"
password = "Passwort"
forgot = "Passwort vergessen"
login = "Login"

When calling the method with getString("clientcockpit/login.php", "inifile.ini") the output is:
string 'clientcockpit/login.php' (length=23)
string '�c�l�i�e�n�t�c�o�c�k�p�i�t�/�l�o�g�i�n�.�p�h�p�' (length=47)

A: Your INI file seems to be in UTF16 encoding or similar, using two bytes to represent a single character. I guess that the strange characters in your string are actually NULL bytes (\0).
PHP's Unicode support is quite poor and I guess that parse_ini_file() does not support multibyte encodings properly. It will treat the file as if it was encoded using a "ASCII-compatible" single-byte encoding, just looking for special characters [ and ] to detect sections. As a result, the section keys will be corrupted: One byte actually belonging to [ or ] will be part of the section key:

UTF-16:    [c]    (3 characters, 6 bytes)

For UTF-16BE (big endian):

  Bytes:    00 5B    00 63    00 5D    (6 bytes)
  ASCII:    \0  [    \0  c    \0  ]    (6 characters)

For UTF-16LE (little endian):

  Bytes:    5B 00    63 00    5D 00    (6 bytes)
  ASCII:    [  \0    c  \0    ]  \0    (6 characters)

Assuming ASCII, instead of reading c, parse_ini_file() will read \0c\0 if the source file encoding is UTF-16.
If you can control the format of your INI file, make sure to save it in UTF8 or ISO-8859-1 encoding, using your favorite text editor.
Otherwise you will have to read in the file contents using file_get_contents(), do the encoding conversion (eg. using iconv()) and pass the result to parse_ini_string(). The drawback here is that you will have to detect or hardcode the original file encoding.
If the mb multibyte extension is available on your PHP installation, you can use mb_detect_encoding() and mb_convert_encoding() to do the conversion dynamically.

A: Try this:
$lang_handle = parse_ini_string(file_get_contents($file), true);


text:
Q: Place a BitmapIcon in an Ellipse Element in UWP app In my UWP app, I wish to place a Bitmap Icon inside an Ellipse element. Is there any way to achieve this using the Fill property of the Ellipse, or any other way which allows me to achieve this?
I wish to use Bitmap Icon only because I need to change the colour of the icon using the Foreground property. Is there any way I can create an ImageBrush using a BitmapIcon because this would allow me to fill the Ellipse with an ImageBrush and would help me achieve the UI descibed.

A: Ellipse is a Shape object, hence cannot have content or children. But if you want to place your BitmapIcon inside an elliptic Control, then I think you should use the Border Control.
The Border control has CornerRadius property. Using that, you can turn it's shape into an elliptic one, or even a circle :

The output above was achieved with this code:
<Border
    Width="200"
    Height="200"
    CornerRadius="100"
    BorderBrush="White"
    BorderThickness="1">

    <BitmapIcon
        UriSource="ms-appx:///Assets/StoreLogo.png"
        Foreground="DodgerBlue"/>

</Border>

Does that satisfy your need?


text:
Q: A Problem with download a files from SFTP ? (exception Unhandled) I am trying to download the files or to make download automatically from SFTP into my local drive but i am getting this erro exception Unhandled : Renci.SshNet.Common.SftpPathNotFoundException: 'No such file'.
which i didn't understand it is  "Path to file on SFTP server"
string Host = "***";
int Port = ***;
string RemoteFileName = @"C:\Users\b.omran\Documents\SFTPFiles.gz";
string pathLocalFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "download_sftp_file.txt");
string Username = "**";
string Password = "****";

using (var sftp = new SftpClient(Host, Port, Username, Password))
{
    sftp.Connect();

    using (Stream fileStream = File.Create(pathLocalFile))
    {
        sftp.DownloadFile(RemoteFileName, fileStream);
    }

    sftp.Disconnect();
}

A: You can create an absolute path using client's property:
string relativePath = "testdir/test.dat";
string absolutePath = Path.Combine(sftp.WorkingDirectory, relativePath);


text:
Q: ¿como pasar de un panel a otro con un botón? Buenas tengo un formulario con una clase persona una clase formulario con un array lito un Jframe formulario y un Jframe para el toString de formularios.
Entonces mi idea es la siguiente yo tengo un panel donde hay 2 botones agregar usuario y otro ver usuarios.
Soy muy nuevo en Jframe y no tengo demasiada idea. Como hago para que se abra el panel de agregar usuarios al darle clic a ese botón?
Esta es mi Jframe de formulario para que os hagáis una idea
public class InterfazToString extends javax.swing.JFrame {

    /**
     * Creates new form InterfazToString
     */
    Formulario f;

    public InterfazToString() {
        try {
            f = deserializa();
        } catch (Exception ex) {
            String mensaje = "No existe el archivo txt";
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        txtToString = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        txtToString.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtToStringActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(txtToString, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(txtToString, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(35, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void txtToStringActionPerformed(java.awt.event.ActionEvent evt) {
       f.toString();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(InterfazToString.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(InterfazToString.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(InterfazToString.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(InterfazToString.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new InterfazToString().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JTextField txtToString;
    // End of variables declaration

    public static Formulario deserializa() {
        FileInputStream miFis = null;
        ObjectInputStream miOis = null;
        Formulario f = null;
        try {
            String miFichero = "PilaDePartes.dat";
            miFis = new FileInputStream(miFichero);
            miOis = new ObjectInputStream(miFis);
            boolean seguir = true;
            while (seguir) {
                try {
                    f = (Formulario) miOis.readObject();

                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(InterfazFormulario.class
                            .getName()).log(Level.SEVERE, null, ex);
                } catch (EOFException endOfFileException) {
                    seguir = false;

                } catch (IOException ex) {
                    Logger.getLogger(InterfazFormulario.class
                            .getName()).log(Level.SEVERE, null, ex);
                }
            }
            miOis.close();
            miFis.close();

        } catch (IOException ex) {
            Logger.getLogger(InterfazFormulario.class
                    .getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                miFis.close();

            } catch (IOException ex) {
                Logger.getLogger(InterfazFormulario.class
                        .getName()).log(Level.SEVERE, null, ex);
            }
            try {
                miOis.close();

            } catch (IOException ex) {
                Logger.getLogger(InterfazFormulario.class
                        .getName()).log(Level.SEVERE, null, ex);
            }
        }
        return f;
    }
}

Muchas gracias

A: Con este codigo habres cualquier formulario    dentro del panel solo manda a llamar el metodo y mandale el formulario que quieres abrir
ejemplo:
    private void Cliente_Click(object sender, EventArgs e)//boton cliente
    {
        InsertPanel(new Agregarliente());//AgregarCliente es el nombre de un formulario
    }

    private void InsertPanel(Object form)//metodo parametrico que recibe un objeto de tipo formulario
    {
        try//se coloca un try-catch por el hecho de que si hay errores
        {
            abrecliente.Visible = false; //abrecliente es el nombre de otro panel que tiene 3 botone (no le tomes importancia)
            if (this.panel4.Controls.Count > 0)//se lee como: si el panel 4 tiene algun contenido entonces...(el panel4 es donde abro los formularios)
                this.panel4.Controls.RemoveAt(0);//se remueve lo que tiene adentro(esto mas que nada es para que no se sobreponga un mismo panel que abras dos veces)
            Form AC = form as Form;//se crea una variable de tipo formulario (que se utiliza para asignarle el objeto que esta recibiendo).
            AC.TopLevel = false;//quita el componente de minimizar, maximizar, cerrar del formulario que se esta abriendo.
            AC.Parent = panel4;//esta colocando el formulario en el panel
            AC.FormBorderStyle = FormBorderStyle.None;//se asigna el borde que tendra
            AC.Dock = DockStyle.Fill;//que sea fijo
            AC.Location = new Point(186, 40);//la posicion de donde va a comenzar el formulario.
            AC.Show();//se abre el formulario en el panel
            panel4.Visible = true;//se muestra el panel (con el formulario ya puesto)
            abrecliente.Visible = false;//ignoralo
            abrirpoliza.Visible = false;//ignoralo
            abrirherramientas.Visible = false;//ignoralo (ya que son 3 paneles mas donde guardo botones para mi menu)
        }
        catch(Exception ex)
        {
            MessageBox.Show("Surgio un error " + ex);
        }
    }

Es lo que te entendi que quieres... y si quieres abrir el panel como tal, te recomiendo que ocultes primero el panel, despues lo llenes y despues de llenarlo lo pongas visible


text:
Q: Django Model Form is not validating the BooleanField In my model the validation is not validating for the boolean field, only one time product_field need to be checked , if two time checked raise

product_field = models.BooleanField(default=False)
product_field_count = 0
        for row in range(0,product_field_count):
            if self.data.getlist(f'product_info_set-{row}-product_field'):
                product_field_count += 1
                if product_field_count  <= 1:
                    raise ValidationError(
                        _(
                           " Need to Be Select Once"
                        ))

validation error.

A: You can tidy up the check a little with sum(iterable, /, start=0):
product_field_name_count = sum(
    [
        True
        for row in range(0, product_field_count)
        if self.data.getlist(f"product_info_set-{row}-product_field") is not None
    ]
)

if product_field_name_count > 1:
    raise ValidationError(
        'Only one item of this type may be selected'
    )

If you're finding this isn't working as expected, you may want to add print() to assure underlying assumptions about where certain variables are correct.
import pprint
pprint.pprint(self)
pprint.pprint(self.__dict__)
pprint.pprint(self.data)


text:
Q: EXTJS editor datefield not rendered after add it to grid When I add an editor with datefield as Xtype to my grid, the datefield does not render.
My problem is that I have to validate a daterange based on two dates. When I click in one of the dafields check the value of the other picker, but I can not get the value of the other datefield because is not render (the datefield renders after click it).
Moreover, if the validator crashes with the undefined, the datefield gets mad and the position on the DOM changes randomly.
The code is something like this:
{ xtype: 'form',
defaults: {
     labelAlign: 'top',
     width: '95%'
},
items: [
     Ext.create('Ext.grid.Panel', {
          id: '<the id>',
          selModel: Ext.create('Ext.selection.CheckboxModel', {
              singleSelect: false,
              sortable: false,
              checkOnly: true
          }),
          store: myStore,
          plugins: {
              ptype: 'celledititing',
              pluginId: 'celledit',
          },
          columns: [
              { text: 'Field 1', dataIndex: 'FIELD_1', width: '25%' },
              { text: 'Field 2', dataIndex: 'FIELD_2', width: '25%' },
              { text: 'Date 1', dataIndex: 'DATE_1', width: '25%',
                renderer: Ext.util.Format.dateRenderer('d/m/Y'),
                editor: {
                     xtype: 'datefield',
                     id: '<date id>',
                     vtype: 'daterange',
                     endDateField: '<date 2 id>',
                     dateRangeMin: '',
                     flex: 1
               },
               { text: 'Date 2', dataIndex: 'DATE_2', width: '25%',
                 renderer: Ext.util.Format.dateRenderer('d/m/Y'),
                 editor: {
                     xtype: 'datefield',
                     id: '<date 2 id>',
                     vtype: 'daterange',
                     startDateField: '<date id>',
                     dateRangeMin: '',
                     flex: 1
               }
          ],
          plugins: {
              ptype: 'cellediting',
              clicksToEdit: 1
          },
          height: 200
      })
      ]
 }

Greetings-

A: You are right. you cannot get value from other datefield because it is not rendered, you can save field in grid's property and validate it manually on grid's validateedit event. here is almost ready snippet, you just need to add your validate logic in grid's validateedit listener

var myStore = Ext.create('Ext.data.Store', {

    data: [{
        FIELD_1: 'voluptas',
        FIELD_2: 'consequatur',
        DATE_1: '12/15/2013',
        DATE_2: '4/18/2008'
    }, {
        FIELD_1: 'eveniet',
        FIELD_2: 'modi',
        DATE_1: '4/7/2008',
        DATE_2: '7/26/2004'
    }, {
        FIELD_1: 'ea',
        FIELD_2: 'voluptas',
        DATE_1: '7/3/2012',
        DATE_2: '9/2/2008'
    }, {
        FIELD_1: 'minima',
        FIELD_2: 'iste',
        DATE_1: '3/3/2002',
        DATE_2: '7/15/2013'
    }, {
        FIELD_1: 'consequatur',
        FIELD_2: 'beatae',
        DATE_1: '3/3/2013',
        DATE_2: '10/20/2014'
    }],
    fields: [{
        name: 'FIELD_1'
    }, {
        name: 'FIELD_2'
    }, {
        name: 'DATE_1',
        type: 'date'
    }, {
        name: 'DATE_2',
        type: 'date'
    }]
});

Ext.create("Ext.panel.Panel", {
    title: "test",
    renderTo: Ext.getBody(),
    items: [{
        xtype: 'form',
        defaults: {
            labelAlign: 'top',
            width: '95%'
        },
        items: [
            Ext.create('Ext.grid.Panel', {
                id: '<the id>',
                selModel: Ext.create('Ext.selection.CheckboxModel', {
                    singleSelect: false,
                    sortable: false,
                    checkOnly: true
                }),
                store: myStore,
                plugins: {
                    ptype: 'celledititing',
                    pluginId: 'celledit',
                },
                parseDate: function(value) {
                    var me = this,
                        val = value,
                        altFormats = me.altFormats,
                        altFormatsArray = me.altFormatsArray,
                        i = 0,
                        len;

                    if (value && !Ext.isDate(value)) {
                        val = me.safeParse(value, me.format);

                        if (!val && altFormats) {
                            altFormatsArray = altFormatsArray || altFormats.split('|');
                            len = altFormatsArray.length;
                            for (; i < len && !val; ++i) {
                                val = me.safeParse(value, altFormatsArray[i]);
                            }
                        }
                    }

                    // If configured to snap, snap resulting parsed Date to the closest increment.
                    if (val && me.snapToIncrement) {
                        val = new Date(Ext.Number.snap(val.getTime(), me.increment * 60 * 1000));
                    }
                    return val;
                },
                listeners: {
                    validateedit: {
                        fn: function(editor, e) {
                            var grid = editor.grid;
                            var date = grid.parseDate(e.value);

                            if(e.field=="DATE_1"){
                              field = grid.startField
                            }else{
                              field = grid.endField
                            }
                            if (!date) {
                                return false;
                            }
                            ///// validate your Fields HERE

                            return true;
                        }
                    }
                },
                startField: null,
                endField: null,
                    columns: [{
                              text: 'Field 1',
                              dataIndex: 'FIELD_1',
                              width: '25%'
                          }, {
                              text: 'Field 2',
                              dataIndex: 'FIELD_2',
                              width: '25%'
                          }, {
                              text: 'Date 1',
                              dataIndex: 'DATE_1',
                              width: '25%',
                              renderer: Ext.util.Format.dateRenderer('d/m/Y'),
                              editor: new Ext.create("Ext.form.field.Date",{
                                xtype: 'datefield',
                                id: '<date id>',
                                dateRangeMin: '',
                                flex: 1,
                                listeners: {
                                    change: function(field) {
                                        this.up("gridpanel").startField = field;
                                    }
                                },
                              })
                          }, {
                              text: 'Date 2',
                              dataIndex: 'DATE_2',
                              width: '25%',
                              renderer: Ext.util.Format.dateRenderer('d/m/Y'),
                              editor: {
                                  xtype: 'datefield',
                                  id: '<date 2 id>',
                                  dateRangeMin: '',
                                  dateRangeMax:'',
                                  flex: 1,
                                  listeners: {
                                      change: function(field) {
                                          this.up("gridpanel").endField = field;
                                      }
                                  }
                              }
                          }],

                plugins: {
                    ptype: 'cellediting',
                    clicksToEdit: 1
                },
                height: 200
            })
        ]
    }]
})
<html>
  <head>
    <link rel="stylesheet" href="https://cdn.sencha.com/ext/gpl/4.2.0/resources/css/ext-all.css">

    <script src="https://cdn.sencha.com/ext/gpl/4.2.0/ext-all-dev.js"></script>

    </head>
  </html>


text:
Q: How often should I/do you make commits? I am a recent (as of yesterday) college grad - BS in Computer Science. I've been a huge fan of version control ever since I got mad at an assignment I was working on and just started from scratch, wiping out a few hours worth of actually good work. Whoops!
Since then, I've used Bazaar and Git (and SVN when I had to for a Software Engineering class), though mostly Git to do version control on all of my projects. Usually I'm pretty faithful about how often I commit, but on occasion I'll go for a while (several functions, etc.) before writing a new commit.
So my question for you is, how often should you make commits? I'm sure there's no hard and fast rule, but what guideline do you (try to) follow?

A: You shouldn't commit based on a time basis, but on a feature basis. Whenever you add a new feature that's worth committing, commit. You added a working method? Commit. You fixed a typo? Commit. You fixed a file's wrong indentation? Commit. There's nothing wrong committing small changes, as soon as the commit is relevant.
What is wrong is committing a huge number of changes, with no relations between each others. It makes it very hard to detect the commit source of a given regression.
Sometimes, I make twenty commits in an hour, and sometimes I commit once a day, depending of the amount of code that was modified.
Making small commits allows you to use very powerful tools like git-bisect.
Don't forget the rule n°1 of the committer: never break the trunk. If you need to make several commits that are likely to break the trunk, create a branch instead.

A: Whenever I have something that works (meaning, doesn't break anything for anyone else) I'll do a check-in. I write most of my stuff test first, so that means every time I have a new test that passes, I check-in.
In practice that means a few times per hour. At least a couple of times every hour, with 5 being quite a bit.

A: On DVCS, I commit basically anytime I'm starting on a change that would be really annoying if I couldn't undo, anytime I need to share with others, or anytime it would be really useful to see what I changed since that point.  That ranges from several times an hour to a couple times per day.  Also, I very rarely commit when my build doesn't at least compile and run without immediate segfaults, although that can be useful too if you want to be able to isolate and share just the fix for that particular bug.
Note with centralized version control, which you are very likely to be required to use on the job, you generally don't commit until you're pretty sure you won't get a storm of angry emails for doing so.  Depending on how independent the changes you're making are, and how much your company subscribes to the continuous integration dogma, that's more along the lines of once a day to maybe once a month on a big new feature.
That frequency difference is one of the main reasons I use git on top of my company's official centralized VCS.

A: If your working in a team environment with a build server, you'll only want to commit when you've got something that builds. It's very annoying for the rest of the team otherwise :)

A: It depends a little on what the development environment is.
If you're the only one contributing to a code base, then a deferred commit won't be that crucial. However, if you're in a team of several developers, and everyone thinking "oh well, I'll wait with the commit a little" then you'll often end up handling a lot of conflicts and losing a lot of time.
The general rule (for both scenarios) would be: Commit as often as possible. If you think "it's not ready yet" (because it'll break the build or simply isn't done yet) then create a branch and commit to that branch but make sure you do commit.

A: At least once a day, usually three or four as I tend to commit anytime I take a break.  I work on my own, so I don't have to worry about messing someone else up, and I can always revert a file if I think I've gone down the wrong path.
I had a bad experience once when I wasn't making commits regularly and my hard drive crashed and I lost a few hours work.  Since my repository is on another machine and is backed up regularly, there's no reason I should have lost anything.

A: Thanks to git branches and how they are easily managed, I commit really often. I would say, whenever you add something that you feel is important and that might add up to building something later, you should commit.
Also, I often find myself doing some refactoring and adding new tests before the new code, so for this case I commit for every time I run the test, watch it fail, make it pass again and refactor.
Also, after any bug fix no matter how tiny or insignificant it might seem.
I sometimes go down the "commit it as soon as it compiles" road as well.

A: I work alone. My development environment is my notebook. The commit environment is a server on the web.
If the client uses the web server to keep track of progress. So nearly every day I do an upload along with an e-mail saying what's new.
If the commit environment is a production environment then I have to be more careful about every change being tested before any commit. But still, often seems better, as nobody has doubts about whether the new feature is planned or done already; they get what they ask for ASAP.

A: Watched this Joel On Software - FogBugz/Kiln presentation recently and think it relates well to your question.
While in some version control 'commit' is synonymous with 'publish' (or 'give pain to others') in distributed VCS they are often seperated.
So when to commit may depend on the VCS you use.

A: Automatically commit after every successful build.
I assume that if you want to revert to an earlier version, and you can remember the approximate wall-clock time of the point you want to revert to, you can just look up at that revision.
Of course if you use TDD then there are better integrated solutions.

A: Every night when I go home I have a script that will automatically go through all my branches and do a commit (note all developers don't get these changes.  Its just my personal branch).  This way I don't have to think about it.
Also I have a script that will automatically run an update in the morning.  I use this one so that if I work from my laptop at night my changes are automatically there in the morning.
As for rolling back changes that I make during the day my editor has a history of all changes and is much faster than doing a commit on every save/compile.


text:
Q: Is there a way to limit Ray object storage max memory usage I'm trying to capitalize on Ray's parallelization model to process a file record by record. The code works beautifully, but the object storage grows fast and ends up crashing. I'm avoiding using ray.get(function.remote()) because it kills the performance because the task is composed of a few million subtasks and the overhead of waiting for a task to finish. Is there a way to set a global limit to the object storage?
#code which constantly backpressusre the obejct storage, freeing space, but causes performance to be worse than serial execution
for record in infile:
    ray.get(createNucleotideCount.remote(record, copy.copy(dinucDict), copy.copy(tetranucDict),dinucList,tetranucList, filename))

#code that maximizes throughput but makes the object storage grow constantly
for record in infile:
    createNucleotideCount.remote(record, copy.copy(dinucDict), copy.copy(tetranucDict),dinucList,tetranucList, filename)

#the called function returns either 0 or 1.

A: You can do ray.init(object_store_memory=10**9) to limit the object store to use 1 GB of your system RAM (as opposed to all of it by default).

object_store_memory – The amount of memory (in bytes) to start the
object store with. By default, this is automatically set based on
available system memory.

(see docs on ray.init())
There is more information in the documentation on memory management at https://docs.ray.io/en/releases-1.11.0/ray-core/memory-management.html.


text:
Q: How to convert from java.util.Map to Scala immutable Map I'm using Scala 2.11.12. I have a java.util.Map<String, Long>, which I'd like to convert to a Scala immutable Map[String, Long]. How do I do that?
I tried to use scala.collection.JavaConverters._ as follows
import scala.collection.JavaConverters._
val scalaMap = response.jMap.asScala // this throws compile error Required  Map[scala.Predef.String, Long], but found mutable.Map[java.lang.String, java.long.Long]

val scalaMap = response.jMap.asScala.toMap // this now throws compile error required Long, but found java.long.Long

The issue seems to be that a Java Long is not the same as a Scala Long.
I see that there is a Long2long option, but how to use that here?


text:
Q: Integral with respect to brownian motion Let $f$ be a continuous function on $[0,\infty)$ and $B_t$ be a standard Brownian motion. Define
$X_t=\int_0^t f(s) dB(s).$
a) Show that $X_t$ is Gaussian and computer its covariance $C(X_s, X_t)$
b) prove that $e^{(X_t - 1/2 C(X_t, X_t))}$ is a continuous time martingale.
I think I know how to show $X_t$ is Gaussian (basically expressing it as a sum of Brownian motion increments each of which is gaussian) is that right?
I don't know how to derive the covariance and show that  $e^{(X_t - 1/2C(X_t, X_t))}$ is a martingale, any hint would be appreciated.

A: *

*Covariance: As @Did pointed out, Itô's formula combined with the polarization identities (i.e. $a \cdot b = \frac{1}{4} ((a+b)^2-(a-b)^2)$) yields $$\mathbb{E} \left( \int g(r) \, dB_r \int h(r) \, dB_r \right) = \mathbb{E} \left( \int g(r) h(r) \, dr \right)$$ whenenever the expression is well-defined. Setting $g(r) := 1_{[0,t]}(r) f(r), h(r) := 1_{[0,s]}(r) f(r)$, we find $$\mathbb{E}(X_t X_s) = \mathbb{E} \left( \int_0^{s \wedge t} f(r)^2 \, dr \right) = \int_0^{s \wedge t} f(r)^2 \, dr$$ where the last inequality holds due to the fact that $f$ is deterministic. Consequently, $$C(s,t) = \int_0^{s \wedge t} f(r)^2 \, dr.$$

*Martingale property: This is a straightforward application of Itô's formula. In fact, we have for $F(t,x) := e^{x-G(t)}$, $$\begin{align*}& F(t,X_t)  - F(0,0) \\ &\quad= \int_0^t F(s,X_s) \, dX_s -  \int_0^t G'(s) F(s,X_s) \, ds + \frac{1}{2} \int_0^t F(s,X_s) f(s)^2 \, ds \end{align*}$$ for any differentiable (deterministic) function $G$. In particular, if we choose $G(t) = \frac{1}{2} C(t,t)$, then this shows $$F(t,X_t)-1 = \int_0^t F(s,X_s) \, dX_s.$$ The right-hand side is a martingale as a stochastic integral with respect to a martingale. This finishes the proof.