text:
Q: Junit testing stategy for clustered ehcache I am planning to use ehcahe to cache some of my frequently used objects. I have a ehcache in a clustered configuration.
Now i want to do the following in my JUnit-

*

*Check if hibernate ehcache code is working correctly in cluster mode.

*Check if my objects are correctly being fetched from cache and not recreated from WS.

Any thoughts?

A: Q> Check if hibernate ehcache code is working correctly in cluster mode.
A> You will have to mock a lot of stuff - double layer of (at least two separate instances) database, Hibernate and Ehcache to say the least. This might be doable but to me this doesn't make sense on many levels. First, the definition of a unit is the smallest testable part of an application - and this case goes nowhere near it. Secondly, I am sure Ehcache has unit/integration tests itself, do you really have so little trust in your libraries that you want to write unit tests for them? (proof of concept is quite different from unit test)
Q> Check if my objects are correctly being fetched from cache and not recreated from WS.
A> Scenarios are quite different depending on the cache strategy (cache-aside VS cache-as-sor VS read-through). This however should be quite easy as you have the control over your WS. During the test you should be able to determine how many times the WS was called - say, if the first read-through call to cache results a call to WS, then the second call shouldn't (because of the record being cached).


text:
Q: How to have one list box present data based on selection of first one? I'm making a windows form with 2 list boxes. My plan is for the user to have the option to add/edit/remove from both list boxes. When a user selects an option from the first list (a selection of car names i.e. Mazda 3), the second list box will show all the data that would be entered based off that of the first selection (my idea is to keep service records for each vehicle; this box also will have the option to add/edit/remove). How should I go about having the second list box show items based on the selection of the first list box?
Is a multidimensional array the best way to do this? I also plan on having a picture box that will show a picture that the user can upload and will be view-able based on the selection of the SECOND list box.
Thanks

A: Could you please provide the code of what you have so far? Without knowing that, I would say you can have a function invoked by the change in the first list box
`private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     if(listBox1.Text == "mazda 3")
         //do something here with listbox2
 }`

A: I'm not really clear on what it actually is you're trying to do, but from my understanding you have a list of cars, and for every car on that list, there is a list of service records?
If this is the case you could do something like this:
public partial class Form1 : Form
{

    List<string> cars = new List<string>()
    {
        "Mazda 3",
        "Mazda 6",
        "VW Polo",
        "VW Golf"
    };

    List<string> Mazda3 = new List<string>()
    {
        "12-04-2008",
        "14-03-2010",
        "20-05-2012",

    };

    List<string> Mazda6 = new List<string>()
    {
        "12-08-2012",
        "14-07-2014",
        "03-09-2016",
    };

    List<string> VWPolo = new List<string>()
    {
        "Some Date",
        "Some Date",
        "Some Date",
    };

    List<string> VWGolf = new List<string>()
    {
        "Some Date",
        "Some Date",
        "Some Date",
    };

    List<List<string>> ServiceLists = new List<List<string>>();

    public Form1()
    {
        InitializeComponent();

        ServiceLists.Add(Mazda3);
        ServiceLists.Add(Mazda6);
        ServiceLists.Add(VWPolo);
        ServiceLists.Add(VWGolf);

        Cars_listBox.DataSource = cars;
    }

    private void Cars_listBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        ServiceRecords_listBox.DataSource = ServiceLists[Cars_listBox.SelectedIndex];
    }
}

In this example the listBoxes are created in the designer

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cauchy Riemann Eqn I need a bit of help as I'm stuck on this problem...this maybe simple..but.. I have to find all z ∈ C such that the function f(z) = z cos(z(bar)) satisfies the Cauchy-Riemann eqns.
So far I have worked out the following:
∂u/∂x= cos(x) - xsin(x) - ycos(x)sinh(y)
∂u/∂y =  xcos(x)sinh(y) - sin(x)[sinh(y) + ycosh(y)]
∂v/∂x = sin(x) + xcos(x) - ysin(x)cosh(y)
∂v/∂y = xsin(x)cosh(y) + cos(x)[xsinh(x)+cosh(x)]
Do I simply have to check whether ∂u/∂x= ∂v/∂y and ∂u/∂y=-∂v/∂x, in order to find out if it satifies the C-R eqns?


text:
Q: Autoscroll chat without javascript (html and css only) I searched very long time how to autoscroll chat without JavaScript. But couldn't find any solution except this example, but there the scroll with mouse does not work as expected. Anyway all the others uses JavaScript more or less. But after some time I saw at an employee one a strange (because I don't clearly understand why it works) but simple solution and I want to share it with SO community. May be someone also search how to auto scroll only with CSS properties and HTML.

A: The "magic" part is in the .messages-wrapper. All we need in generally is just wrap our .messages to another div and set to it flex-direction: column-reverse. Also we can control from where messages will start from top or from bottom just adding/removing height: 100% property to .messages-wrapper. The part which I don't understand is why the column-reverse works? I always saw that column-reverse reverse only first level children order but in this case it do some "magic". I will very glad if someone explains me how and why it works

//JUST TO ADD MESSAGES DYNAMICALLY

const topMessages = document.querySelector('.start-from-top .messages');
const bottomMessages = document.querySelector('.start-from-bottom .messages');

let topMessagesNumber = 0;
let bottomMessagesNumber = 0;

const addMessage = (messages, number) => {
  const message = document.createElement('div');
  message.innerHTML = 'Some text ' + number;
  message.className = 'message';

  const isRightMessage = Math.random() >= 0.5;

  message.classList.add(`${isRightMessage ? 'right' : 'left'}`);

  messages.append(message);
}

const addTopMessage = () => {
  addMessage(topMessages, ++topMessagesNumber);
}

const addBottomMessage = () => {
  addMessage(bottomMessages, ++bottomMessagesNumber);
}
div:not(.messages):not(.messages-wrapper) {
  outline: 1px solid black;
}

.chat {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 150px;
}

.messages-wrapper {
  display: flex;
  flex-direction: column-reverse;
  overflow-y: auto;
}

.messages-wrapper.start-from-bottom {
  height: 100%;
}

.message {
  margin: 16px 8px;
}

.message.right {
  text-align: right;
}

.message.left {
  text-align: left;
}

.add-message {
  padding: 8px;
}
Starting first message from top

    <button onclick="addTopMessage()">Add message</button>

Starting first message from bottom

    <button onclick="addBottomMessage()">Add message</button>


text:
Q: Relational Databases: Database Structure / Flow I'm using Entity Framework to setup a database. I'm brand new to relational databases and I'm attempting to determine the proper way to setup a few tables and their relations. Here's the scoop.
Say I have three tables in my database.
The main table is table A which holds a dataset for an object let's call this object Food. Columns: FoodID (primary key), RecipeID (foreign key paired to it's recipe in Table C).
Table C : contains records for recipes used to make the different Food items stored in Table A. Columns: RecipeID (primary key) and Recipe Name.
Table B : Is an instruction / recipe entry to for creating a Food. Columns : EntryID (primary key), RecipeID (foreign key referencing the Recipe ID in table C), FoodID (foreign key referencing a Food in Table A).
I can't wrap my ahead around the proper way to do this since it makes a circular relationship.
Do I just remove the foreign key (RecipeID) from the Food table? What is the proper flow I should be pursuing in situations like this.
 Recipes -> Multiple Recipe Entries -> Food -> Recipe

Food requires a recipe to make it but Food is used in recipes to make other Food.
Conceptualizing the data into C# code it would look like this.
public class Food
{
    public int FoodID { get; set; }
    public string Name { get; set; }
    public List<Food> Recipe { get; set; }
}

Entity Framework Model would be the following.
public class Food
{
    [Key]
    public int FoodID { get; set; }//Pri Key
    public string Name { get; set; }
    public int FoodRecipeID { get; set; }//Foreign Key

    public virtual FoodRecipe FoodRecipe { get; set; }//Navigation Property
}

public class FoodRecipeEntry
{
    [Key]
    public int FoodRecipeEntryId { get; set; } //Pri Key
    public string Name { get; set; }
    public int FoodID { get; set; }//Foreign Key
    public int FoodRecipeID { get; set; }

    //Navigation Properties
    public Food Food { get; set; }
    public FoodRecipe FoodRecipe { get; set; }
}

public class FoodRecipe
{
    [Key]
    public int FoodRecipeID { get; set; } //Pri Key
    public string Name { get; set; }
    public virtual ICollection<FoodRecipeEntry> FoodRecipeEntries {get; set; }//Navigation Property
}

A: Here are some pointers:

*

*Remove the Food ID from FoodRecipeEntry, the FoodID is implied by the recipe since the recipe is for a specific food, and the entry belongs to the given recipe

*I'd personally put the foreign key inside Recipe, not Food - a single food may have multiple recipes, so it should be Recipe -> Food

In code this would look like so:
public class Food
{
    [Key]
    public int FoodID { get; set; }//Pri Key
    public string Name { get; set; }

    public virtual FoodRecipe FoodRecipe { get; set; }//Navigation Property
}

public class FoodRecipeEntry
{
    [Key]
    public int FoodRecipeEntryId { get; set; } //Pri Key
    public string Name { get; set; }

    [ForeignKey("FoodRecipe")] // Personally I prefer using explicit foreign key attributes to avoid implicit jankiness
    public int FoodRecipeID { get; set; }

    [ForeignKey("Ingredient")]
    public int IngredientID { get; set; }

    //Navigation Properties
    public virtual FoodRecipe FoodRecipe { get; set; }

    public virtual Food Ingredient { get; set; }
}

public class FoodRecipe
{
    [Key]
    public int FoodRecipeID { get; set; } //Pri Key
    public string Name { get; set; }
    [ForeignKey("Food")] // Personally I prefer using explicit foreign key attributes to avoid implicit jankiness
    public int FoodID { get; set; }//Foreign Key
    public virtual Food Food { get; set; }
    public virtual ICollection<FoodRecipeEntry> FoodRecipeEntries {get; set; }//Navigation Property
}


text:
Q: Add UIScrollView to my application I have gone through many tutorials but most of them tell how to add a UIScrollView using the interface builder. I need to add a scrollview using code. I went through several tutorials and what they did was they add the UIView to the UIScrollView . [scrollView addSubView:myView]; simple as that ad connect to using interface builder.
Can someone please guide me as in how to add a UIScrollView using code (Only Code)

A: Is really simple:
UIScrollView * scroller = [[[UIScrollView alloc] initWithFrame:CGTectMake(0, 0, 320, 480)] autorelease];
[self.view addSubview:scroller];

int x = 0;

for (int i = 0; i < 5; i++){

    UIView * myview = [[[UIView alloc] initWithFrame:CGRectMake(x, 0, 320, 480)] autorelease];
    [scroller addSubview:myView];

    x += myView.frame.size.width;

}

[scroller setContentSize:CGSizeMake(x, 480)];

This code was compiled in my head, so sorry if there is a sintax mistake.

A: All my examples use code rather than the nib - it's way easier to create and configure a scroll view in code! See here:
https://github.com/mattneub/Programming-iOS-4-Book-Examples/tree/master/convertedToIOS5
The scroll view examples start with p482p494scrollViewInCode.


text:
Q: What is the modular curve for level 1, 2? An elliptic curve over a scheme $S$ is the data of a proper smooth morphism
of schemes $\pi: E\rightarrow S$ whose geometric fibres are connected curves of genus $1$ and a section $e: S \rightarrow E$.
A level $\Gamma(N)$–structure on an elliptic curve $E$ over
a scheme $S$ is an isomorphism $E[N] \rightarrow (\mathbb{Z}/N\mathbb{Z})_S\times_S(\mathbb{Z}/N\mathbb{Z})_S$ of group
schemes over $S$.
Let $R$ be an integral domain. The category $R-Ell$ is the category whose objects are elliptic curves $E\rightarrow S$ with $S$ an $R$-scheme and whose morphisms are cartesian square diagrams of $R$-morphisms.
$\Gamma(N)$ is a functor $R-Ell^{op}\rightarrow Set$ sending an elliptic curve to the set of level $\Gamma(N)$-structures on it.
For $N\geq 3$ and $R=\mathbb{Z}[1/N]$, results of Katz and Mazur imply that $\Gamma(N)$ is representable by an elliptic curve whose base is a smooth affine $\mathbb{Z}[1/n]$-curve.
What I am asking is for $N=1, 2$ is the moduli problem representable by something geometric (algebraic space, DM stack etc.)? Is there a reference establishing its good properties? I find navigating the literature difficult.


text:
Q: I Have 3 Variables NAME, DIRECTORY, FILE_EXTENSION how to make a file with this information? def createfile(name, location, extension):
    print(name, extension, location)

I have this code and I need to make a file with these variables
I have tried a couple of things but they never seemed to work.

A: Here is a code using tkinter to get the name of the folder by an Entry widget. The code focuses on pdf files, but can be substituted for any file type.
This function is called fisrt with the path of your file or your locations, passing the path as 'files' *arg.
def replace_slash(files):

    ficheros=[]

    for i in files:

        pth=pathlib.Path(i)
        pth=str(pth)
        ficheros.append(pth.replace('/', '\\'))

    return ficheros

def save_file_window(file_to_save, extension):

        work_file = os.path.dirname(__file__) # Save the path of the working folder (where the '.py' file is located).
        all_files = os.listdir(work_file) # Saves all the files in the folder, in a list.
        location = ''.join(replace_slash(work_file)) # Where the file will be saved. You can replace it for an specific location.

        aux_root= Tk()
        aux_root.resizable(0,0)
        aux_root.title('Save file')

        aux_mf= Frame(aux_root)
        aux_mf.pack()

        def save_file():
            extension = ext_entry.get()

            if ent.get()== '':
                nom = 'file_doe'
            else:
                nom= ent.get()

            if extension in ent.get():
                nom= ent.get().replace(f'.{extension}', '')

            if nom + f'.{extension}' in all_files:
                nom= nom + '-new'

            with open(f'{location}\\{nom}.{extension}', 'wb') as new_file:
                file_to_save.write(new_file)

            messagebox.showinfo(title= 'Saved', message= f'File saved successfully.'
                f'\n\nFile name: {nom}.{extension}'
                f'\n\nFile path: {destination}')

            aux_root.destroy()

        entVar= StringVar()

        lb= Label(aux_mf, text= 'Select the file name and the type below:', font= 'bold', pady= 15, padx= 30)
        lb.grid(row= 0, column= 0)

        ent= Entry(aux_mf, textvariable= entVar)
        ent.grid(row= 1, column= 0, pady= 15)

        ext_entry= Entry(aux_mf, textvariable= entVar)
        ext_entry.grid(row= 2, column= 0, pady= 15)

        btn= Button(aux_mf, text= 'Send', pady= 5, font= 'bold', activebackground= "#38EB5C", cursor= 'hand2', bd= 5,width= 10,command= save_file)
        btn.grid(row= 3, column= 0)

        aux_root.mainloop()

A: Adding code below for better understanding with output screenshot.
import os
def createfile(name, location, extension):
    print(name, extension, location)
    #starting creating a file with some dummy contents
    path = os.path.join(location, name + '.' + extension)
    f = open(path, "a")
    f.write("Your contents!! or whatever you want to put inside this file.")
    f.close()
    print("File creation is successful!!")

def readfile(name, location, extension):
    #open and read the file after the appending:
    path = os.path.join(location, name + '.' + extension)
    f = open(path, "r")
    print(f.read())

#pass the parameters here
createfile('test','./','txt')
readfile('test','./','txt')


text:
Q: Minimal requirements to be a submersion. I saw here (A surjective map which is not a submersion) that a smooth differentiable map $f:M\to N$ between two manifolds $M$ and $N$ is not necessarily a submersion. A counterexample is $f:\mathbb{R}\to\mathbb{R}$, $x\to x^3$, then at $x=0$ its differential is not surjective. Is it possible to make general extra assumptions on the map $f$ such that it is a submersion, and if so, what are they?

A: If $f$ is a surjective map of constant rank, then it is a submersion. Let's prove this. The main engine is the rank theorem.

$F:M \to N$ is a smooth map with constant rank $r$. $dim(M) = m$ and $dim(N) = n$. Then, given $p \in M$, we can choose charts around $p$ and $F(p)$ in which $F$ has the coordinate representation $(x_1, ..., x_r, x_{r+1}, ..., x_m) \to (x_1, ..,x_r, 0,..,0)$ if $m \leq n$.

The proof I know uses contradiction, but I would like to see a different proof if anyone knows one. Anyway, here goes the one I know. Suppose $F: M \to N$ as above, and is surjective, and it is has constant rank $r < n$.
Then, given a point $p \in M$, we can put coordinate charts $U$ and $V$ around $p$ and $F(p)$ , respectively, such that we have the form $(x_1,..., x_n) \to (x_1, ..., x_r, 0,..,0)$. AS a manifold, $M$ has a basis of pre compact coordinate balls. So, we can assume $U$ is some pre compact coordinate ball, since it certainly contains such a ball containing $p$. We can also assume that $F(\overline{U}) \subseteq V$. Now, $F(\overline{U})$ is identified with a subset of $\{(y_1,...,y_r,0,...,0)| y_1,...,y_r \in \mathbb{R} \}$  in $\mathbb{R}^n$, and so $F(\overline{U})$ clearly contains no open subset. If it did, then the image of this set in $\mathbb{R}^n$ would have to be open, and so could not be a subset of that set of points. Thus, $F(\overline{U})$ is closed, as the image of a compact set, and has empty interior, since it contains no open set. Thus,  is nowhere dense.
$M$ has a countable basis of such coordinate balls, and so we can obtain a countable cover of $M$, $\{ \overline{U_{a_n}} \}$ with $F(\overline{U_{a_n}})$ nowhere dense.
So, then $M = \bigcup \overline{U_{a_n}}$ gives $F(M) = F(\bigcup \overline{U_{a_n}}) = \bigcup F(\overline{U_{a_n}})$. This is the union of countably many nowhere dense sets, and as such it has empty interior, and so, in particular, is nowhere dense. So, $F$ was not surjective in the first place.
I think one could probably actually give a shorter proof using Sard's theorem. If $F$ had constant rank and is not a submersion, then every point in $F$ is a critical point. So, every value of $F$ is a critical value. So, $F(M)$ has measure $0$ in $N$, and consequently $F$ is not surjective.


text:
Q: RatingBar touch position is inaccurate This is my RatingBar:
<RatingBar
    android:id="@+id/rbFeedback"
    android:stepSize="1.0"
    android:rating="5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:visibility="visible"
    app:layout_constraintBottom_toTopOf="@+id/btnSubmitFeedback"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

This is my onRatingBarChangeListener:
float ratingscore = 5.0f;
@Override protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.rating);
    rbFeedback = findViewById(R.id.rbFeedback);
    rbFeedback.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener(){
        @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser){
            ratingscore = rating;
        }
    });
}

When I click anywhere between the middle of the 3rd star (2.50) and the middle of the 4th star (3.49), it selects 4/5 stars. Why does clicking in the middle of the 3rd star give 4 stars?
So if I click on the middle of the 3rd star, it selects 4/5 stars.
These are the results that it is giving me for each range:
click 0.00 to 0.49 = 1 stars
click 0.50 to 1.49 = 2 stars
click 1.50 to 2.49 = 3 stars
click 2.50 to 3.49 = 4 stars
click 3.50 to 5.00 = 5 stars

This seems to be default behavior and not a bug, but I don't want this behavior.
I would like this range:
click 0.00 to 0.99 = 1 stars
click 1.00 to 1.99 = 2 stars
click 2.00 to 2.99 = 3 stars
click 3.00 to 3.99 = 4 stars
click 4.00 to 4.99 = 5 stars

How can I achieve this?

A: I have a same issue. I change step size from 1 to 0.1 and handle it in activity. I get the rating every time click on the rating bar. Then compare it to get the number of stars.
    if (ratingNumber >= 0f && ratingNumber <= 1f) {
        rating.setRating(1f);
    } else if (ratingNumber >= 1.1f && ratingNumber <= 2f) {
        rating.setRating(2f);
    } else if (ratingNumber >= 2.1f && ratingNumber <= 3f) {
        rating.setRating(3f);
    } else if (ratingNumber >= 3.1f && ratingNumber <= 4f) {
        rating.setRating(4f);
    } else if (ratingNumber >= 4.1f && ratingNumber <= 5f) {
        rating.setRating(5f);
    }

Hope it helps you or someone else.


text:
Q: foreach by quantity in laravel I develop a ticketing system which user have to choose the quantity of ticket category. I want to save the record to database by the total of quantity. But it seems to be failed. I end up only save the record by category id. Here is the result when I try to return it.

and this is my code in controller.
public function ticket_checkout(Request $request)
    {
        $ctg_id = $request->cat_id;
        $price = $request->price;
        $name = $request->name;
        $qty = $request->qty;
        // return count($qty);

        $data = [];
        $i = 0;
        foreach($qty as $item){
            if($qty[$i] != 0){
                $data[] = [
                    "ctg_id" => $ctg_id[$i],
                    "price" => $price[$i],
                    "qty" => $item,
                ];
            }
            $i++;
        }

        return $data;
        Ticket_checkout::insert($data);
        // return $qty;
        return view('ticket.index', compact('data','qty'));
    }

I wonder if I missing something here? I tried to do looping 'for' by quantity inside the 'foreach' but it seems not working too.


text:
Q: IONIC3 for IOS Error - UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'attrib' of null When i try to create a build or run the ios version of my app by navigating to the root folder and passing the command:
sudo ionic cordova build ios --verbose

I am getting errors stating " UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'attrib' of null at ConfigParser.shortName "
Kindly help i am stuck with this from past 2 weeks. My Android build & Web Version works fine.

A: Try removing and adding the IOS platform again.
ionic cordova platform remove ios
ionic cordova platform add ios


text:
Q: How do I get the background url from css Selenium Webdriver I'm trying to check the url of an image, located in a div - in the 'background:' - in the CSS for the page.  But when 'get' the CssValue and display it just shows blank.
The html for the div is:

Welcome

.......

...and the CSS for the div is:
div.Welcome {
background: rgba(0, 0, 0, 0) url("imageurl") no-repeat scroll center 25px;
float: left;
margin: 50px 20px 50px 150px;
padding-top: 230px;
width: 300px;
}

I've tried to locate as below:
WebElement WelcomeImg = driver.findElement(By className("Welcome"));

String WelImg = WelcomeImg.getCssValue("background");

Assert.assertTrue(WelImg.contains("imageurl"));

I've also tried with
("background-url");

Any help would be greatly appreciated

A: I think, you should try with new thing! Get the background image property and let me know whether it worked.
WebElement WelcomeImg = driver.findElement(By className("Welcome"));
String WelImg = WelcomeImg.getCssValue("background-image");
Assert.assertTrue(WelImg.contains("imageurl"));

Hope, it may help you.


text:
Q: AngularJS Update Scope $q So recently I've been updating something that looks like the below:
$scope.arrayOfThings = [];

function setArrayOfThings() {
     thingsService.get().then(function (things) {
         $scope.arrayOfThings = things;
     });
}

$scope.$on('arrayOfThings.add', setArrayOfThings);

To look more like this (using the lesser-known promise integration into bindings...):
$scope.arrayOfThings = thingsService.get();

But how do I force arrayOfThings to update (or re-resolve?) when the collection is changed from another $scope?

A: arrayOfThings can be seen only inside a child scope, so any change of arrayOfThings in a child scope will maintain data-binding anyway. The data-binding has to be resolve manually by $scope.$apply if the arrayOfThing is changed from an event (DOM event, $broadcast, etc)

A: You need to put a watch on the service call thingsService.get in the controller that you want to be notified of a change. Like this:
$scope.$watch(thingsService.get, function(newVal, oldVal){
  $scope.arrayOfThings2 = newVal;
} );

This is assuming you are injecting that service into the new controller.


text:
Q: forward()/redirect() usage for a signup process? I'm trying to finalize a signup process for my webapp, but am getting confused with servlet forwarding/redirects (again). The flow looks like this:
// /signup/index.jsp
<form action='/user/signup'>
</form>
<%
if (request.getAttribute("msg") != null) {
    %><div><%= request.getAttribute("msg") %><%
}
%>

// Servlet which maps to '/user/signup':
public void doPost(..) {
    // process signup params..

    // I want to show the user /signup/index.jsp again after completion:
    req.setAttribute("msg", "signup worked!");
    req.getRequestDispatcher("/signup/index.jsp").forward(req, resp);
}

when I use the forward() method, the browser shows the url of the post action still:
/user/signup

but the content is of:
/signup/index.jsp

this is what forward() is supposed to do. I am not sure if this is confusing to the user though - the url is different than the page that actually generated the content.
I stepped through what twitter does, looks like they are foward()ing the user around:
// twitter.com/signup
if (ok) {
    forward("/find_sources/suggestions");
    if (ok) {
        forward("/find_sources/contacts");
        if (ok) {
            forward("/find_sources/anyone");
            if (ok) {
                forward("/");
            }
        }
    }
else {
    forward("/signup"); // error msg displayed here etc
}

In the above, if you mess up on the initial signup page, your browser shows the /account/create url, but the content of the page looks like /signup - so I guess they're doing the same thing I am (I am just assuming the underlying forward()/redirect() options are the same for all http servers, not specific to jsp).
Is my flow normal then? Should I be doing this some other way? I guess the options are:

*

*Use forward() and accept that the url will be of the action url.

*Use redirect() and store any messages I want to show the user in a session.

Thank you

A: If you wish to do what twitter does - make all the validation in-line - i.e. display validation errors with AJAX. Then the users will click "register" only if they have completed everything correctly and the fact that forward is used won't be much of a problem.
However, in the general case, try to find some conversation framework (like spring web flow), or something similar to JSF's @ViewScope - i.e. something between request and session to accommodate this use case.
Another option is to use redirect and clear the contents of the session that have been just set.


text:
Q: What is "if and only if" all about? I recently learnt about this mysterious "if and only if". That's all I know about it:

*

*"$B\implies A$" is the symbolic notation for "If $B$, then $A$".

*"$A$ only if $B$" means the same as "$A\implies B$".

*So "$A$ if and only if $B$" means "($A$ if $B$) AND ($A$ only if $B$)", which can be expressed symbolically as $(B\implies A)\land(A\implies B)$.

*Thus the "if and only if" can be written as a double arrow $\iff$.
I understand it sofar. But the thing I wondered about is why the symbol "$\iff$" is also used to mean equality of two statements. Why? Isn't equality of two statements (that is, equality of the truth values of those statements) the more fundamental notion? Is there something about the "if and only if" I don't know?

A: Consider two particular statements about a hypothetical natural number $n$:

*

*$A$: "The number $n$ is a multiple of $2$ and of $15$"

*$B$: "The number $n$ is a multiple of $6$ and of $5$"
These are equivalent statements, which means that for each natural number $k$, both $A(k)$ and $B(k)$ have the same truth value.
However, $A$ and $B$ on their own do not have truth values, because until we know a particular value of $n$ we do not know whether $A$ and $B$ are true or false. The fact that they are equivalent is thus a statement about the equality of an infinite set of truth values (one for each $k$), not a statement about "the truth value of $A$" and "the truth value of $B$"
Moreover, $A$ and $B$ are not equal statements. For example, the first statement contains a numeral $2$ and the second does not. The first requires 31 characters, not counting spaces, while the second only requires 30. Because the statements are not the same, we do not call them "equal".
For these reasons, we don't use an equality sign to denote equivalence of statements. First, the statements are rarely literally the same. Second, statements with undetermined variables ("free variables") do not have truth values at all until the variables are replaced with concrete values.


text:
Q: ios why can't i hook WKCustomProtocol methods WKCustomProtocol is a class form WebKit source code, I've already debugged it. It exists
HDWebURLProtocol,WKCustomProtocol superClass is NSURLProtocol. I hook my own class 'HDWebURLProtocol', which was successful, But WKCustomProtocol was not successful;
I use Xcode 10.1, iOS 12.1 simulator, Debug run WebKit code
This is My Code:
+ (void)exchange {

    Class WKCustomProtocolClass = object_getClass(NSClassFromString(@"WKCustomProtocol")); // HDWebURLProtocol

    SEL canInitWithRequest = NSSelectorFromString(@"canInitWithRequest:");
    SEL af_canInitWithRequest = NSSelectorFromString(@"fix_canInitWithRequest:");

    BOOL add1 = class_addMethod(WKCustomProtocolClass,
                                canInitWithRequest,
                                class_getMethodImplementation(WKCustomProtocolClass, canInitWithRequest),
                                "B@:@");

    BOOL add2 = class_addMethod(WKCustomProtocolClass,
                                af_canInitWithRequest,
                                (IMP)af_canInitWithRequest2,
                                "B@:@");

    NSLog(@"%d,%d", add1, add2);

    Method orgi = class_getClassMethod(WKCustomProtocolClass, canInitWithRequest);
    Method after = class_getClassMethod(WKCustomProtocolClass, af_canInitWithRequest);

    method_exchangeImplementations(orgi, after);
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"

BOOL af_canInitWithRequest2(id sender, SEL cmd, NSURLRequest *req) {
    SEL canInitWithRequest = NSSelectorFromString(@"fix_canInitWithRequest:");
    return [sender performSelector:canInitWithRequest withObject:req];
}

#pragma clang diagnostic pop

breakpoint screenshots


text: Q: Is drawing straws fair if there are 2 short straws instead of the customary 1? I know that the probability is fair for the normal version (i.e. you stop drawing after the only short straw is drawn.) But what if there are 2 short straws? Wouldn't the odds change after the first is drawn?


text:
Q: $_GET not working in drupal module FIXED!!
I just moved few site's from our server back to local server to use it as dev server.
They are done in drupal, and I'm facing a lot problems, still I managed to get em alive.
So the problem is that i have module that will $_GET['nid'] and use it to load node in this module. Only thing is that $_GET just f's at me and returns empty array. Otherwise module seem's to be working just fine, since when I hard code $nid in module, it is willing to print it out and work like a charm.
Here's my code:
    //get nid (current node) and prev (previous nodes) if present
    if (isset($_GET['nid'])){
    $nid = $_GET['nid'];
    };
    //echo ($nid);
    //if(isset($_GET['prev'])){
    //      $prev = $_GET['prev'];
    //};
    //if there's a nid given, load it, check if there is a node like that.
    if($nid > 0){
            $processNode = node_load($nid);
            $timeInfo['02_processNode_loaded'] = date('Y-m-d H:i:s');

and then it will keep on doing it's thing. And yea when i hard coded $nid it worked like a charm.
Url: http://example/example?nid=2
Edit:
Also tester $server['reguest_uri'] witch came out empty.
Edit2:
Also tested
$yrityshyva = drupal_get_query_parameters();
print_r ($yrityshyva);

and it's empty

A: you are missing closing single quote
change
$nid = $_GET['nid];

to
$nid = $_GET['nid'];

A: Do you have modrewrite enabled? if so, you can try
http://example/example/nid=2

best,
e.

A: Okay, this was totally my bad since, i didnt have mod_rewrite on....
Thanks for all who have answered


text:
Q: Why tests are executed with junit-jupiter (aggregator) but not using separate dependencies? I'm using Maven to build a Spring boot project.
When I set Junit jupiter dependencies like this
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.5.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.5.1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <version>5.5.1</version>
    <scope>test</scope>
</dependency>

I got the error

juil. 23, 2019 10:47:42 PM org.junit.platform.launcher.core.DefaultLauncher handleThrowable
  AVERTISSEMENT: TestEngine with ID 'junit-jupiter' failed to discover tests
  java.lang.NoClassDefFoundError: org/junit/platform/engine/support/discovery/SelectorResolver

But when I set dependencies using aggregator, tests are executed normally.
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.5.1</version>
    <scope>test</scope>
</dependency>

So what's are the difference between this two ?

A: You are missing junit-platform-launcher artifact. See official JUnit 5 User Guide:
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
You should add this to your pom.xml:
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.5.2</version>
    <scope>test</scope>
</dependency>


text:
Q: How to Pass List to SOAP API as a request How to Pass List to SOAP API request from android
I know how to pass normal object, but at the time of passing the List I'm getting  following exception Unable to cast object of type 'GTCFWebServices.Models.ToEmail' to type 'System.Collections.Generic.List1[GTCFWebServices.Models.ToEmail]'.
This is expected soap xml request I need to pass List< ToEmail > as a request.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:gtc="http://schemas.datacontract.org/2004/07/GTCFWebServices.Models">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:SendEmailNotificationToScannedUser>
         <!--Optional:-->
         <tem:fromEmail>
            <!--Optional:-->
            <gtc:ActivationCode>6wDQ8</gtc:ActivationCode>
            <!--Optional:-->
            <gtc:Email>?</gtc:Email>
            <!--Optional:-->
            <gtc:IsEmailHasToSent>true</gtc:IsEmailHasToSent>
            <!--Optional:-->
            <gtc:Name>Snehal Jadhav</gtc:Name>
            <!--Optional:-->
            <gtc:PhoneNumber>?</gtc:PhoneNumber>
            <!--Optional:-->
            <gtc:ProfileImageName>?</gtc:ProfileImageName>
            <!--Optional:-->
            <gtc:UniversityImageName>?</gtc:UniversityImageName>
            <!--Optional:-->
            <gtc:UniversityName>?</gtc:UniversityName>
         </tem:fromEmail>
         <!--Optional:-->
         <tem:scannedUsers>
            <!--Zero or more repetitions:-->
            <gtc:ToEmail>
               <!--Optional:-->
               <gtc:Body>body</gtc:Body>
               <!--Optional:-->
               <gtc:CC>
                  <!--Zero or more repetitions:-->
                  <gtc:Contact>
                     <!--Optional:-->
                     <gtc:Email>?</gtc:Email>
                     <!--Optional:-->
                     <gtc:FirstName>?</gtc:FirstName>
                     <!--Optional:-->
                     <gtc:LastName>?</gtc:LastName>
                  </gtc:Contact>
               </gtc:CC>
               <!--Optional:-->
               <gtc:ScannedUserId>1</gtc:ScannedUserId>
               <!--Optional:-->
               <gtc:Subject>?</gtc:Subject>
               <!--Optional:-->
               <gtc:To>
                  <!--Zero or more repetitions:-->
                  <gtc:Contact>
                     <!--Optional:-->
                     <gtc:Email>?</gtc:Email>
                     <!--Optional:-->
                     <gtc:FirstName>?</gtc:FirstName>
                     <!--Optional:-->
                     <gtc:LastName>?</gtc:LastName>
                  </gtc:Contact>
               </gtc:To>
            </gtc:ToEmail>
         </tem:scannedUsers>
      </tem:SendEmailNotificationToScannedUser>
   </soapenv:Body>
</soapenv:Envelope>

A: It is not possible to pass complex object like a list of complex object as a parameter in SOAP request.
Finally, I passed String concatenating with, (comma) for a list and then API side we separated it and created a list.


text:
Q: how to use regex to add leading zero Question - what is the shortest form of regex to add a leading zero into a found pattern?
I want to add a leading zero to any number that matches this regex pattern
[(][0-9][0-9][0-9][0-9][-][0-9][0-9][0-9][0-9][-][0-9][0-9][)]
I am using Notepad++.

A: In Notepad++ Regex Replace, you use $n to represent the nth capture group for replacement:
Search for: [(]([0-9][0-9][0-9][0-9][-][0-9][0-9][0-9][0-9][-][0-9][0-9])[)]
Replace with: (0$1)


text:
Q: How can I use if-statements with drag-and-drop to open different links depending on the object that is dragged? I am trying to make a webpage where you can drag and drop one of three images onto a target image, and depending on the image that is dragged and dropped onto the target, the user will be directed to a different link.
For example, when the user drags the image with the ID "drag 1" onto the target image, they are directed to the webpage "portfolio-fiber" on my website.  Alternatively, if the user drags the image with the ID "drag 2" onto the target image, they are directed to the webpage "portfolio-paint"; and so on.
So far, I've been able to get almost everything to work, but when I drag any of the images, they all direct me to the same webpage ("portfolio-fiber").
I am new to coding, so I would greatly appreciate any advice you can provide about how to make different draggable images direct the user to different links.  Below is the script I have so far.

DRAG THE MEDIA YOU WANT TO VIEW ONTO THE CANVAS:

A: You were very close, your first problem was you were assigning data in your if statement by only using a single = when assigning a variable the output will always be true, which is why it always went to portfolio-fiber. Secondly it should be drag 1 not #drag 1 when doing the comparison, you can see this by putting a console.log(data) before your if statements which will show you what is stored in the variable when looking at the browser console.
I believe the code block below should now have the desired effect.
function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
  if (data == "drag 1"){
    window.open('portfolio-fiber', '_self',false).click();
  }
  else if (data == "drag 2"){
    window.open('portfolio-paint', '_self',false).click();
  }
else if (data == "drag 3"){
    window.open('portfolio-other', '_self',false).click();
  }
}


text:
Q: Smoothing geom_path() with scale_y_reverse() and stat_smooth() My dataset:
reading,depth
31055,0.0
57635,0.5
34268,1.0
20926,1.5
13507,2.0
12944,2.5
13002,3.0
12892,3.5
12610,4.0
12158,4.5
12004,5.0

I'm plotting an instrument reading as a function of below-ground depth. Because of what I'm visualizing, I want the axes to have a non-standard configuration, like this:
ggplot(data=f0101, aes(x=reading, y=depth)) +
    theme_classic() +
    scale_y_reverse() +
    scale_x_continuous(position="top") +
    geom_path()

This is perfect, except that I'd like the line smoothed, via stat_smooth() or similar. But, calling a smooth appears to throw off geom_path().
ggplot(data=f0101, aes(x=reading, y=depth)) +
    theme_classic() +
    scale_y_reverse() +
    scale_x_continuous(position="top") +
    geom_path() +
    stat_smooth()

What can I do to get the smoothing effect of stat_smooth() while still plotting the data in an admittedly non-standard configuration?
Thank you!

A: I may be wrong, but I think you probably want something like this:
dat %>%
  ggplot(aes(x = depth, y = reading)) +
  geom_path() +
  stat_smooth() +
  theme_classic() +
  scale_x_reverse() +
  scale_y_continuous(position = "top") +
  coord_flip()

which produces

For this, you're running the smooth with depth on the x and reading on the y, then flipping the coordinates.


text:
Q: How exactly does Encapsulation via Data Hiding Work in Python? Beginner I'm covering a section of Python on Class Polymorphism, specifically Encapsulation and Data Hiding.
The Example of such an Encapsulation is:
class Car:

    __maxspeed = 0
    __name = ""

    def __init__(self):
        self.__maxspeed = 200
        self.__name = "Corolla"

    def drive(self):
        print("Max speed is: " + str(self.__maxspeed))

    def setMaxSpeed(self,speed):
        self.__maxspeed = speed

car_a = Car()
car_a.drive()
car_a.setMaxSpeed(320)
car_a.drive()

The line car_a.drive() leads us to print("Max speed is: " + str(self.__maxspeed)). Where does the value for this specific self__maxspeed come from and why?
From the output, I see it's 200. And the output of car_a.setMaxSpeed(320) is 320. So the same question here with 320. And lastly, what's the function of __maxspeed = 0 and __nane = ""?
Sorry for the extensive question. I new to Python and these examples confused me. I greatly appreciate all help and time.

A:
Where does the value (200) for this specific self__maxspeed come from and
  why?

It comes from the __init__ method, which is invoked when you call Car():
self.__maxspeed = 200

Any time you create a Car it will have a maxspeed of 200 until you set it to something else.

And the output of car_a.setMaxSpeed(320) is 320. So the same question
  here with 320.

Here's the setMaxSpeed function:
def setMaxSpeed(self,speed):
    self.__maxspeed = speed

As you can see, it takes whatever you pass as the argument (320) and sets self.__maxspeed to it.  Nothing too mysterious about it.  That Car will now have a maxspeed of 320 until you set it to something else.

lastly, what's the function of __maxspeed = 0 and __name = ""

They don't have any function.  That is to say, your code never uses them for anything, so either their presence is a mistake, or you have some other code that does something with them, but based on the code you've presented, they are useless and you could delete them with no ill effects.

A: __init__() is invoked everytime whenever any object is created.
After creating the object, the __init__() is invoked automatically.
In this case, __init__() is initializing
__maxspeed with value of 200 . Then, you printed the value of __maxspeed (which is 200 ) using drive() function .
Later, you invoked setMaxSpeed() with 320 as a value. Inside this function, it assigned 320 to the __maxspeed variable of that object which has 200 as it's initial value.
Now, you again invoked drive() function to print the value of __maxspeed which is now 320 . So, 320 is printed.


text:
Q: gridview with footer row total in the final page of the grid protected void inderGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            decimal rowTotal = Convert.ToDecimal
            (DataBinder.Eval(e.Row.DataItem, "DC_No_Decimal"));
            //grdTotal = grdTotal + rowTotal;
            grdTotal += rowTotal;
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lbl = (Label)e.Row.FindControl("lblTotal");
            e.Row.Cells[3].Text = grdTotal.ToString("c");
            //lbl.Text = grdTotal.ToString("c");
        }
    }

from the above code i m getting total for every page in the grid view. Instead of getting total to every page i need all page total at the end of the grid view footer. Help Immediatly.
Thanks in advance

A: If you want the total of ALL pages, and for the footer to only appear on the last page, then you can't calculate the totals how you are doing.
At the moment your looping through every row on the gridview. If you are using paging the gridview won't be showing all the rows, so the total won't be correct.
Are you paging with a PagedDataSource or are you limiting the records returned from SQL etc? If you are using a DataSet and a PagedDataSource you'll be able to find the total from the DataSet (as this will contain all the records). Otherwise, you'll have to create a second query to calculate the total.
Then in terms of displaying the values in the footer, you'll have to add an IF statement to your ItemDataBound event to only display this if its the final page.

A: Noddy but you can try one more check in the if condition.
if(e.Row.RowType == DataControlRowType.Footer && inderGrid.PageCount == inderGrid.PageIndex + 1)
{
 //code here.
}

// Try this
    if(e.Row.RowType == DataControlRowType.Footer && inderGrid.PageCount == inderGrid.PageIndex + 1)
    {
      for (int i=0; i< inderGrid.Rows.Count; i++)
      {
         var currentRowCellVal = Convert.ToDecimal(inderGrid.Rows[i].Cells[0].Text);
         grdTotal += currentRowCellVal;
      }

      e.Row.Cells[3].Text = grdTotal.ToString("c");

    }

A: If you trying to display the record summery, please look this one about Displaying Summary Information in the GridView's Footer

A: What I do is setup the following in the code behind (This is just an example column):
int totalCallsTaken = 0;

public int CallsTaken(int value)
{
    totalCallsTaken += value;
    return value;
}

public int CallsTakenTotal()
{
    return totalCallsTaken;
}

Then in the ASPX page I put the following template field in:
<asp:TemplateField HeaderText="Calls Taken" FooterStyle-Font-Bold="true">
    <ItemTemplate>
        <%#CallsTaken(Convert.ToInt32(Eval("CallsTakenCount").ToString())).ToString("N0")%>
    </ItemTemplate>
    <FooterTemplate>
        <%#CallsTakenTotal().ToString("N0")%>
    </FooterTemplate>
</asp:TemplateField>

I hope that helps, Ian.

A: Just to be certain I'm understanding, you're saying you have a grid with say 100 items, but only 25 are shown at any given time. Then you want the footer to only display the sum of those 25 items that are displayed on the page.
There's a couple of options that you can do here for this:
1) Use JavaScript to calculate the total after the page has been rendered.
2) use intelligent SQL to only return those particular rows that you're wanting to display on the grid--and then keep your grid the same
3) calculate the visible rows in your code, and only add them when you need them.  Remember, you know in the code behind which Grid.PageIndex you're on as well as how many items each page has. With this knowledge, you should be able to determine via the row index if any given datarow will be rendered to the screen.

A: You need to generate all records total using the actual data.
If you are doing paging at the data-sire (database) side then you have total at the data-sore side - you may use the same SP that returns a page-full of records to return the total of all records. If you are retrieving all records and doing paging at the web server side then you may use the retrieve data-source to do the totaling.
From optimization perspective, you can compute the total once and store it in the view-state.
If you wish to show the footer on the last row then you can use ShowFooter - set it to true only on the last page.

A: All you need to do is check whether your row is in the current page and do the calculation.
For example, something like this:
if (e.Row.RowType == DataControlRowType.DataRow)
{
    decimal rowTotal = Convert.ToDecimal
    (DataBinder.Eval(e.Row.DataItem, "DC_No_Decimal"));
    if (e.Row.DataItemIndex >= inderGrid.PageIndex * inderGrid.PageSize
        && e.Row.DataItemIndex < inderGrid.PageIndex * inderGrid.PageSize + inderGrid.PageSize)
    grdTotal += rowTotal;
}

A: Try this,
using System.Linq;

dt.AsEnumerable().Select(x => x.Field<decimal>("DC_No_Decimal")).Sum().ToString();

you can use the code like this for get sum at the footer

gv.DataSource = dt;

gv.Columns[2].FooterText = dt.Rows.Count > 0 ? dt.AsEnumerable().Select(x => x.Field<decimal>("DC_No_Decimal")).Sum().ToString() : "";

gv.DataBind();


text:
Q: Shape Detection (circle, square, rectangle, triangle, ellipse) for a camera captured image + i OS 5 + Open CV I am new to OpenCV and need to know the method of OpenCV which detects different shapes (circle, square, rectangle, triangle, ellipse) in a camera captured image for iPhone.
so, could someone directs me to the right direction (references/articles/anything) that which techniques are better to get it done.
Thanks..
iOmi

A: First you will probably need to look at an edge detector such as Canny to extract the shapes into a binary image. (Although this may be expensive for the iphone)
For circles I would have a look at the HoughCircles.
For squares and rectangles you should look at the findContours method and the sample code squares.cpp in the samples directory when you downloaded opencv.
With a quick google search I was able to find an article about detecting shapes in C# which roughly corresponds to the methods you would use in another language while using the opencv library.
I have not used opencv in ios but I hope this will help get you started.


text:
Q: Pictures not attached in file I am using python win32 to drive excel 2010. I want to insert pictures into certain cells
import win32com.client as win32
from win32com.client import constants as constants

excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True

wb = excel.Workbooks.Add()
ws = wb.Worksheets('Sheet1')
ws.Name = 'PicDemo' ## rename worksheet

## select the active sheet
excel.Sheets('PicDemo').Select()
ws = excel.ActiveSheet
ws.Cells(9,9).Select()

## insert a png pic into this cell
ws.Pictures().Insert(pic file path)

I can see the pictures inserted on my PC, but when I send the excel to my friend, they couldn't see the picture but red cross with 'invalid link'.
I search the web and a lot of people complained about this glitch in excel 2010. I just want the pics saved absolutely without any dependent linking.
Is there a python win32 workaround?

A: Microsoft changed the behavior in Excel 2010 and 2013. Try this:
xlApp = win32.Dispatch(r'Excel.Application')
xlBook = xlApp.Workbooks.Open(filename)
xlSheet = xlBook.Sheets(sheet_name)
rng = xlSheet.Range("B2:F8")
height = rng.Offset(rng.Rows.Count, 0).Top - rng.Top
width = rng.Offset(0, rng.Columns.Count).Left - rng.Left
xlSheet.Shapes.AddPicture(image_file_name, False, True, rng.Left, rng.Top, height, width)

AddPicture has an option to save the image with the document.
Height and Width are required. In the code above I am using the Range to size the image.


text:
Q: PyEZ - Cron Job to connect to 8 routers and save the running config to 8 local files at a specific time stamp I am a starter to PyEZ. Can I write a cron job in PyEZ which will connect to 8 routers and fetch the running Config on device and save to 8 different files at a particular timestamp. Could you help me achieve the same.
I have already written a PyEZ code which will write the Base config to my local file.
Loading the config files to local file
from jnpr.junos import Device
from lxml import etree
dev = Device(host='hostname',port='22',user='root', password='sitlab123!' )
dev.open()class Create_Config():
def __init__(self):

    cnf = dev.rpc.get_config() ####Get Config as Str
            with open('myfile.txt', "w") as text_file:

            text_file.write(etree.tostring(cnf))

            text_file.close()

#####Return Configuration

def get_conf(self):

    return dev.cli("show configuration")

A: You can use python-crontab module along with PyEZ module.
Python-crontab
To create a new cron job is as follows:
from crontab import CronTab
#init cron
cron   = CronTab()

#add new cron job
job  = cron.new(command='/usr/bin/echo')

#job settings
job.hour.every(4)


text:
Q: permutations of a 3 object Help please,
Exercise: Work out the full multiplication table for the set of permutations of three objects.
I know there are $6$ permutations.
$(1,2,3), (2,3,1), (3,1,2), (2,1,3), (1,3,2)$ and $(3,2,1)$.
However, I don't know the order. I know order is very important.
Please help. Thanks.

A: For exemple $$(2,1,3)\circ(3,2,1)={ {1\, 2\, 3} \choose {2\, 1\,3}} \circ {{1\, 2\, 3}  \choose {3\, 2\, 1}}$$ Since for this multiplication
$$1\rightarrow 2 \rightarrow 2$$
$$2\rightarrow 1 \rightarrow 3$$
$$3\rightarrow 3 \rightarrow 1$$
we have $$(2,1,3)\circ(3,2,1)={ {1\, 2\, 3} \choose {2\, 3\,1}}=(2,3,1)=(123)$$
Order of  $(1,2,3)$ is 1.
Order of $(2,3,1)$ is 3 (because $(2,3,1)\circ(2,3,1)\circ(2,3,1)=(1,2,3)$).
Order of $(3,1,2)$ is 3 (because $(3,1,2)\circ(3,1,2)\circ(3,1,2)=(1,2,3)$).
Can you finish?


text:
Q: Laravel Horizon getting empty Dashboard Invalid or unexpected token I installed a Horizon 5.14.1 in Laravel 9.36.2
But when im gonna acess a dashboard i got this error
Uncaught SyntaxError: Invalid or unexpected token (at app.js?id=766b568d1924aa83b2a1f279d2c5ab9e:2:484352)
But in the console, php artisan horizon this works.
Someone can help me?


text:
Q: Executing a macro over a list of years I've been struggling with this problem for a while now. I have written a macro lets call it macro1 and I want to run it on a list of years lets say 1989 1990 1995 using a do or %do loop in open code but I cannot get it to work. I have been trying things along the lines of
%let years = 1989 1990 1995
%local i next_year
%do i=1 %to %sysfunc(%countw(&years));
    next_year = %scan(&years, &i);
    %macro1(&next_year);
%end

to no avail. Does anyone have a convenient solution to this problem? It seems like something that another programming language would be able to do in 3 lines (I have to use SAS though as its the only available language). Any help would be great.

A: Your code could work inside a macro definition if you include the required %LET needed to create a macro variable. And terminate your statements with the required semi-colons. And also leave off the semi-colons you don't need.
%macro test(years);
%local i next_year;
%do i=1 %to %sysfunc(%countw(&years));
  %let next_year = %scan(&years, &i);
  %macro1(&next_year)
%end;
%mend test;
%test(1989 1990 1995)

You could also eliminate the unneeded NEXT_YEAR variable completely.
%macro1(%scan(&years, &i))

Really you should just avoid using macro coding.  Stick to learning how to write actual SAS code first.  Wait to learn how to use macros to generate code until you know what code you want to generate. Complex DO loops are much easier to create using the real language of a data step instead of trying to code in a macro processor.
data _null_;
  do year=1989, 1990, 1995 ;
    call execute(cats('%nrstr(%macro1)(',year,')'));
  end;
run;

But sometimes wallpaper code is easier than over complicating things. Here is the three line program.
%macro1(1989)
%macro1(1990)
%macro1(1995)


text:
Q: ASP.NET 5 tag returning 500 Internal Server Error I am newbie with asp.net 5 and I wonder if someone could give me some guidance.
I have a project where I am rendering an Angular 2 app with asp.net 5 using the Steve Sanderson template (first version with 1.0.0-rc1-final).
It works ok on IIS Express but when I publish to Azure it doesn't.
I tried changing some settings but decided to publish on IIS locally to see, if could reproduce the error (500) but in an environment where I am more confortable.
And yes after publishing I have the same error but I still don't know how to get a more detailed one.
I have tried with:

*

*app.UseDeveloperExceptionPage();

*web.config

*web.config stdoutLogEnabled="true"

*web.config <httpErrors errorMode="Detailed" />

*etc

but none of them worked.
If I remove the tag in charge of rendering the app
   <app asp-prerender-module="ClientApp/boot-server" asp-prerender-webpack-config="webpack.config.js">Loading...</app> it works.
Thank you very much in advance.

A: Sorry I was a little be confused because I changed the template to RC2 and then back to RC1 and everything was kind of mess (about all in my mind).
I have studied a little be more of asp.net 5 and how to use DNVM, DNU and DNXs which I should have done before and now reviewing what is happening from the command line I have more clues of what to do.
Basically I had a problem with the dnx version first, then with one of the node dependency and now I am struggling with something to do with my webpack config which I have to review more deeply as well.
Thanks.


text:
Q: No puedo ver el Calendario de react-dates - Problema con css? Estoy tratando de hacer uso de la libreria react-dates (https://github.com/react-dates/react-dates/), mas especificamente del  DayPickerRangeController (http://react-dates.github.io/react-dates/?path=/story/daypickerrangecontroller--default).
La cosa es que puedo ver el calendario con el inspector de google chrome, pero no lo estoy visualizando en la pantalla.
Entiendo que es un problema de CSS, pero aun eliminando esta linea: import 'react-dates/lib/css/_datepicker.css'; y agregando estilos (como indica aca https://github.com/react-dates/react-dates/#overriding-styles) la cosa no cambia.
Cuando elimino la linea import 'react-dates/lib/css/_datepicker.css'; veo cosas en pantalla, pero claramente el CSS esta roto y no se ve el calendario como yo quiero

Dejo el codigo de mi componente, espero que alguien ya haya pasado por esto y me pueda dar una mano. Desde ya muchas gracias.

// Node Modules
import 'react-dates/initialize';
import { DayPickerRangeController } from 'react-dates';
import moment from 'moment';
import 'react-dates/lib/css/_datepicker.css';
import {
  useEffect, useRef, useState
} from "react";

// Hooks
import useSettings from "@/src/hooks/useSettings";

const Stays = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [focusedInput, setFocusedInput] = useState('startDate');
  const staysBoxRef = useRef();
  const staysBtnRef = useRef();

  const {
    saveSettings,
  } = useSettings();

  const setDates = ({startDate, endDate}) => {
    setStartDate(startDate)
    setEndDate(endDate)
  }

  const handleClick = () => {
    console.log("handle click")
    setIsOpen(!isOpen);
  }

  const handleClickOutside = e => {
    // Click outside means we did not click in the box or the button.
    const clickOutside = isOpen && staysBoxRef && !staysBoxRef?.current?.contains(e.target)
    && staysBtnRef && !staysBtnRef?.current?.contains(e.target) ? true : false;

    if (clickOutside) {
      handleClick();
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  });

  return (
    <>
    <button
      className={isOpen ? `item stay open` : `item stay`}
      ref={staysBtnRef}
      onClick={() => handleClick()}
    >
      Stay
      Add dates
    </button>

      <div
        className={isOpen ? `stay-selector-container open` : `stay-selector-container`}
        ref={staysBoxRef}
      >

          <DayPickerRangeController
            startDate={startDate} // momentPropTypes.momentObj or null,
            endDate={endDate} // momentPropTypes.momentObj or null,
            onDatesChange={({ startDate, endDate }) => setDates({ startDate, endDate })} // PropTypes.func.isRequired,
            focusedInput={focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
            onFocusChange={focusedInput => setFocusedInput({ focusedInput })} // PropTypes.func.isRequired,
            initialVisibleMonth={() => moment().add(2, "M")} // PropTypes.func or null,
          />

    </>

  );
};

export default Stays;

A: encontre una respuesta finalmente. El componente DatePicker solo debe inicializarse cuando su padre se este mostrando. En mi caso, el calendario esta dentro de un modal, por lo que la forma correcta de renderizarlo es hacerlo una vez que el modal fue abierto. Solo tuve que agregar esto a mi codigo y funciono sin problemas (la variable isOpen es quien controla si el modal esta abierto o cerrado)
{isOpen &&
    <DayPickerRangeController
        ...
    />
}


text:
Q: Shell Scripting for pattern recognition I have got a sample file containing following string. I need to have all the strings between 'if' and 'endif' in a single line by removing new lines (\n)
Sample is shown below. I needed this output using sed or in bash script.
Can anyone help me??
--sample String
if
ABC
BCD
DEF
endif
if
123
456
789
endif

--needed ouptput
ifABCBCDDEFendif

if123456789endif

A: Assuming the file contains only if-endif blocks:
awk '{ printf("%s", $0) } /^endif$/ { printf("\n") }'

With intervening text that should be unaltered, a slightly more complex approach is called for:
awk '/^if$/    { InIf = 1 }
     /^endif$/ { InIf = 0 }
               { printf("%s", $0) }
     !InIf     { printf("\n") }'

A: Suppose You have file tt1 which contains above string then use
cat tt1 | sed  's/\n//g' | sed  's/endif/endif\n/g'

A: A one liner will do this
If your file is file.txt then
Command
cat file.txt | tr -d "\n" | sed 's@endif@endif\n@g'


text:
Q: Evaluating the value of the norm of a function I am trying to show:
$$\|f_\alpha \|  = \| \alpha \|_{\ell^\infty} $$
Given that:
$$f_\alpha:\mathbb{R}^2 \rightarrow \mathbb{R}, \quad f_\alpha = \alpha_1 x_1 + \alpha_2 x_2$$
($\mathbb{R^2}$ is equiped with the $\|.\|_\infty$)
I am struggling to get passed the definition of the operator norm:
$$\|f\|= \sup \limits_{\substack{x \in \mathbb{R}^2\\ \|x\|_{\ell^\infty} = 1}} |\alpha_1 x_1 + \alpha_2 x_2 | = \sup \limits_{\substack{x \in \mathbb{R}^2\\ x \neq 0}} \frac{ |\alpha_1 x_1 + \alpha_2 x_2 |}{\|x \|_{\ell^\infty}}$$
Could someone point me in the right direction?

A: As @Alonso Delfín mentioned, the desired conclusion is wrong. Actually this question is related to the so-called dual norm. By Hölder inequality, for $a,x\in\mathbb{R}^n$, there holds
$$
\sum |a_ix_i|\leq\|a\|_{\ell^p}\|x\|_{\ell^q},
$$
where $p^{-1}+q^{-1}=1$ for $1\leq p,q\leq\infty$ and for each $p,q$ and $a$ there exists $x$ establishing the equality. Therefore we have
$$
\|\langle a,\cdot\rangle\|_{\ell^p}=\|a\|_{\ell^q},
$$
and that's why it is called the dual norm. As your case, it actually should be
$$
\|\langle a,\cdot\rangle\|_{\ell^\infty}=\|a\|_{\ell^1}.
$$


text:
Q: Displaying locations based on post codes on google map We tried to plot the locations based on post codes/address on google map using the google maps JS API V3. We need to first get longitude and latitudes for the post code/address and then plot the location on map. Because of this, each location plotting is counted as 2 requests and also there is a delay in showing up the locations on map.
My question is, is there a way in google maps API where in we can directly display the location on map without converting the postcode or address to longitude and latitude. Our application will have more than 100 users logging in and each user may have upto 1000 locations to show up. Even using the work license, the quota will exhaust quickly and delays.Any solution will be higly appreciated.
Thanks,
Harish

A: Calling this url help:
http://maps.googleapis.com/maps/api/geocode/json?address={YOUR_POSTAL_CODE}

For more information on GeoCoding https://developers.google.com/maps/documentation/javascript/geocoding#ReverseGeocoding
The more specific you set your address, the more specific the results...
ps... only your first question, the results... Not the displaying...

A: GeoCoding is the correct way to do it. Here is an example with a address search input from Google:
https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
Basically you just initialize the map on start and when the request to geocode the address returns the coordinates you set the map position. From what I can see this makes only one request to the Google Maps API.


text:
Q: Recursion in python - why isn't the sum overriden by 0 everytime the fuction is called within itself? I have a perfectly working recursion:
def sum_of_list(a_list):
    sum = 0
    for element in a_list:
        if isinstance(element, list):
            sum += sum_of_list(element)
        else:
            sum += element
    return sum

some_list = [1, 2, [3, 4], [5, 6]]
print(sum_of_list(some_list))

But I don't understand why the sum isn't overriden by 0 every time the line sum += sum_of_list(element) is executed? Because it calls the function back from the start where the sum equals to 0.

A: Each time sum_of_list() is called, the "sum = 0" line creates a local variable with the value 0 unique to that call of the function. If you had a global variable declared outside of this function declaration that is used as your "sum" variable, then it would be reset to 0 I believe
sum = 0
def sum_of_list(a_list):
    sum = 0
    for element in a_list:
        if isinstance(element, list):
            sum += sum_of_list(element)
        else:
            sum += element
    return sum
some_list = [1, 2, [3, 4], [5, 6]]
print(sum_of_list(some_list))


text:
Q: Database Query Slower with View I kind of have a feel for why the view is slower: The where clause is probably not applied at the same time.  The results do seem to be the same, though.  I am not sure what I can do about this, short of not using a view...which is not ideal, as I added the view to avoid code repetition, and I don't want to remove it if it isn't necessary.
Any suggestions for to change the way I am doing this so that I can use a view like in Command 1 but still have my query be executed as quickly as it is executed in command 2?
declare @foo varchar(50)
set @foo = 'be%'

ALTER VIEW [dbo].[wpvw_v]
AS
select distinct [name]
from kvgs kvg left join cdes cde
on kvg.kvgi = cde.kgi
group by [name], cde.kgi, kvg.mU
having count(cde.kgi) >= 2 or kvg.mU = 1 or
   exists (select [name] from FP x where x.name = kvg.name)

--Command 1: Takes 7 seconds
select [name] from wpvw_v where name like @foo

--Command 2: Takes 1 second
SELECT DISTINCT kvg.name
FROM         dbo.kvgs AS kvg LEFT JOIN
                      dbo.cdes AS cde ON kvg.kvgi = cde.kgi
where name like @foo
GROUP BY kvg.name, cde.kgi, kvg.mU
HAVING      (COUNT(cde.kgi) >= 2) OR
                      (kvg.mU = 1) OR
                      EXISTS
                          (SELECT     Name
                            FROM          dbo.FP AS x
                            WHERE      (Name = kvg.name))

A: Your query from view is like this:
SELECT name FROM (SELECT DISTINCT name FROM ...) WHERE name = @name;

while the second one is:
SELECT DISTINCT name FROM ... WHERE name = @name;

The two queries are very different and even though they produce the same result, the fiurst one can be answered only if the entire table is scanned to produce the distinct names, while the second one can scan only the names you're interested in.
The gist of the problem is that the presence of DISTINCT places a barrier that does not allow for the filtering predicate to move down the query tree to a place where is effective.
Update
Even if DISTINCT is not a barrier, on second look the second look there is a even more powerful barrier there: the GROUP BY/HAVING clause. One query filters after the GROUP and HAVING condition was applied, the other one before. And the HAVING condition has subqueries that reference name again. I doubt the QO can proove the equivalence of the filtering before the aggregate and filtering after the aggregate.

A: I didn't think the HAVING clause could accommodate what you'd posted, but I believe your view should be written to use UNIONs instead.  Here's my take on it:
ALTER VIEW [dbo].[wpvw_v] AS
WITH names AS(
  SELECT k.name
    FROM KVGS k
   WHERE EXISTS(SELECT NULL
                  FROM CDES c
                 WHERE c.kgi = k.kvgi
              GROUP BY c.kgi
                HAVING COUNT(c.kgi) > 1)
  UNION ALL
  SELECT k.name
    FROM KVGS k
   WHERE k.mu = 1
GROUP BY k.name
  UNION ALL
  SELECT k.name
    FROM KVGS k
    JOIN FP x ON x.name = k.name
GROUP BY k.name)
SELECT n.name
  FROM names n

If you want to filter out duplicates between the 3 SQL statements, change UNION ALL to UNION.  Then you can use:
SELECT n.name
  FROM wpvw_v n
 WHERE CHARINDEX(@name, n.name) > 0

A: As far as I know, the full result set of the view is collected and then further widdled down by the SELECT statement that uses it.  This is very different from your second SELECT statement, which doesn't collect any more than it needs.

A: You could try an inline tabled function (http://www.sqlhacks.com/index.php/Retrieve/Parameterized-View) but tbh I see that as a bit of a hack.
Honestly I'd probably go for the code repetition. I don't really see SQL in the same way that I see other code - I keep on seeing vast differences in performance between otherwise logically equivalent statements.

A: Without seeing more (the CREATE TABLE, INDEX, and CONSTRAINT statements for each table, for example) and preferably seeing the query plans as some sample data representative of the cardinality of the join as well, it's hard to say.
Possibly, there is a semantic difference between the queries that has to do with the collation under which the LIKE expression is evaluated, and it might be impossible to coax the same plan.
However, there is probably plenty of room for query tuning here. It seems unlikely you need to fully aggregate all the COUNT()s. You have three rather distinct conditions under which you want to see a "name" in your result. With UNION you might be able to make one or more of them simpler to calculate, and if concurrency isn't an issue, you might even write this as a multi-step user-defined table-valued function that accumulates the names in separate steps.

A: I believe the following reproduces your problem:
create table tbl (idx int identity(1,1), name varchar(50), val float)

declare @cnt int
set @cnt=0
while @cnt < 10000
begin
insert tbl select char(CAST(rand()*256 AS INT)), rand()
set @cnt = @cnt + 1
end
go
create view tbl_view as select distinct name from tbl group by name having sum(val) > 1

Then if you run the following query:
SET STATISTICS IO ON
declare @n varchar(50)
set @n='w%'
select * from tbl_view where name like @n
SET STATISTICS IO OFF
GO
SET STATISTICS IO ON
declare @n varchar(50)
set @n='w%'
select distinct name from tbl where name like @n group by name having sum(val) > 1
SET STATISTICS IO OFF

You get the following:
(1 row(s) affected)
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'tbl'. Scan count 1, logical reads 338, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1 row(s) affected)
Table 'tbl'. Scan count 1, logical reads 338, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

The view forces it to work off a sub-table first and only then to apply the filter. Now, if you modify the view and remove the DISTINCT, this does not change. But if you modify the view to remove the group by:
create view tbl_view as select name from tbl where val > 0.8 group by name
go
SET STATISTICS IO ON
declare @n varchar(50)
set @n='w%'
select * from tbl_view where name like @n
SET STATISTICS IO OFF
GO
SET STATISTICS IO ON
declare @n varchar(50)
set @n='w%'
select name from tbl where val > 0.8 and name like @n group by name
SET STATISTICS IO OFF

Then you get the same results for both queries:
(1 row(s) affected)
Table 'tbl'. Scan count 1, logical reads 34, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1 row(s) affected)
Table 'tbl'. Scan count 1, logical reads 34, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

So it does seem like the HAVING is the barrier.

A: Table-valued functions tend to be quicker than views, assuming your WHERE conditions are known and can be supplied in parameters.
One advantage of table-valued functions is that you can have multiple statements, so you can convert OUTER JOINs to quicker INNER JOINS in subsequent statements.  So instead of this:
INSERT INTO @resultTable
    table1_id,
    table1_column,
    table2_column,
    table3_column
SELECT
    table1.id,
    table1.column,
    table2.column,
    table3.column
FROM
    table1
    INNER JOIN table2 ON table2.table1_id = table1.id
    LEFT OUTER JOIN table3 ON table3.table1_id = table1.id

return @resultTable

... you can do this, which I find is always faster:
INSERT INTO @resultTable
    table1_id,
    table1_column,
    table2_column,
SELECT
    table1.id,
    table1.column,
    table2.column,
FROM
    table1
    INNER JOIN table2 ON table2.table1_id = table1.id

UPDATE @resultTable SET
    table3_column = table3.column
FROM @resultTable AS result
    INNER JOIN table3 ON table3.table1_id = result.table1_id

return @resultTable


text:
Q: Big data with spatial queries/indexing Currently I am using SQL Server and having issues with scaling an unrelated 100 million records doing about a million writes every day, 32 GB of ram used up and CPU at 80%-90% most of the time. This makes me weary of staying with SQL server, but if possible I'd like to stay with it. I've been looking into mongoDB.
I have a new project and it will require to store about 100 million spatial records, all as polylines and with 15 or so attributes associated with the geometry. I know SQL Server and mongoDB both support spatial indexing, with mongoDB using an inferior (as I read) Geohash compared to R-tree index.
I think they balance out in terms of performance for the GIS data because I feel even though mongoDB has an inferior Spatial index, it will be made up in terms of just shear performance of its read speed compared to SQL Server.
The real problem that I have is for every single polyline, there will be time data that is tied to each polyline. The number is anywhere from 20 to 2000 depending on how well it can scale. That's 2 billion now and potential to grow to 200 billion.
The polyline data will not exceed 100 million, and will be about 1KB per record (100 GB). If we store all the data unnormalized, and don't care about duplicating the GIS data in effort to avoiding doing a JOIN, that is 2-200 TB, basically not manageable by me.
Therefore I think some de-normalization is needed, GIS data in one table/collection and associated timedata in another.
At a moments notice, a map request will come in and request a tile which should query all the GIS information for that bounding box (think spatial intersection) and using this result, timedata AVERAGE over a time range needs to be queried for the selected polylines. The dataset has to be together (JOINED) when it hits the map renderer. All this will happen 12-20 times a second as a map is being panned, as the map will color the polylines according to the timedata.
My question is, given mongoDB spatial indexing performance, will going from 100 million to say 250,000 records be an issue when using geoIntersects?
Then once the 250,000 polylines are found, I would need to query the timedata for the time assoicated with the 250,000 polylines for a certain WHERE clause, most likely a time range. Can mongoDB accomplish this given the table will contain over 2 billion records, and do it sub-second?
Right now I am able to go from 2 million to 200,000 polylines in SQL Server 2012 at around 4 seconds using a spatial index. This is acceptable, but it's not taking into considering the timedata at all and its 50 times less data then there will be.
I feel like doing a JOIN operation with mongoDB will defeat the purpose of mongoDB and not yield better performance than SQL Server.
What is the database recommendations for accomplishingly this task?
Key Points:

*

*Support spatial indexes in order to correctly query the GIS data.

*Data will only be written annually, basically 100% reads.

*most queries on timedata will need an AVERAGE within a timerange

*Low load, only 2-10 users connected at any given time
The budget is around $1000 a month for the server/server(s).
Edit:
The time data consists of the reported mph at that segment of a road in 15 minute intervals. A user-search would be "I want to see the average speeds of this road on fridays, in the past 3 months"
The map engine then renders it according to a legend based on average speeds. The map engine needs to know what color each road/polyline will be, so if there are X roads being viewed on the map, it needs X values along with the X polylines.

A:
Data will only be written annually, basically 100% reads.
...most queries on timedata will need an AVERAGE within a timerange

Those two things, 100% reads and an aggregation sounds like a data warehouse/star structure would be worth exploring. There's alot of concepts to understand to properly build such a structure, but we can hit on a potential design.

The time data consists of the reported mph at that segment of a road
  in 15 minute intervals. A user-search would be "I want to see the
  average speeds of this road on fridays, in the past 3 months"

When you say in 15 minute intervals, I am assuming we might have 5 people who passed through that segment between 1:15 PM - 1:30 PM, and so have 5 records for that time period.
This is going to be an uncomfortable exercise for anyone who has never built a data warehouse before, but as someone who was very skeptical of these approaches and have put them into practice, I've seen that you can get a huge performance boost.  In other words, I am a skeptical convert.  Usually you keep your normalized database for operational transactions, then nightly/weekly populate your data warehouse from it.
It is important to know what types of queries you will be hitting this with, as we design the star structure to lend itself to them.  It doesn't severely constrain the queries though, and you still have alot of flexibility.  There's lots of generic analytic/OLAP tools that build upon star structures, and their flexibility is evidence of this.
Date/Time Dimensions
First thing we'll do is create a time and date dimension.  Each row in the time dimension represents a 15 minute interval.  I would document somewhere start/end inclusive/exclusive so any times that are on the fence are clearly included/excluded.  It only has 96 rows, one for each 15 minute interval in a day.
Id,StartTime(inclusive),EndTime(exclusive)
 1, 0:00, 0:15
 2, 0:15, 0:30
...
95,23:30,23:45
96,23:45,24:00

The date dimension can be designed a couple different ways.  To maximize analytical flexibility, we usually have a row for every real day that our data covers.  This seems ridiculous to anyone with a normalize DB design background, but it's pretty standard practice in data warehouses, and there literally are entire chapters in Data Warehouse books that explain why.  There are scripts out there that help you generate the entries in a date dimension.  If your data covers 2000 and you plan to reload the database over the next few years, then you would create entries for every single day from 2000 to 2020 which is only 7300 rows(20 years*365 days). Consider this can easily be cached in a very small amount of memory.
Id,Date(date),Year(smallint),Month(tinyint),Day(tinyint),MonthName,MonthAbbreviation,DayOfWeekNumber(tinyint),DayOfWeekName....
1000,2015,5,15,...
1001,2015,5,16,...
1002,2015,5,17,...

The reason for all of the extra columns such as DayOfWeekNumber and DayOfWeekName is to support very straightforward aggregations on those properties or combinations.  Makes groupby DayOfWeekNumber very easy so you can do trend analysis in different ways.
Poly Dimension
For a poly dimension, you'd have one row per road segment.  I made this choice because multiple time entries would share a single poly segment, and thus we'd want polyIds in the fact table below to group on.
Speed Facts Table
This table is going to be the one with the huge number of records.  Each row in your fact table should be as tiny as possible.  This maximizes I/O throughput, speed of aggregation, and ability to cache as much as possible in memory.
For example, DateId should be smallint since 2 bytes is enough to represent 32767 IDs, much more than the 7300 needed for 20 years of data with room for 60 more years.  TimeId would be a tinyint.  People will say storage is cheap, but that's not the driving factor.  I/O throughput and cache utilization are why small row size is important(and thus rows per page).
RoadSegmentId, TimeId, DateId, Speed
1,1,1,45
1,1,1,47
1,1,1,92
1,2,1,55
1,2,1,67
1,2,1,91
2,1,1,55
2,2,1,67
2,2,1,91
...

Querying
"I want to see the average speeds of this road on fridays, in the past 3 months"
Select rsd.Polygon, Avg(f.Speed)
From SpeedFacts f
Inner Join DateDimension dd on f.DateId = dd.Id
Inner Join RoadSegmentDimension rsd on f.RoadSegmentId = rsd.Id
Where dd.DayOfWeekNumber = 5 and dd.Date > '3/6/2015' --you could of course get current date, subtract 3 months to make this more generic
   and rsd.Polygon.STIntersects(@boundingBox)
Group By f.RoadSegmentId, rsd.Polygon

So there are a few things to notice.  How SQL server chooses to optimize this is hard to say without testing, but the structure allows for a path that seems efficient:

*

*Select from DateDimension rows greater than 3/6/2015 and DayOfWeekNumber 5.  Each of these should have an index and page reads should have good utilization because the rows physical ordering will place them in the same pages.  This produces 12 rows, one for each week.

*Now SQL Server has only 12 DateId's, and can use the index on SpeedFacts.DateID to narrow down what rows/pages from SpeedFacts to read.

The SpeedFacts.DateId index is alot smaller than if we had a SpeedFacts.Date column that was an actual date type.  So the index over those millions of rows is much smaller and thus SQL Server can read through it much faster.  Thus narrowing down the number of rows it is interested in the fact table.
The only thing that worries me is depending on patterns of your data, this probably doesn't eliminate the need to perform STIntersects on every single polygon in the RoadSegmentDimension.  If you have sparse speed measurements, where alot of segments don't have any readings for certain timeframes, then it's possible the third step of joining to RoadSegementDimension will eliminate alot of polygons and then applying the StIntersects will only be necesary on the remaining polygons.
Regardless, the hope is it can narrow down the number of fact rows very efficiently before performing the spatial comparison.
Either way I think you will see significant performance with this kind of structure over more traditional structures, and would bet the performance gain is greater than any difference between the engines.
I don't know alot about MongoDB, but I've used other flavors of NoSQL/document/json databases, and I'm not really sure that kind of engine really lends itself well to this type of analysis.

A: If you end up wanting to explore the Geohash route more deeply, here's a more fleshed-out implementation of Geohash related functions for TSQL in which you might be interested.

*

*QalGeohash-TSQL
As to the debate between the performance of R-Tree Indexes versus Integer-based Geohashes, I have different experiences related to big data scenarios. The trade-off is the same as in software engineering between using index Arrays, HashTables, and Trees. Each has use cases in which they are superior to the other two. The same holds for R-Tree Indexes versus Geohash clustering.


text:
Q: How can I re-arrange this regex to work with the MM/DD/YYYY format? There's a brilliant bit of regex by Macs Dickinson that validates DD/MM/YYYY strings taking into account allowable days for each month (eg 28 vs 30 vs 31) and the possibility of February 29th but only on leap years:
^(((0[1-9]|[12][0-9]|3[01])[- /.](0[13578]|1[02])|(0[1-9]|[12][0-9]|30)[- /.](0[469]|11)|(0[1-9]|1\d|2[0-8])[- /.]02)[- /.]\d{4}|29[- /.]02[- /.](\d{2}(0[48]|[2468][048]|[13579][26])|([02468][048]|[1359][26])00))$

I'm looking to re-arrange this to use for MM/DD/YYYY strings, but I can't wrap my head around it enough to get it there. Any help is much appreciated!

A: The regex you posted has a mistake in the Leap Year section.
Otherwise it is a fair facsimile of that form.
I've fixed his mistake, and rearranged the day/month for you.
It now matches MM/DD/YYYY.
((?:0[13578]|1[02])[- /.](?:0[1-9]|[12][0-9]|3[01])|(?:0[469]|11)[- /.](?:0[1-9]|[12][0-9]|30)|02[- /.](?:0[1-9]|1\d|2[0-8]))[- /.](\d{4})|(02[- /.]29)[- /.]([0-9]{2}(?:0[48]|[13579][26]|[2468][048])|(?:[02468][048]|[13579][26])00)
Formatted / explained
   (                                            # (1 start), Non-LeapYr  MM/DD
        (?: 0 [13578] | 1 [02] )                     # Months with 31 days
        [- /.]
        (?: 0 [1-9] | [12] [0-9] | 3 [01] )
     |
        (?: 0 [469] | 11 )                           # Months with 30 days
        [- /.]
        (?: 0 [1-9] | [12] [0-9] | 30 )
     |
        02                                           # February with 28 days
        [- /.]
        (?: 0 [1-9] | 1 \d | 2 [0-8] )
   )                                            # (1 end)
   [- /.]
   ( \d{4} )                                    # (2), Any year 0000 - 9999

|                                             # OR,

   ( 02 [- /.] 29 )                             # (3), LeapYear  MM/DD
   [- /.]
   (                                            # (4 start), Leap Years 0000 - 9996
        [0-9]{2}
        (?: 0 [48] | [13579] [26] | [2468] [048] )
     |
        (?: [02468] [048] | [13579] [26] )
        00
   )                                            # (4 end)


text:
Q: How to run a Django post_save signal as a background process? I have a post_save attached to a model which loads a substantial amount of information via json response from an external API when it is created. Unfortunately this takes long enough that heroku times out before it ever has a chance of finishing.
After doing some research is seems the best way to do this is as a background process.
What would be the best way to run a post_save signal asynchronously?
After reading about celery it seems too heavy-weight for one process. Are there other methods that are trusted?
from django.db.models.signals import post_save
import urllib2
import json

class Foobar(models.Model):
    # ... fields ... #

def foobar_post_save(sender, instance, created, *args, **kwargs):
    """Load info from external API

    data
    ----
    sender - The model class. (Foobar)
    instance - The actual instance being saved.
    created - Boolean; True if a new record was created.
    *args, **kwargs - Capture the unneeded `raw` and `using`(1.3) arguments.
    """

    if created:
        url_to_open = <api_url>
        resp = urllib2.urlopen(url_to_open)
        data = json.loads(resp.read())
        # ... load data ... #

post_save.connect(foobar_post_save, sender=Foobar)

A: I ended up finding the answer with rq which has a nice Heroku documentation
And implemented like so:
from django.db.models.signals import post_save
import urllib2
import json
from rq import Queue
from worker import conn

q = Queue(connection=conn)

class Foobar(models.Model):
    # ... fields ... #

    def load_data(self):
        url_to_open = <api_url>
        resp = urllib2.urlopen(url_to_open)
        data = json.loads(resp.read())
        # ... load data ... #

def foobar_post_save(sender, instance, created, *args, **kwargs):
    """Load info from external API

    data
    ----
    sender - The model class. (Foobar)
    instance - The actual instance being saved.
    created - Boolean; True if a new record was created.
    *args, **kwargs - Capture the unneeded `raw` and `using`(1.3) arguments.
    """

    if created:
        q.enqueue(instance.load_data, timeout=600)

post_save.connect(foobar_post_save, sender=Foobar)

A: I'm not 100% sure that this is exactly what you want, but I've done a similar thing, so I think this will do what you need.
import multiprocessing

proc = multiprocessing.Process(
    target = foobar_post_save,           #the function to be run
    args = (sender,instance,created),    #the arguments to pass to the function
    name="foobar post save")             #name not strictly necessary
proc.start()     #starts the process
proc.join(60)    #wait until this is done; optional time limit is in seconds

For more on this, see here: Python 3 multiprocessing module docs.

A: Given you need an asynchronous approach, what about using celery, to run your long running task and then trigger that from your app's post_save.

A: Another idea using Celery or something similar to start a task in the background. So, you create a new task on Celery after post_save and then you can monitor that task to stop / pause / get success signal / etc.


text:
Q: Do headers slow down PHP code? If you have a large class that executes after output(headers/text) is already sent, will that have any affect on your applications performance?
Edit: To clear things up, when output is sent, default headers are sent with it.

A: The execution speed of the PHP will be the same regardless of whether the headers have been sent.
If you can send some HTML (for example the <head> section) then it can actually make your page load faster, as the client can begin to download CSS and javascript files, and start to render the page if you send enough HTML.

A: Headers slowing php code : i think no more than any other instructions, i may be wrong.
And the fact that output had already been send doesn't mean further code will run slower, or that would be a very strange behavior.

A: I suppose that you say that some content is already flushed out to the browser in which case, adding new headers may not have any impact on the previously sent headers - but doing something unnecessarily that doesnt affect anything will increase the overhead for sure(and for nothing). This is assuming that all the functionality that the "large class" does is to add headers.
You should consider re-arranging some code then.
http://us3.php.net/manual/en/function.header.php


text:
Q: How to update Tkinter window every time image is processed I'm trying to create a GUI that will display an image that is taken every 10 seconds and it's processed counter part. I'm having trouble getting the GUI window to update the two images when they get overridden in the file system.
Here's the code I have so far
import cv2
import threading
from imageai.Detection import ObjectDetection
import os
from tkinter import *
import os
from PIL import ImageTk,Image
root = Tk()
canvas = Canvas(root, width = 2000, height = 2000)
canvas.pack()
execution_path = os.getcwd()
inimg = ImageTk.PhotoImage(Image.open(os.path.join(execution_path , "test.jpg")))
outimg = ImageTk.PhotoImage(Image.open(os.path.join(execution_path , "testnew.jpg")))
def capture():
    print("Capturing...")
    videoCaptureObject = cv2.VideoCapture(0)
    ret,frame = videoCaptureObject.read()
    cv2.imwrite("test.jpg",frame)
    print("Done capturing.")
    print("Finding")
    totalPersons = 0
    detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "test.jpg"), output_image_path=os.path.join(execution_path , "testnew.jpg"))
    for eachObject in detections:
     if(eachObject["name"] == "person"):
        totalPersons += 1
    print("Total persons " + str(totalPersons))

detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
execution_path = os.getcwd()
detector.setModelPath(os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))
detector.loadModel("fastest")

def run():
    threading.Timer(10.0, run).start()
    canvas.create_image(20, 20, anchor=NW, image=inimg)
    canvas.create_image(750, 500, anchor=SW, image=outimg)
    root.mainloop()
    capture()
run()

A: try to use
root.update_idletasks()
to update tkinter  GUI window.


text:
Q: Removing redundant SQL queries (in PHP) by using JOIN I am trying to clean up my SQL queries and use JOIN in just ONE where I once used TWO queries.
Here is former code (in PHP):
$cat = "books";  // as a test

$query = "SELECT category, cat_id FROM master_cat WHERE category = '{$cat}'";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {
    $cat_id = $row['cat_id'];
}

$sql = mysql_query("SELECT item, spam, cat_id FROM items WHERE cat_id = ' " . $cat_id . "' ORDER BY TRIM(LEADING 'The ' FROM item) ASC;");

while ($row = mysql_fetch_assoc($sql))
    if ($row['spam'] < 2)
        $output[] = $row;

print(json_encode($output));  // added!

I am trying to just remove the top query and use a JOIN.  The updated SQL statement is this:
EDIT:  I made a mistake in original question.  Basically user input gives us $cat = "something".  There is "something" in master_cat table with a cat_id.  That cat_id is also in the items table.  That is where I need the tables to connect -- and the WHERE clause needs to incorporate "$cat"
UPDATED QUERY:
    $result = mysql_query("SELECT i.item, i.spam, mc.cat_id AS Category
FROM items as i
INNER JOIN master_cat as mc
ON i.cat_id = mc.cat_id
WHERE i.cat_id = '{$cat}'
ORDER BY TRIM(LEADING 'The ' FROM i.item) ASC;");

then:
   while ($row = mysql_fetch_assoc($result))
    if ($row['spam'] < 2)
        $output[] = $row;

I receive this in the browser:
null.
Can someone guide me on how to properly use JOIN which I know will REALLY clean things up here and make more efficient coding.  I just watched a tutorials but still am not quite getting it.
HERE IS FINAL CODE THAT WORKS
$cat = $_POST['category']; // yes, yes, injection.  this is just the short version.

$result = mysql_query("SELECT i.item, i.cat_id, i.spam,  mc.cat_id, mc.category, TRIM(LEADING 'The ' FROM i.item) as CleanItem
FROM items as i
INNER JOIN master_cat as mc
ON i.cat_id = mc.cat_id
WHERE mc.category = '{$cat}'
ORDER BY CleanItem ASC;");

while ($row = mysql_fetch_assoc($result))
    if ($row['spam'] < 2)
        $output[] = $row;

A: $sql = "SELECT i.item, i.spam, mc.cat_id AS Category
FROM items as i
INNER JOIN master_cat as mc
ON i.cat_id = mc.category
WHERE items.cat_id = '{$cat_id}'
ORDER BY TRIM(LEADING 'The ' FROM item) ASC";

Since you aliased it you have to keep it as aliased: fix the second to last line:
WHERE i.cat_id = '{$cat_id}'

A: You have reference the items table by its full name in the WHERE clause, you should be using the alias you created (i).
You also have an ambiguous column reference item in your ORDER BY clause.
Try changing the last two lines to:
WHERE i.cat_id = '{$cat_id}'
ORDER BY TRIM(LEADING 'The ' FROM i.item) ASC

You should also inspect mysql_error() to get a string description of the error, which would have pointed you straight to the problem.

A: Try this one:
$sql = "SELECT i.item, i.spam, mc.cat_id AS Category
FROM items as i
INNER JOIN master_cat as mc ON i.cat_id = mc.cat_id
WHERE i.cat_id = '{$cat_id}'
ORDER BY TRIM(LEADING 'The ' FROM item) ASC";

If you alias items as i, you should use i everywhere else. Besides, mc.category does not seem to exist so I replaced it with mc.cat_id. What does mysql_error say?

A: You are probably getting false as your response to the initial query and not a result set
You should join on i.cat_id = mc.cat_id
You should also probably perform your i.item cleaning (i.e. removing 'The ') in the select statement (even as a seperate field if you need to keep i.item intact) and then order by that field.
You should reference i.cat_id = '{$cat_id]}', not items.cat_id


text:
Q: Find date from image/text I have dates like this and I need regex to find these types of dates
   12-23-2019
   29 10 2019
   1:2:2018
   9/04/2019
   22.07.2019

here's what I did
first I removed all spaces from the text and here's what it looks like
   12-23-2019291020191:02:2018

and this is my regex
    re.findall(r'((\d{1,2})([.\/-])(\d{2}|\w{3,9})([.\/-])(\d{4}))',new_text)

it can find 12-23-2019 , 9/04/2019 , 22.07.2019 but cannot find 29 10 2019 and 1:02:2018

A: You may use
(?<!\d)\d{1,2}([.:/ -])(?:\d{1,2}|\w{3,})\1\d{4}(?!\d)

See the regex demo
Details

*

*(?<!\d) - no digit right before

*\d{1,2} - 1 or 2 digits

*([.:/ -]) - a dot, colon, slash, space or hyphen (captured in Group 1)

*(?:\d{1,2}|\w{3,}) - 1 or 2 digits or 3 or more word chars

*\1 - same value as in Group 1

*\d{4} - four digits

*(?!\d) - no digit allowed right after

Python sample usage:
import re
text = 'Aaaa 12-23-2019, bddd   29 10 2019 <===   1:2:2018'
pattern = r'(?<!\d)\d{1,2}([.:/ -])(?:\d{1,2}|\w{3,})\1\d{4}(?!\d)'
results = [x.group() for x in re.finditer(pattern, text)]
print(results) # => ['12-23-2019', '29 10 2019', '1:2:2018']


text:
Q: What's the meaning of zsh's default IFS=$' \t\n\C-@' , the "\C-@" part What's the meaning of zsh's default IFS=$' \t\n\C-@', the \C-@ part

A: \C-@ denotes null character here. This string inside $'…' expands to the actual null character.
Zsh supports null characters in strings. Some other shells don't, so trying to put the null character in their IFS doesn't make sense. Compare this answer.
In addition other shells may not expand \C- sequences inside $'…' or may not support $'…' at all (see this question).