text:
Q: Vaadin hilla property call does not exist I was trying to create a vaadin hilla application, trying to save a person's details. Created endpoint and the person object as well, but in generated files, the error is showing as below.

[TypeScript] Property 'call' does not exist on type 'PersonDetails'.

The application is running, pages also came up but with error.
@Endpoint
@AnonymousAllowed
public class PersonEndpoint {

    private InterPersonService personService;

    @Autowired
    public PersonEndpoint(InterPersonService personService) {
        this.personService = personService;
    }

    @Nonnull
    public String savePerson(PersonDetails person) {
        return this.personService.savePerson(person);
    }

}

Vaadin hilla application to save a person's details. Expected to set the value from the textbox to the generated object and the data will be available in the endpoint save method.


text:
Q: How to center image inside a circular imageview? I have an ImageView. I have done some manipulation to make it circular. All is good. But, I realize that the image is not centered. Apparently, the image is positioned from the top left of the ImageView. How can I make this image centered to the circular ImageView?
Here is my code:
// Decode the Byte[] into bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
// Set the Bitmap into the imageView
mImage.setImageBitmap(bmp);

//circle img
int wbmp = bmp.getWidth();
int hbmp = bmp.getHeight();
int diameter;
if (wbmp > hbmp) {
   diameter = hbmp;
} else {
   diameter = wbmp;
}

Bitmap resized = Bitmap.createScaledBitmap(bmp, wbmp, hbmp, true);
Bitmap conv_bm = ImageHelper.getRoundedRectBitmap(resized, diameter);

mImage.setImageBitmap(conv_bm);
// TODO Auto-generated method stub
//circle img ends

and this is the ImageHelper:
public class ImageHelper {

//circle image
public static Bitmap getRoundedRectBitmap(Bitmap bitmap, int radius) {
    Bitmap result = null;
    try {

        Bitmap sbitmap;
        if(bitmap.getWidth() != radius || bitmap.getHeight() != radius) sbitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,false);
        else sbitmap = bitmap;

        result = Bitmap.createBitmap(sbitmap.getWidth(), sbitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);

        int color = 0xff424242;
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, sbitmap.getWidth(), sbitmap.getHeight());

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawCircle(sbitmap.getWidth() / 2, sbitmap.getHeight() / 2,
                sbitmap.getWidth() / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

    } catch (NullPointerException e) {
    } catch (OutOfMemoryError o) {
    }
    return result;
}
//circle image ends

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Segmentation Fault (core dumped) - vectors I am working at algorithm which can calculate length of curve using elementary segments. So if I have vector of x and y coordinates of curve I need to calculate number of this elementary segments. I've invented my own recursive algorithm for that. There is a code:
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;
//***********************************************
inline double Pitagoras(double xp, double yp, double xf, double yf)
{
    return sqrt((xp - xf)*(xp - xf) + (yp - yf)*(yp - yf));
}
//***************************************************
inline double calculateX(double xp, double yp, double a, double b, const double eps)
{
   double delta;
   double x1, x2;

     delta = (-2.0 * xp + 2.0 *a*b - 2.0 *a*yp)*(-2.0 * xp + 2.0 *a*b - 2.0 *a*yp)
        - 4.0* (1.0 + a*a)*(xp*xp + yp*yp + b*b - 2.0*b*yp - eps*eps);

     x1 = (-(-2.0 * xp + 2.0 *a*b - 2.0 *a*yp) - sqrt(delta))/(2.0 * (1.0 + a*a));
     x2 = (-(-2.0 * xp + 2.0 *a*b - 2.0 *a*yp) + sqrt(delta))/(2.0 * (1.0 + a*a));

   if(x1 >= xp)
     return x1;
     else
       return x2;
}
//***************************************************
inline double calculateY(double x, double a, double b)
{
  return a*x + b;
}
//***********************************************
unsigned long algorithmKolmogorow(double xp, double yp, double xf,
double yf, const double eps, vector<double> &vectorX, vector<double> &vectorY);
//***********************************************
int main()
{
    vector<double> vctrY; //vector of value of function
    vector<double> vctrX; //vector of x
    double xP,yP,xF,yF; //coordinates of two points on the curve
    const double Eps = 0.0001; //length of elementary line

      for(double x=1.0; x<=5 ;x +=0.001)
        {
          vctrX.push_back(x);
          vctrY.push_back(x*x); //f(x) = x^2
        }

    xP = vctrX[0];
    yP = vctrY[0];
    xF = vctrX[1];
    yF = vctrY[1]; //set beginning value

    cout<<algorithmKolmogorow(xP, yP, xF, yF, Eps, vctrX, vctrY)*Eps;

    return 0;
}
//***************************************************
unsigned long algorithmKolmogorow(double xp, double yp, double xf,
 double yf, const double eps, vector<double> &vectorX, vector<double> &vectorY)
{
    static unsigned long N; //licznik
    static unsigned long i = 1;
    double d;
    double a,b;

      d = Pitagoras(xp, yp, xf, yf);

         if(d >= eps){
            a = (yf - yp)/(xf - xp);
            b = yp - a*xp;
            xp = calculateX(xp, yp, a, b, eps);
            yp = calculateY(xp, a, b);
            N++;
         }

           else{
             i++;
             xf = vectorX[i];
             yf = vectorY[i];
             //cout<<i<<"\t"<<vectorX[i]<<"\t"<<vectorY[i]<<endl;
           }

             if(i < vectorX.size())
              N =  algorithmKolmogorow(xp, yp, xf, yf, eps, vectorX, vectorY);

return N;
}

In main as you can see, I'm setting x,y coordinates for parabolic function. When Eps is big for example Eps = 0.001 everything works. If I set smaller value like Eps = 0.0001 then I get error like in topic and program stop running. I've completely no idea why.
I can add any new informations which you need (about my compiler, IDE, OS etc).
Rafal

A:          i++;
         xf = vectorX[i];
         yf = vectorY[i];
         //cout<<i<<"\t"<<vectorX[i]<<"\t"<<vectorY[i]<<endl;
       }

         if(i < vectorX.size())

That will exceed the bounds of the vector by 1.  Maybe you needed if(i < vectorX.size()-1)  or (noting the comment by AndyG) maybe you needed the i++ to be below those two uses of i.

A: You are probably running out of stack space due to the recursion.
A quick hack around this is to raise the stack size using ulimit in the shell, e.g.
(ulimit -s unlimited; ./my_program)

The real fix however is to remove the recursion.  algorithmKolmogorow looks like it does tail-recursion only, which can always be converted to a loop:
unsigned long algorithmKolmogorow(double xp, double yp, double xf,
 double yf, const double eps, vector<double> &vectorX, vector<double> &vectorY)
{
    static unsigned long N; //licznik
    static unsigned long i = 1;
    double d;
    double a,b;

    while(true) {
      d = Pitagoras(xp, yp, xf, yf);

         if(d >= eps){
            a = (yf - yp)/(xf - xp);
            b = yp - a*xp;
            xp = calculateX(xp, yp, a, b, eps);
            yp = calculateY(xp, a, b);
            N++;
         }

           else{
             i++;
             if(i >= vectorX.size())
               return N;
             xf = vectorX[i];
             yf = vectorY[i];
             //cout<<i<<"\t"<<vectorX[i]<<"\t"<<vectorY[i]<<endl;
           }

    }

}

There also fixes the problem of accessing the vectors one element passed their bounds.
There are still some problems:

*

*N should be initialized

*algorithmKolmogorow can only be used once per program invocation.  Remove the static from N and i to fix that.

A: Your value for Eps is too small.  It causes the algorithm to progress too slowly, which means you run out of stack space before the calculation can finish.  I increased Eps to 0.005 and the code runs fine.  Not sure if it produces the right answer though; you'll have to check.
Also, you need to change these lines:
xf = vectorX[i];
yf = vectorY[i];

To this:
xf = vectorX[i-1];
yf = vectorY[i-1];

Otherwise you access past the last vector element on the last iteration.  You may also want to do a tolerance study on Eps to see how small it has to be to get an accurate calculation.


text:
Q: GORM criteria query filtering where id in list I'm trying to add a clause to an existing GORM criteria to do some extra filtering.
I have various objects in my domain that are owned by an Organisation. For example, Product. Organisations can also own other organisations. I only want Users who belong to a particular Organisation to be able to see domain objects that belong to that Organisation or any of their Organisation's child Organisations.
There are a number of places in my application where I need to query for domain objects that are owned by Organisations. I want to create a DetachedCriteria instance that I can reuse throughout by application wherever I need to filter out objects that a User should not be allowed to see.
I've denormalised my model a bit to hopefully make things easier. When a new Organisation is inserted, it recursively adds itself to the hierarchyOrganisations collection of each of the Organisations above it.
class Organisation {
    ...
    static hasMany = [hierarchyOrganisations: Organisation]
    ...
}

One of the places I want to apply the organisation filtering DetachedCriteria is in Grails' scaffolding controller's list method, so I need to be able to paginate the final set of results.
Using the Product controller's list method as an example, I'm currently doing something like this -
def hierarchyCriteria = new DetachedCriteria(Organisation).build {
    eq('id', currentUserOrganisation.id)
}

def productInstanceList = Product.createCriteria().list {
    inList('parentOrganisation.id', hierarchyCriteria.list().each { organisation ->
        organisation.hierarchyOrganisations.collect { it.id }
    })
}

...which works, but I don't think it will scale. I'll be hitting the database to bring back the collection of hierarchyOrganisations, then iterating over them in the application to pull out the id, and then querying again to bring back the final filtered list of organisations.
If I was using SQL, I could use a join or an inner select, but I can't seem to get the syntax right translating this to the GORM criteria dsl.

A: def organisationInstanceList = Organisation.createCriteria().list {
    idEq(currentUserOrganisation.id)
    hierarchyOrganisations{
      //Eagerly fetch all children for the parent org
    }
}

def children = organisationInstanceList?.first().hierarchyOrganisations

I may be over-simplifying things, but the above should give you the parent org and the corresponding children orgs. What else do you need?
Adding to @Sergio's option:
The denormalization may be unnecessary. Data model can be used as
class Organisation {
    Organization parent
}

When a new organization is added, just map it to the corresponding parent, automatically an hierarchy is created.
In order to get, all the children(paginated) from a parent, use
def children = Organization.findAllByParent(currentUserOrganisation, [max: params.max, offset: params.offset])

A: I just ended up using some SQL to augment the criteria.
By adding a sqlRestriction block to my criteria dsl I was able to add a subselect to apply the filtering I needed
I'd still be interested in finding out if this is possible using just the grails hibernate criteria dsl.


text:
Q: C++: Uninitialized Variable Output Is 0 in Xcode I'm in a very rudimentary beginner's programming course, focusing on C++. We're currently being taught about member variables vs local variables. To that end, I've written this very simple program, to see what the output would be when a local variable is declared but uninitialized and given the same name as a member variable that has been initialized.
class myclass
{
    public:
        void getvalues();
        myclass();
    private:
        int count;
};

myclass::myclass()
{
    count = 100;
}

void myclass::getvalues()
{
    int count;
    std::cout << count << std::endl;
}

int main()
{
    myclass foo;
    foo.getvalues();

    return 0;
}

My expectation is that I would get some garbage output of some very large random number. Instead, the output is 0. Any particular reason why this is? I'm using Xcode, if this makes a difference.

A: Officially this is undefined behavior. But some environments will zero out memory. While other will leave it uninitialized. One thing you can count on is this not behaving the same in all environments (e.g., visual studio, gcc, etc.)


text:
Q: inserting an object that has const fields into a container Suppose I have:
class A {
public:
    const int x;
    A() : x(3) {}
}

And I'd like to create
std::vector<A>

g++ complains that the default assignment operator won't work since it tries to do this->x = x, which can't be done since x is const.
Is there any way around this?

A:
g++ complains that the default assignment operator won't work since it
  tries to do this->x = x, which can't be done since x is const.

g++ complains correctly. Your class does not satisfy copyable requirement of the standard containers that is why you cannot use it with them.

Is there any way around this?

Of course there is. Even more than one way.
E.g. the most obvious thing: you can remove const qualifiers from the members to make class copyable.
Or otherwise you can store pointers (or smart pointers) to the containers instead of the objects (one specific way to do that is what tpg2114 suggested).

A: Have you tried using something like boost::ptr_vector? You would be storing a pointer to the object instead of the object, but that gets around the assignment problem.
http://www.boost.org/doc/libs/1_48_0/libs/ptr_container/doc/ptr_vector.html

A: I think the moral of the story is if you want your object to be copy assignable don't render it non-copy-assignable by having const or & members or a non-public copy assignment operator.
Edit:
For reference: With C++11 you can emplace into standard containers which is both more efficient and allows you to put noncopyable objects into standard containers.


text:
Q: Laravel error in login route when the user is authenticated I have a Laravel app with an Auth system created by php artisan make:auth command.
To login, I go to localhost/app/login, submit the form and the app redirects me to localhost/app/admin. Everything is fine. But when I try to visit localhost/app/login after logging in, I get the error:
'Trying to get property of non-object' in '…\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php 158

How can I make the app redirect me to a different page if the user is already logged in? Can anybody help me? Thanks.


text:
Q: Abstract classes and interface In an Interface by default the data member are static and final.
Static it is because it can not be instantiated,but why it is final?
and the other question is even the abstract classes can not be instantiated,then why it can have a non static data member??

A: and the other question is even the abstract classes can not be instantiated,
then why it can have a non static data member??

Because in abstract classes, you can define as much functionality you want, which can be then used by its childs.

A: Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
I wouldn't advise on putting variables in an interface since the interface mainly serves as a blueprint for it's classes.
Why can an abstract class have a non-static data member?
A static variable is one that's associated with a class, not objects of that class. Generally speaking, the purpose of an abstract class is to provide a skeleton with some non-abstract behavior, but other bits still to be filled in by subclasses which can also define functionality and use the abstract class' variables.


text:
Q: NoMethodError in MicropostsController#index I cannot figure this out-
NoMethodError in MicropostsController#index
and
I have searched the web and cannot seem to make the right change.  I am doing Michael Hartl's Rails Tutorial and I am in ch 2 where we do microposts.
Here's index.html.erb
Listing Microposts

      Content
      User

    <% @microposts.each do |micropost| %>

        <%= micropost.content %>
        <%= micropost.user_id %>
        <%= link_to 'Show', micropost %>
        <%= link_to 'Edit', edit_micropost_path(micropost) %>
        <%= link_to 'Destroy', micropost, method: :delete, data: { confirm: 'Are you sure?' } %>

    <% end %>

<%= link_to 'New Micropost', new_micropost_path %>

and
Microposts Controller
Class MicropostsController < ApplicationController

  def index

  end

  def show

  end

  def new

  end

  def edit

  end

  def create

  end

  def update

  end

  def destroy

  end
end

A: You are getting this error because there is no microposts instance variable in index action, in index action you should set @microposts like this:
def index
  @microposts = Micropost.all
end


text:
Q: align 3 divs vertically with top div having background image i've looked and looked and tried many things but just can't seem to get this to work properly, and it's driving me bonkers.
i'm trying to have multiple divs on a page, 100% width, one after the other. the top div has a background image, and its height will change depending on the screen size.
everything works fine using relative positioning until I add the background image, at which point it needs to be absolute positioned and the bottom two divs sit on top of the first div with the image.
can someone please explain / show me how I can get this to work


text:
Q: App crashing. KeyException? I get crash reports from my app. I really don't understand what the problem is. It never
crashes with me... What can be the problem? From the app hub error message:
0        coredll.dll       xxx_RaiseException                                            19
1        mscoree3_7.dll                                                                  436488
2        mscoree3_7.dll                                                                  386545
3        mscoree3_7.dll                                                                  540936
4                          TransitionStub                                                0
5                          System.ThrowHelper.ThrowKeyNotFoundException                  52
6                          System.Collections.Generic.Dictionary 2.get_Item              136
7                          System.IO.IsolatedStorage.IsolatedStorageSettings.get_Item    80
8                          ScheduledTaskAgent1.ScheduledAgent.OnInvoke                   660
9                          Microsoft.Phone.Scheduler.ScheduledTaskAgent.Invoke           856
10                         .AgentRequest.Invoke                                          764
11                         Microsoft.Phone.BackgroundAgentDispatcher.InvocationThread    196
12                         System.Threading.ThreadHelper.ThreadStartHelper               132
13                         System.Threading.ThreadHelper.ThreadStart_Context             80
14                         System.Threading.ExecutionContext.Run                         324
15                         System.Threading.ThreadHelper.ThreadStartHelper               168
16       mscoree3_7.dll                                                                  429164
17       mscoree3_7.dll                                                                  310125
18       mscoree3_7.dll                                                                  310319
19       mscoree3_7.dll                                                                  305995"

A: Looks like the BackgroundAgent is trying to load an item from the IsolatedStorageSettings.ApplicationSettings that doesn't exist. Check in your ScheduledTaskAgent1.ScheduledAgent.OnInvoke method.
1/ First check the existence of the key using the "IsolatedStorageSettings.ApplicationSettings.Contains" method before retrieving it
2/ If the key does not exist, act accordingly
For instance, if you're doing:
somevalue = IsolatedStorageSettings.ApplicationSettings["setting"];

Then "setting" is the key the error message is referring too. Replace your code by:
if (IsolatedStorageSettings.ApplicationSettings.Contains("setting"))
{
    somevalue = IsolatedStorageSettings.ApplicationSettings["setting"];
}else
{
    // set somevalue to its default value
}


text:
Q: Performing operator expression on a function What I want. I write an operator expression, and Mathematica performs it on a function.
Examples:
E^(b D): f[x] -> f[x+b]
a^(x_ D): f[x] -> f[a x]
E^(Pi I /4 (D^2 - x_^2 +1)) : Fourier transform (unitary, angular velocity)
E^(D^2) : Weierstrass transform
etc.
See here more: https://math.stackexchange.com/a/1495596/2513


text:
Q: How to evaluate a variable length in shell script? I want to write a shell script, in which it will call different command according to the variable length. But I didn't figure it out yet.
My unwork script is here:
for i in n5 n25
if ${#i} == 2;
then
do
    python two.py n5
elif ${#i} == 3;
do
    python three.py n25
fi

How to evaluate the variable length in shell script?

A: You probably want:
for i in n5 n25
do
   if [ ${#i} -eq 2 ]; then
       python two.py n5
   elif [ ${#i} -eq 3 ]; then
       python three.py n25
   fi
done

Note that:

*

*for goes with do ... done.

*if goes with then ... [elif; then] ... [else; then] ... fi.

*the integer comparisons need -eq (equal) instead of = (for strings) and are written within brackets (if [ "$var" -eq 2 ], etc).


text:
Q: How do I find the index of a particular element within a List in DAML? Say I have a List that looks like this:
let identifiers = ["ABC123", "DEF456", "GHI789"]

I want to know the index if the element "DEF456". What's the recommended way to accomplish this?

A: The findIndex function in the Base.List module in the standard library, does what you want.
daml 1.0 module FindIndex where

import Base.List
import Base.Maybe

test foo : Scenario {} = scenario
  let
    identifiers = ["ABC123", "DEF456", "GHI789"]
    index: Maybe Integer = findIndex ((==) "DEF456") identifiers

  assert $ index == Just 1

Under the hood most list manipulation in DAML, including findIndex is implemented using foldr and foldl.
-- Returns the index of the first element in the list satisfying the predicate, or M.Nothing if there is no such element.
def findIndex (f: a -> Bool) (xs: List a) : Maybe Integer =
  headMay (findIndices f xs)

-- Returns the indices of all elements satisfying the predicate, in ascending order.
def findIndices (f: a -> Bool) (xs: List a) =
  let work acc x =
        let i = fst acc
        let is = snd acc
        tuple (i + 1) (if f x then cons i is else is)
  reverse (snd (foldl work (tuple 0 nil) xs))

A: In daml 1.2 you can use the elemIndex : Eq a => a -> [a] -> Optional Int function in the DA.List standard library module like so:
daml 1.2 module MyModule where

import DA.List

indexOfElement = scenario do
  let identifiers = ["ABC123", "DEF456", "GHI789"]
      index : Optional Int = elemIndex "DEF456" identifiers
  assert $ index == Some 1
  return index


text:
Q: Enter in parameter value SQL in MS Access (latest version) I am running into this issue where I keep getting this dialog box appearing asking me to enter in parameter values when it shouldn't be. Here is the code:
SELECT ProductionCost
FROM tblFilm
WHERE ProductionCost >"220";

It keeps popping up with the dialog box. Can someone please help me with this? Thank you!


text:
Q: What's the difference between BigQuery and Bigtable? Is there any reason why someone would use Bigtable instead of BigQuery? Both seem to support Read and Write operations with the latter offering also advanced 'Query' operations.
I need to develop an affiliate network (thus I need to track clicks and 'sales') so I'm quite confused by the difference because BigQuery seems to be just Bigtable with a better API.

A: The difference is basically this:
BigQuery is a query Engine for datasets that don't change much, or change by appending. It's a great choice when your queries require a "table scan" or the need to look across the entire database. Think sums, averages, counts, groupings. BigQuery is what you use when you have collected a large amount of data, and need to ask questions about it.
BigTable is a database. It is designed to be the foundation for a large, scaleable application. Use BigTable when you are making any kind of app that needs to read and write data, and scale is a potential issue.

A:
This may help a bit in deciding between different datastore solutions that Google cloud offers (Disclaimer! Copied from Google Cloud page)
If your requirement is a live database, BigTable is what you need (Not really an OLTP system though). If it is more of an analytics kind of purpose, then BigQuery is what you need!
Think of OLTP vs OLAP; Or if you are familiar with Cassandra vs Hadoop, BigTable roughly equates to Cassandra, BigQuery roughly equates to Hadoop (Agreed, it's not a fair comparison, but you get the idea)
https://cloud.google.com/images/storage-options/flowchart.svg
Note
Please keep in mind that Bigtable is not a relational database and it does not support SQL queries or JOINs, nor does it support multi-row transactions. Also, it is not a good solution for small amounts of data. If you want an RDBMS OLTP, you might need to look at cloudSQL (mysql/ postgres) or spanner.
Cost Perspective
https://stackoverflow.com/a/34845073/6785908. Quoting the relevant parts here.

The overall cost boils down to how often you will 'query' the data. If
it's a backup and you don't replay events too often, it'll be dirt
cheap. However, if you need to replay it daily once, you will start
triggering the 5$/TB scanned very easily. We were surprised too how
cheap inserts and storage were, but this is ofc because Google expects
you to run expensive queries at some point in time on them. You'll
have to design around a few things though. E.g. AFAIK streaming
inserts have no guarantees of being written to the table and you have
to poll frequently on tail of list to see if it was really written.
Tailing can be done efficiently with time range table decorator,
though (not paying for scanning whole dataset).
If you don't care about order, you can even list a table for free. No
need to run a 'query' then.

Edit 1
Cloud spanner is relatively young, but is powerful and promising. At least, google marketing claims that it's features are best of both worlds (Traditional RDBMS and noSQL)

A: BigQuery and Cloud Bigtable are not the same. Bigtable is a Hadoop based NoSQL database whereas BigQuery is a SQL based datawarehouse. They have specific usage scenarios.
In very short and simple terms;

*

*If you don't require support for ACID transactions or if your data is not highly structured, consider Cloud Bigtable.

*If you need interactive querying in an online analytical processing (OLAP) system, consider BigQuery.


text:
Q: node.js - Can't figure out how to sabe sessions with session-express I'm new to node.js and sessions, I'm trying to store some values in the node.js session, but everytime I reload the page and check the console.log the session haven't been saved. My code:
var session;
var org;

function checkSession(argument){
  var sess = argument;
  if(sess.org){
    return null;
  }
  else{
    return sess.org;
  }
}
/* GET home page. */
router.get('/', function(req, res, next) {
  session = req.session;
  var sessionChecked = checkSession(session);
  if(sessionChecked){
    org = sessionChecked;
  }
  else{
    org = req.query.org || 'Google';
    session.org = org;
    session.save();
  }

So basically what I want is, when the user loads the page for the first time, he can type a organization, and when he does that, this organization is saved on the session, so when he reloads the page, the organization is already selected.
I know I must be doing something really wrong and/or bad codding, but I just can't figure this out.
Thank you!

A: It looks like calling session.save() isn't doing what you expect. Express won't write to the session unless the route is fully processed. You likely need to call res.end() at the end of your get function.
Take a look at https://github.com/expressjs/session#reqsession and try to understand each line of code in that example.
Good luck!

A: It turns out the problem was that my session was expiring in 20 seconds. Silly me.


text:
Q: My intent is not matching with expected response I'm using botkit with luis recognizer and below is the sample code:
bot.dialog('OnboardingDialog', (session) => {
   ....
....

}).triggerAction({ matches: 'OnboardingBook' })

I have defined onboarding intent in responses as below:
OnboardingBook:{buttonTitle:'',url:'',response:'new hire can be onboarded some extra stuff',title:'Onboarding book'}
CookBook: {buttonTitle:'',url:'',response:'this is about cookbook',title:'cook'}
Ideally, if I type onboarding in my chat bot, it should return response defined in Onboarding intent. But right now its giving me other intent answer. If i type, onboarding book its giving me cook book intent.
Please help me out why few intents are matching with other than expected. Is there any logic behind this? How to resolve this problem. Please help me out.

A: When you test your LUIS app in the LUIS portal do you get the correct intent? If so then perhaps you need to save and train, the publish your LUIS app again. If you do not get the correct result in the LUIS portal then you can click inspect and edit the top scoring intent (save + train then publish to push the change live).


text:
Q: Java policy settings not working for FilePermission Our Java policy file used to just be:
grant {
  permission java.security.AllPermission;
};

I am trying to make our application more secure than just granting everything to everyone.  I have it working well except I am having troubles giving permission to files.
The error I currently get is:
java.security.AccessControlException: access denied (java.io.FilePermission \\server.log write)

I have tried so many combinations of things, such as:
permission java.io.FilePermission "\\\\server.log", "write";
permission java.io.FilePermission "C:\\Temp\\logs\\server.log", "write";
permission java.io.FilePermission "\\server.log", "write";
permission java.io.FilePermission "${TEMP}${/}-", "write";
permission java.io.FilePermission "*", "read,write";

The only thing I can get it to work is using:
grant {
  permission java.security.AllPermission;
};

I get the error "java.io.FileNotFoundException: \server.log (The filename, directory name, or volume label syntax is incorrect)" when using (even when the files do exist):
permission java.io.FilePermission "<<ALL FILES>>", "write";

Just wondering if anyone had any other ideas to try.  I don't really want to have to resort to granting all just to get the file permissions right, obviously I am missing something.
EDIT:
I just realized that maybe this is a clue in the log file:
log4j:ERROR setFile(null,false) call failed.

Maybe I need some permissions for this specifically? Digging around Google now....

A: In Oracle documentation have some examples:
https://docs.oracle.com/javase/8/docs/technotes/guides/security/spec/security-spec.doc3.html
permission java.io.FilePermission "myfile", "read,write";
permission java.io.FilePermission "/home/gong/", "read";
permission java.io.FilePermission "/tmp/mytmp", "read,delete";
permission java.io.FilePermission "/bin/*", "execute";
permission java.io.FilePermission "*", "read";
permission java.io.FilePermission "/-", "read,execute";
permission java.io.FilePermission "-", "read,execute";
permission java.io.FilePermission "<<ALL FILES>>", "read";

permission java.io.FilePermission "c:\\temp\\foo", "read,write,delete")
\\this one works for me

A: I think the problem is because you are trying to write to a file without permission to read it.
permission java.io.FilePermission "C:\\folder\\*", "read, write";


text:
Q: Comunicação com baudrate 110 Tenho que receber dados de um equipamento que tem uma interface TTL que manda os dados a 110 bits por segundos.
Em todos os testes que realizei quando tento chegar a essa velocidade tenho problemas, por exemplo:

*

*Meu programa não recebe os 9 bytes enviados, somente 8 e o que recebe
não condiz com que deveria.

*Receber Usando o minicom (Linux Ubuntu) ele não aceita configurar o baudrate com 110 somente 300 o que não favorece na leitura.

*Com Arduino (ide v1.6 e v1.8) quando mando alguma coisa pela serial a 300 bits por segundo só vai caracteres sem sentido, qualquer outra velocidade funciona (to mandando um simples Serial.println("oi") )
Alguma ideia do que pode estar acontecendo?

A: Uma opção é utilizar a linguagem Python usando o módulo pyserial. É um módulo bem versátil, podendo receber diversas configurações da comunicação serial e padrões.
Um exemplo de código em Python usando serial abaixo:
import serial

class Comunicacao():

    def SerialInit(self, NomePorta, Velocidade, TimeRX, TimeTX):

        try:
            self.PortaCom = serial.Serial(NomePorta, Velocidade, 8, serial.PARITY_NONE, serial.STOPBITS_ONE, TimeRX,
                                          False, False, False, TimeTX)
            self.PortaCom.reset_input_buffer()
            self.PortaCom.reset_output_buffer()

        except Exception:
            print("Erro na porta " + NomePorta + "!")

    def WriteSerial(self, DadosTx):

        try:
            self.PortaCom.flushOutput()
            TamPac = DadosTx[3]
            for i in range(TamPac):
                DadoTxByte = bytes((DadosTx[i],))

                self.PortaCom.write(DadoTxByte)
                print(DadoTxByte)

        except Exception:
            print("Erro Escrita")

    def Leitura_Serial(self, DadosRx):

        LeituraSerial = [0] * 200

        for i in range(200):

            if (self.PortaCom.in_waiting > 0):
                LeituraSerial[i] = self.PortaCom.read()
                LeituraSerial[i] = self.ByteToInt(LeituraSerial[i])
                print(LeituraSerial[i])

            else:
                break

DadosTx = [1,2,3,4,5,6,7,8]
DadosRx = [0] * 100
PortaCom = Comunicacao()
PortaCom.SerialInit("/dev/ttyUSB0", 115200, 1, 1)
PortaCom.WriteSerial(DadosRx)


text:
Q: Android App Map Fragment not showing in release version I've created a small android app using a Map Fragment and been testing it using jetbrains-studio. I've obtained an API key and it works fine, whether the phone is plugged into the laptop via the USB cable or whether I carry it around standalone (I need to do this as it has a tracking element involved).
I have "Maps SDK for Android" API enabled via the APIs and services dashboard.
When I uploaded the App I went to "App signing" and downloaded the Google certificate, called "deployment_cert.der". When it came time to
compile my app,
keytool -importcert -file deployment_cert.der -keystore keystore.jks
(keystore was the file created when I went to compile the release version of the app as a signed apk; when I uploaded the app, Google didn't grumble and accepted it)
I got my wife to test out the app by downloading from the playstore on her phone and tablet but instead of the map, I get a grey box, with the Google logo in the corner, +/- zoom buttons and the "home centre" circle in the top right hand corner. Everything else on the app is working.
I don't have a clue what could be wrong? Could someone please provide some hints? I am stumped as to what to look for.
I've checked device compatibility and all the devices I've used are listed in the device directory as being OK.
My Manifest file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mydomain.ge">

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/gmarkerblank"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".GE"
        android:label="@string/title_activity_ge">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

My build.gradle file is:
apply plugin: 'com.android.application'

android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.mydomain.ge"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//implementation 'com.google.android.gms:play-services:12.0.1'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support:design:27.1.1'
implementation 'com.github.pengrad:mapscaleview:1.4.1'

}

My activity file is as follows:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1"
android:id="@+id/tlll"
>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llhelpgraphic"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight=".08"
    android:background="#000000"
    android:orientation="horizontal">

    <ImageButton
        android:id="@+id/helpButton"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_margin="3dp"
        android:adjustViewBounds="true"
        android:src="@drawable/help5"
        />

    <ImageView
        android:id="@+id/titleview"
        android:layout_height="match_parent"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        android:src="@drawable/title"
        />

</LinearLayout>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/frlayout"
    android:layout_weight=".82"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    >

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".GE" />

</FrameLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight=".10"
    android:background="#004D79"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/addressText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="7dp"
        android:layout_weight="1"
        android:background="#FFFFFF"
        android:text="Enter UK address or postcode">
    </EditText>

    <Button
        android:id="@+id/findButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="Find">
    </Button>
</LinearLayout>

Basically, what this produces is, a top row containing an image button, then next to it, filling up the rest of the row is the title of the app
Then below is the map, filling up the most of the space
The very bottom is a row containing a text edit box, and a button on the right hand side.
I can't see anything obviously amiss in the source code

A: Your app generates different SHA-1 fingerprints depending on your build variant.
Also when you use Google's App Signing, Google generates a SHA-1 fingerprint for you when you upload your apk, so you need to add that fingerprint in your Google Cloud Platform Console like you did with your debug fingerprint.
You can view the generated fingerprint by going to Google Play Console -> Release Management -> App signing


text:
Q: installing node-gd in ubuntu when I install node-gd lib, I'm getting the following warning:
root@iZ25mlpjokyZ:~# npm install node-gd
/
> node-gd@1.1.0 install /root/node_modules/node-gd
> node-gyp rebuild

gyp WARN EACCES user "root" does not have permission to access the dev dir "/root/.node-gyp/4.3.1"
gyp WARN EACCES attempting to reinstall using temporary dev dir "/root/node_modules/node-gd/.node-gyp"
gyp WARN EACCES user "root" does not have permission to access the dev dir "/root/node_modules/node-gd/.node-gyp/4.3.1"
gyp WARN EACCES attempting to reinstall using temporary dev dir "/root/node_modules/node-gd/.node-gyp"

A: Thanks.
I solved it with the following commands:
apt-get install g++ gcc
apt-get update
apt-get upgrade

A: the package on website tells us to install libgd2-dev using ubuntu package manager as
sudo apt-get install libgd2-dev

but this package is not available in the source list the thing that worked for me is as follows
sudo apt-get isntall libgd-dev
npm i node-gd --save


text:
Q: MySQL, Select value based on conditional count of grouped items I have a table buildings which looks like:
+----+------------------+-------+
| id | accommodation_id | type  |
+----+------------------+-------+
| 1  | 2                | Villa |
+----+------------------+-------+
| 2  | 2                | Suite |
+----+------------------+-------+
| 3  | 5                | Villa |
+----+------------------+-------+

I what for each accommodation to determine which type it is by this logic:
If the accommodation has more than 1 building use the hard code value of Accommodation otherwise buildings.type column.
The expected output should looks like
+---------------+
| type          |
+---------------+
| Accommodation | <- the result for accommodation_id=2
+---------------+
| Villa         | <- the result for accommodation_id=5
+---------------+

I've tried this query
SELECT IF(Count(id) = 1, type, 'accommodation') AS type
FROM   `buildings`
WHERE accommodation_id = 2
GROUP  BY accommodation_id

It fails because of usage of type which is not in the group (fault of only_full_group_by).
If I add type to the grouping it returns not required result
+---------------+
| type          |
+---------------+
| Accommodation | <- the result for accommodation_id=2 & id=1
+---------------+
| Accommodation | <- the result for accommodation_id=2 & id=2
+---------------+
| Villa         | <- the result for accommodation_id=5 & id=3
+---------------+

I'm using MySQL8 with sql_mode=only_full_group_by

A: You just need to count the distinct values of type for each accommodation_id, and if greater than 1, output Accommodation, otherwise the type:
SELECT accommodation_id,
       CASE WHEN COUNT(DISTINCT type) > 1 THEN 'Accommodation'
            ELSE MIN(type)
       END AS type
FROM buildings
GROUP BY accommodation_id

Output:
accommodation_id    type
2                   Accommodation
5                   Villa

Demo on dbfiddle

A: Just a slight improvement on Nick's answer +1, to make the query sargable:
SELECT
    id,
    CASE WHEN MIN(type) <> MAX(type) THEN 'Accommodation' ELSE MIN(type) END AS type
FROM buildings
GROUP BY id;

The above query should be able to use the following index:
(id, type)

The reason for this is that it only uses MIN and MAX, so for each id group the min and max type values can be looked up using the index, quickly.


text:
Q: Different Imphash for same PE file I am analyzing a windows executable (C:\Windows\System32\xcopy.exe). The Imphash value calculated with Python is different from the one shown with PE studio. How can Imphash for a same file be different when computed using two different tools?
What's missing here ?
Imphash Python: 1effe65a4f251e4ae9fa8551f9fcdabb
Imphash PeStudio: 370E0F2A87317776FEB42A7B32DD037B

A: On 64-bit systems, the path C:\Windows\System32 is virtualized – 64-bit processes can access it directly, but 32-bit processes are magically redirected to C:\Windows\SysWow64 instead.
Your "pestudio" tool is 32-bit, so it is actually seeing the 32-bit version of xcopy.exe rather than the 64-bit one.
Python 3.9.4 [MSC v.1928 64 bit (AMD64)]

>>> pefile.PE(r"C:\Windows\System32\xcopy.exe").get_imphash()
'1effe65a4f251e4ae9fa8551f9fcdabb'

>>> pefile.PE(r"C:\Windows\SysWow64\xcopy.exe").get_imphash()
'370e0f2a87317776feb42a7b32dd037b'


text:
Q: Working with PageBreaks in Excel Javascript API I'm trying to figure out PageBreaks in Excel w/ the Javascript API.
My goal is to put blank lines on the end of the last page, filling up the unknown amount of blank space.
I've been reading the docs on PageBreaks and noticed a funciton getCellAfterBreak() which seems like a good starting point. I'd need to get the offset range of the cell above that to the bottom of my UsedRange.
I can't really seem to get any useful information from the console or docs, here is what I've been trying, can anybody point me how to use these funcitons?
https://learn.microsoft.com/en-us/javascript/api/excel/excel.pagebreak?view=excel-js-preview
https://learn.microsoft.com/en-us/javascript/api/office-scripts/excelscript/excelscript.pagebreak?view=office-scripts
Code:
var ws = context.workbook.worksheets.getActiveWorksheet();
var PageBKs = ws.horizontalPageBreaks
PageBKs.load('items')
await context.sync()
console.log('PageBKs')
console.log(PageBKs)
var Count = PageBKs.getCount()
console.log('Count')
console.log(Count)


text:
Q: Draw large 16:9 transparent PNG in AndEngine? I'd like to draw a large (1920x1080) partly-transparent PNG over the whole screen in AndEngine. Textures have to be power-of-2 sized, and probably a lot of phones won't have support for textures that large anyway. Is there a straightforward way to add an image of that size to the scene in AndEngine, or am I going to have to manually slice it up into 256x256 chunks and render a bunch of them as sprites?

A: I just tried loading a 2048x2048 image as a background image using AndEngine GLES1 and an old Android 1.6 phone. It works quite nice. There is some performance penalty though, but that would be the same if you used many smaller textures.


text:
Q: How to get XYZ data of room center? I am trying to place an element into the center of several rooms. So far I have achieved something similar by using the Location Point which has placed the element close to the center but not exact.
I attempted to fix this by using two methods that I believed would help accomplish this task, GetElementCenter and GetRoomCenter but when I run the plugin, nothing happens.
class Class2
{
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        //Get access to Revit command data, user interface and document
        UIApplication uiapp = commandData.Application;
        UIDocument uidoc = uiapp.ActiveUIDocument;
        Document doc = uidoc.Document;

        //Collect all rooms
        FilteredElementCollector roomCollector = new FilteredElementCollector(doc).OfClass(typeof(SpatialElement));

        // Collect element
        FilteredElementCollector element = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_Cameras);

        //Get symbol
        FamilySymbol elementSym = element.FirstElement() as FamilySymbol;

        using (Transaction tx = new Transaction(doc))
        {
            try
            {
                tx.Start("Start");

                //For loop for every room in the roomCollector
                foreach (SpatialElement oneRoom in roomCollector)
                {
                    //Get area of each room
                    Room room = oneRoom as Room;
                    double area = room.Area;

                    //Location point version
                    Location loc = room.Location;
                    LocationPoint location = loc as LocationPoint;
                    XYZ point = (null == location) ? XYZ.Zero : location.Point;

                    //New version
                    XYZ source = GetRoomCenter(room);

                    double smallRoom = 301;

                    if (area <= smallRoom)
                    {
                        doc.Create.NewFamilyInstance(source, elementSym, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
                    }
                }
                tx.Commit();
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
                tx.RollBack();
            }
        }
        TaskDialog.Show("Message", "Task completed successfully");
        return Result.Succeeded;
    }

    public XYZ GetElementCenter(Room room)
    {
        BoundingBoxXYZ bounding = room.get_BoundingBox(null);
        XYZ center = (bounding.Max + bounding.Min) * 0.5;
        return center;
    }
    public XYZ GetRoomCenter(Room room)
    {
        XYZ boundCenter = GetElementCenter(room);
        LocationPoint locPt = (LocationPoint)room.Location;
        XYZ roomCenter = new XYZ(boundCenter.X, boundCenter.Y, locPt.Point.Z);
        return roomCenter;
    }
}

}
Any help on getting the XYZ data of the center of a room would be greatly appreciated.

A: Assuming that you have straight walls bounding the room, I would suggest that you take a look at mathematical and geometrical algorithms for determining the center point of a polygon. Something like this new algorithm for finding a visual center of a polygon is probably best suited to your needs, even though you neither state this fact nor probably are yet aware of it :-)


text:
Q: Make-Before-Break Relay with Very High Continuous DC Current I need to use a relay in order to do field sweeps with my electromagnet, which is hooked up to a couple very beefy monopolor power supply. (My magnet's impedance is  ~2 Ohm, and I am putting ~40 Amps through it at maximum power).
Initially, I figured the Potter & Brumfield T92 Series Two-pole 30A PCB Relay would work for me.
A cursory glance at the contact data revealed:

*

*Rated Current: 30A

*Limited Continuous Current: 40A

*Limited Making Current: 40A

*Limited Breaking Current: 40A

I assumed I would be pushing the limits, but this relay is $13 and I had one laying around.  However, then I looked at the contact ratings, and I saw, under the 'Load' header:

*

*40A, 277VAC, resistive

*30A, 120/277VAC, resistive

*10A, 600VAC, general purpose

*20A, 28VDC, resistive
Where I have italicised the rating that concerns me. Is this to say that I should not use this relay? Does anyone have any idea what kind of relay I should use? When I look at "power relays," they all seem to have just two contacts, rather than the eight that I would expect... Also, how do I tell if the relays are make-before-break or break-before-make? I know that the one I have now will work, only because I know someone else who is using it for the same thing...
Thank you for your help!

A: The DC voltage rating of relays and switches is roughly 10% of the AC rating.  When you start getting to higher currents the DC rating is even worse.
This is because of arcing when the contacts are broken.  With AC the arc is automatically extinguished when the waveform crosses the zero point. Of course, DC doesn't do this, so the arc doesn't extinguish by itself. So you can only support much lower voltages for the same contact distance.  And of course, because of this the arcs can last longer, which means the maximum current must be reduced as well.
In general relays are break-before-make since they work by a single leaf moving between two contacts.  To get a make-before-break you effectively have to have two completely separate contact systems which operate at different times.  It is more normal to use two separate relays and control them at different times if you really need make-before-break.
"Power" relays which handle very high currents are often just on-off, since they have very large contacts which travel over a greater distance.
Another consideration with the relays is the type of load.  You have an electromagnet. That is an inductive load, not just a resistive load.  The rating is for purely resistive, and doesn't take into account any back-EMF (back electromotive force) from an inductive load.  The EMF induced by the collapsing magnetic field can be many times higher than the voltage you are operating at, and this EMF can cause more arcs in the relay contacts further degrading the relay.  So for an inductive load you need a higher rated relay than for a resistive load.

A: Majenko tells you why most relays have such limited DC current ratings.  However, there are other options.
You mention 2 Ohms, 40 Amps.  I assume that means that you are running from about 80 Vdc.
1)  Automotive starter solenoids are rated for very high DC currents with very inductive loads.  You will want to look at 24V solenoids used for starting big-rig diesel engines, not those used for 12V passenger automotive vehicles.
2) I think your better option is to look at MOSFETs.  This also allows you to implement your make-before-break timing in your control circuit.


text:
Q: Flexbox content spills over in Firefox I'm not sure what I'm doing wrong here, but for some reason, Firefox doesn't adjust the height of my Flexbox blurbs according to its content like how Safari and Chrome do.
Blurb is basically the different boxes in my layout. Before you say anything, I've also tried switching it back to a div layer, but it still doesn't work.
The basic code of Blurb is as follows:
blurb {
display: block;
height: auto;
margin: 5px;
padding: 10px;
background: #fffeee;
-webkit-flex: 3 0 0;
    flex: 3 0 0;
}

Here is my code:
http://jsfiddle.net/HenQ8/1/
The general layout of the page is like this:

There's nothing wrong with the code when it comes to Safari and Chrome, which renders it like this:

but when it comes to Firefox the height bases itself on the column on the right like this:

Any idea what I'm doing wrong, or what I should add to the blurb so that it contains its content to itself instead of spilling out? Thanks in advance!

A: It looks like the main problem comes down to a couple lines from your 'blurb' block of CSS. Specifically, your flex/-webkit-flex lines:
flex: 3 0 0;
-webkit-flex: 3 0 0;

The last parameter of flex is "flex-basis," which is apparently being handled a little differently between Firefox and Chrome/Safari. If you inspect one of the 'blurb' elements and look at the computed styles in Chrome and Firefox, you'll see that the browsers are interpreting the value as '0px.' The problem is that while Chrome is expecting '0px,' Firefox is not. Firefox is expecting '0%' (which is not exactly the same thing as 0px); annoyingly, if you were to use "flex: 3 0 0%," while it would fix it for Firefox, it would also break Chrome and Safari's display. It looks like while Chrome and Safari are trying to do the right thing with 0px, Firefox is sticking closer to the standard. When it sees '0px,' it attempts to make the blurb boxes as small as possible, causing the text to overlap.
If you search through the flexbox spec (http://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/) for "flex-basis" you can find some further details on it as well as some discussion of 0px vs 0%.
Instead of providing flex-basis a number, however, you can also use "auto" which will size the element "according to its size property (which can itself be the keyword auto, which sizes the element based on its contents)" (http://css-tricks.com/almanac/properties/f/flex-basis/). In my testing this has resolved the display in Firefox, Chrome and Safari.
Example CSS block with changes:
blurb {
    display: block;
    outline: 2px solid red;
    margin: 5px;
    padding: 10px;
    background: #fffeee;
    -webkit-flex: 3 0 auto;
    flex: 3 0 auto;
}

Fiddle example:
http://jsfiddle.net/blake770/85McA/2/
Links if you want to do more reading:

*

*http://css-tricks.com/snippets/css/a-guide-to-flexbox/

*https://developer.mozilla.org/en-US/docs/Web/CSS/flex

*http://css-tricks.com/almanac/properties/f/flex/

*http://css-tricks.com/almanac/properties/f/flex-basis/


text:
Q: AutoCompleteExtender is not working in user cotrole page in share point 2010 web application We are developing share point web application, in which threre are many user control(ascx) and aspx pages are there. My AutoCompleteExtender working fine in aspx page but when i put the code inot ascx(User control)page it doesnot working. Please help me...
My code in User controle for autocomplete search is:
 <asp:TextBox ID="txtCity" runat="server" onkeyup="SetContextKey()" Style="width: 50px;"></asp:TextBox>
                <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtCity"
                    MinimumPrefixLength="2" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000"
                    ServiceMethod="GetCity" ServicePath="~/Search.aspx" OnClientItemSelected="setCompanyMasterID"
                    UseContextKey="true" CompletionListCssClass="completionList" CompletionListItemCssClass="listItem"
                    CompletionListHighlightedItemCssClass="itemHighlighted" OnClientPopulated="onListPopulated">
</asp:AutoCompleteExtender>

Java Script and Css code is :

    function SetContextKey() {
        $find('<%=AutoCompleteExtender1.ClientID%>').set_contextKey($get("<%=txtTokenID.ClientID %>").value);
    }
    function setCompanyMasterID(source, eventargs) {

        var strIFSC = eventargs.get_value();
        alert(strIFSC);
        var Name = document.getElementById("<%=txtCity.ClientID %>").value;

        alert(Name);
    }
    function onListPopulated() {

        var completionList = $find('<%=AutoCompleteExtender1.ClientID%>').get_completionList();
        completionList.style.width = '200px';

        for (i = 0; i < completionList.childNodes.length; i++) {

            completionList.childNodes[i].title = completionList.childNodes[i]._value;
        }

    }
</script>
<style type="text/css">
    .autocomplete_firstrow
    {
        background-color: Red;
        height: 20px;
    }
    .completionList
    {
        border: solid 1px Gray;
        margin: 0px;
        padding: 3px;
        height: 220px;
        overflow: auto;
        background-color: #888888;
    }
    .listItem
    {
        color: #191919;
    }
    .itemHighlighted
    {
        background-color: #ADD6FF;
    }
</style>

And my GetCity method is in Search.aspx page becasue i did it after searching in nets...
[System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static List<string> GetCity(string prefixText, int count, string contextKey)
        {
            GCIntegrationClient objGCIntegrationClient = new GCIntegrationClient();
            WcfGCIntegrationService.ServiceResult objServiceResult = new WcfGCIntegrationService.ServiceResult();
            objServiceResult = objGCIntegrationClient.GetIFSCCodeLOV_GetObjectData(contextKey, "", prefixText);

            System.Threading.Thread.Sleep(20000);

            List<string> CityNames = new List<string>();
            for (int i = 0; i < objServiceResult.UserData.IFSCCodeGrid.Length; i++)
            {
                CityNames.Add(AjaxControlToolkit.AutoCompleteExtender.
                  CreateAutoCompleteItem(objServiceResult.UserData.IFSCCodeGrid[i].BankName, objServiceResult.UserData.IFSCCodeGrid[i].BankName));
            }
            return CityNames;
        }

Problem is that when i type the text then GetCity method didn't get fired....
but its get fired and working fine when it is on aspx page...
it is not working in ascx page....i have search many things but i didn't get appropriate answer...please help me.

A: // do something like this at the end of your code
public class GetCity
{

    public GetCity()
    {
    }
    public GetCity(string Name, string Value)
    {
        this.Name = Name;
        this.Value = Value;
    }
    public string Name { get; set; }
    public string Value { get; set; }

}


text:
Q: @XmlSeeAlso doesn't work for the same root node I'm trying to implement inheritance with @XmlSeeAlso annotation. Everything works as expected when using different root node names for subclasses. But with the same root names Unmarshaller always choses the last class from the XmlSeeAlso list despite of the content. It's impossible to change root names. Is where any way to make Unmarshaller to chose class correctly by content?
import java.io.ByteArrayInputStream;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.jaxb.Jaxb2Marshaller;

public class Test {
  public static void main(String[] args) {
    Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
    unmarshaller.setClassesToBeBound(Parent.class);
    System.out.println(unmarshaller.unmarshal(new StreamSource(
        new ByteArrayInputStream("<value>AAABBB</value>"
            .getBytes()))));
    System.out.println(unmarshaller.unmarshal(new StreamSource(
        new ByteArrayInputStream("<value><c>CCC</c><d>DDD</d></value>"
            .getBytes()))));
  }

  @XmlSeeAlso({ ChildAB.class, ChildCD.class })
  public static abstract class Parent {
  }

  @XmlRootElement(name = "value")
  public static class ChildAB {
    @XmlElement(name = "a")
    private String a;
    @XmlElement(name = "b")
    private String b;

    @Override
    public String toString() {
      return "ChildAB[" + a + "; " + b + "]";
    }
  }

  @XmlRootElement(name = "value")
  public static class ChildCD {
    @XmlElement(name = "c")
    private String c;
    @XmlElement(name = "d")
    private String d;

    @Override
    public String toString() {
      return "ChildCD[" + c + "; " + d + "]";
    }
  }
}

Output:
ChildCD[null; null]
ChildCD[CCC; DDD]

A: Why your class ChildAB and ChildCD are static? Also ChildAB and ChildCD should  implement/extend your Parent class.


text:
Q: KiCad PCB Layout Editor - Selecting entire component/footprint instead of a particular element In KiCad PCB Layout Editor, I'm trying to arrange and place the various footprints. But when I click on the component, instead of selecting the entire component/footprint, it selects the closest element of the footprint, like a label, pad, throughhole etc. Is there a setting that allows me to default to select the entire component? This has potential to ruin my design without me realising it if one of the pads is moved accidentally.
I can't find anything in the preferences or settings, so any help is appreciated!
EDIT: Here is a screenshot of a resistor. When I click on the pad, I want the whole component to be selected and not just the pad. You can see that right now, it only selects the pad.

EDIT2: As @dylanweber mentioned, I was mistaken about the pads. But it's still a problem when I hit the M key over a piece of text then it doesn't select the whole footprint, but just the text.

A: If you are using KiCad v5.1.x, you can hold down the Alt key while clicking to get the disambiguation menu for everything under your cursor.
Here is an example of performing this action in pcbnew.  Note that when clicking without the Alt key held down, we get just the pad as it is considered the "most likely" target if you are directly over it.  But with Alt key depressed while clicking, we get all items directly under the mouse cursor.

A: I personally use the fab or courtyard outlines as the place to select the full footprint. Works quite reliably.

A: An entire footprint moves together as one unit, so no matter what pad is selected, moving the pad should also move all other pads (and drill holes) for the component.


text:
Q: Matlab set opacity to M x N x P grayscale matrix I have a matrix define as data = rand(M,N,P) where M = 262, N = 359, P = 562.  Each element in the matrix gets assigned an intensity value for 0 - 255 depending on input scan data.
E.g. data(200,220,232) = 32 or data(200,220,233) = 156
How can i assign transparency to each element in the matrix based on the intensity value. For example: all intensities below 128 have 0.8 transparency, and every value between 128-255 has linear opacity from 0.1-0.4
This is all in Matlab.
Thank you


text:
Q: How do I find the URL (stream) of this radio station? Do you guys know how to find the URL of this radio station? http://trap.fm/
I have been trying to watch some youtube videos but I failed to get the right one.
Mind anyone helping me out? Thanks a lot!

A: There are m3u files to download on the right hand side:

For example the listen192.m3u links to this download. Your browser should ask you what to do with the download.
m3u is a simple text file containing the stream url:
#EXTM3U
#EXTINF:-1,TRAP.FM - 192 kbps
http://stream.trap.fm:6002

You can open the m3u file in any media player, for example with vlc.


text:
Q: Customize order confirmation email in SagePay We need to customize SagePay order confirmation mail.
We assigned  'eMailMessage'=>
test

Your order from abc has been successful.

The unique reference for this transaction is: 917-260650635

Dear Vijay V,

Thank you for your order. Your payment has been processed successfully.

test

Please quote your order number 917-260650635 in all correspondence with either abc or Sage Pay.

Bullet Point    Order total:1,200.00 GBP
Card used:Sagepay Test Visa, United Kingdom - Visa - XXXX XXXX XXXX 5559 - Attempt:1
Bullet Point    You bought:917-260650635
Description Quantity    Item Value  Item Tax    Item Total  Line Total
abc12   1   1200.000000 0.000000    1200.000000 1200.00

How we can customize complete template?
Edit:
We want to customize entire layout with Logo and other deatils:
Dear Xxxx Xxxxxx,

Thank you for your order with DDDD .

Your payment has been processed successfully.

The unique reference for this payment is XXX-XXXXXXXXXX, please quote this in all correspondence with either ABC or Sage Pay.

Order Total:  £xxx.xx

Card Used : Name, Card Type , Last Four Digits XXXX

Your Order: Order Reference#

A: Sorry. You can't - you're limited to inserting the contents of the emailMessage field. You'll need to implement some sort of customer notification yourself, if you want to change the email styling / contents.


text:
Q: Command to move folders from one container to another container using Dockerfile I have pulled ubuntu16.04 and run docker image. I need to move all the folders to "mydistribution" folder inside docker image.
docker pull ubuntu:16.04

docker run -it ubuntu

root@cb3e5b5e75e9:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

In my Dockerfile:
FROM ubuntu:16.04
USER root
ENV destpath mydistribution/ubuntu16.04
RUN mkdir -p mydistribution \
    && mkdir -p mydistribution/ubuntu16.04 \

COPY /. $destpath/ -> this will copy everything from current host folder to container, but instead of this, I want to move all the above folders (ls command output in container) into mydistribution/ubuntu16.04 using Dockerfile. I am not sure if we can do this or not, can someone help me to do the same, what will be the command to move them from container to another folder inside container?


text:
Q: How to get sale ID from the new Paypal Sync Api I'm using the new Paypal Sync Api to get all transactions in a period of time. I need to be able to refund them too.
As all our transactions are always sales I need the sale ID to refund a transaction as stated in https://developer.paypal.com/docs/integration/direct/payments/refund-payments/#set-up-your-development-environment
Unfortunately I can not find anything in the transactions response which can be used as a sale ID
{
    "transaction_details": [

        {
            "transaction_info": {
                "paypal_account_id": "6EN7PS8P9DV6J",
                "transaction_id": "05P62542TL3758730",
                "transaction_event_code": "T0006",
                "transaction_initiation_date": "2019-07-04T12:49:55+0000",
                "transaction_updated_date": "2019-07-04T12:53:09+0000",
                "transaction_amount": {
                    "currency_code": "USD",
                    "value": "10.00"
                },
                "fee_amount": {
                    "currency_code": "USD",
                    "value": "-0.49"
                },
                "transaction_status": "S",
                "ending_balance": {
                    "currency_code": "USD",
                    "value": "0.00"
                },
                "available_balance": {
                    "currency_code": "USD",
                    "value": "0.00"
                },
                "protection_eligibility": "01"
            },
            "payer_info": {
                "account_id": "6EN7PS8P9DV6J",
                "email_address": "paypaltester3@test.de",
                "address_status": "Y",
                "payer_status": "Y",
                "payer_name": {
                    "given_name": "Tester Three",
                    "surname": "Tester Three",
                    "alternate_full_name": "Tester Three Tester Three"
                },
                "country_code": "DE"
            },
            "shipping_info": {
                "name": "Tester Three, Tester Three",
                "address": {
                    "line1": "Teststreet. 1",
                    "city": "SomeCity",
                    "country_code": "DE",
                    "postal_code": "23434"
                }
            },
            "cart_info": {
                "item_details": [
                    {
                        "item_quantity": "1",
                        "item_unit_price": {
                            "currency_code": "USD",
                            "value": "10.00"
                        },
                        "item_amount": {
                            "currency_code": "USD",
                            "value": "10.00"
                        },
                        "total_item_amount": {
                            "currency_code": "USD",
                            "value": "10.00"
                        }
                    }
                ]
            },
            "store_info": {},
            "auction_info": {},
            "incentive_info": {}
        }
    ],
    "account_number": "96B45RCG6AX3E",
    "start_date": "2019-07-03T00:00:00+0000",
    "end_date": "2019-07-04T16:00:00+0000",
    "last_refreshed_datetime": "2019-07-15T08:59:59+0000",
    "page": 1,
    "total_items": 15,
    "total_pages": 1,
    "links": [
        {
            "href": "https://api.sandbox.paypal.com/v1/reporting/transactions?start_date=2019-07-03T00%3A00%3A00Z&end_date=2019-07-04T16%3A00%3A00Z&fields=all&page_size=500&page=1",
            "rel": "self",
            "method": "GET"
        }
    ]
}

I tested a refund call with a transactionId and with an invoiceId but both returned "INTERNAL_SERVICE_ERROR".
Is there any way to get the sale ID by an API after the customer has completed the payment or do I have to save the sale ID in a database after creating a payment?
Thanks

A: With T0006 you are lucky, it is a simple PayPal Checkout APIs. transaction, it would be harder with T0002. Anyway, no the response have much more data. The example is below.
You can find it in invoice_number, or invoice_id. If only you had this data during payment creation procedures.
"transaction_details":[
      {
         "transaction_info":{
            "paypal_account_id":"HHHHH",
            "transaction_id":"040404040404040",
            "transaction_event_code":"T0006",
            "transaction_initiation_date":"2019-10-31T06:21:37+0000",
            "transaction_updated_date":"2019-10-31T06:31:02+0000",
            "transaction_amount":{
               "currency_code":"AUD",
               "value":"96.90"
            },
            "fee_amount":{
               "currency_code":"AUD",
               "value":"-4.08"
            },
            "shipping_amount":{
               "currency_code":"AUD",
               "value":"17.90"
            },
            "transaction_status":"S",
            "transaction_subject":"Full License",
            "ending_balance":{
               "currency_code":"AUD",
               "value":"92.82"
            },
            "available_balance":{
               "currency_code":"AUD",
               "value":"92.82"
            },
            "invoice_id":"1110-US1",
            "protection_eligibility":"01"
         },
         "payer_info":{
            "account_id":"HHHHH",
            "email_address":"test@paypal.com",
            "address_status":"Y",
            "payer_status":"Y",
            "payer_name":{
               "given_name":"First",
               "surname":"Last",
               "alternate_full_name":"First Last"
            },
            "country_code":"GB"
         },
         "shipping_info":{
            "name":"Shaun Smith",
            "address":{
               "line1":"123, Some Road",
               "line2":"Shop 4",
               "city":"Melbourne",
               "country_code":"AU",
               "postal_code":"3185"
            }
         },
         "cart_info":{
            "item_details":[
               {
                  "item_name":"Full License",
                  "item_description":"Full License",
                  "item_quantity":"1",
                  "item_unit_price":{
                     "currency_code":"AUD",
                     "value":"79.00"
                  },
                  "item_amount":{
                     "currency_code":"AUD",
                     "value":"79.00"
                  },
                  "total_item_amount":{
                     "currency_code":"AUD",
                     "value":"79.00"
                  },
                  "invoice_number":"1110-US1"
               }
            ]
         },
         "store_info":{

         },
         "auction_info":{

         },
         "incentive_info":{

         }
      },


text:
Q: Angular Resource PUT Operation with Payload I have the following factory to send query to server:
app.factory('Request', ['$resource',
    function ($resource) {
        var res = $resource("bin/server.fcgi/REST/" + ':resourceName/:ID', {}, {
                get : {
                    method : 'GET'
                },
                put : {
                    method : "PUT"
                }
            });
        return {
            get : function (arguments, b, c) {
                return res.get(arguments, b, c).$promise;
            },
            put : function(arguments,b,c){
                return res.put(arguments, b, c).$promise;
            }
        };
    }
]);

I call it like this:
Request[methodName](params).then(successFunction).catch (failFunction);

However, if i want to send a PUT query:
Request["put"](params).then(successFunction).catch (failFunction);

where
params = {
   resourceName : "ATable",
   ID : 222,
   AProperty : "changedValue"
}

I take then following request: (so an error)
http://myadres.com/REST/ATable/222?AProperty=changedValue

instead of
http://myadres.com/REST/ATable/222

with payload
{ AProperty:changedValue }

What is wrong with this?

A: app.service('Request', ['$resource',function ($resource) {
        var res = $resource('bin/server.fcgi/REST/:resourceName/:ID',
            {resourceName: "@resourceName", ID: "@ID"},
            {
                get : { method : 'GET'},
                put : { method : "PUT", params: {resourceName:"@resourceName", ID: "@ID"}//you can leave the string empty if you dont want it to be a defualt value like ID:""
            });

        this.get = function () {
            return res.get().$promise;
        }
        this.put = function(obj){
            return res.put(obj).$promise; // it can be also {like json with your params}
        }
]);

and then call it from controller by
var obj = {
    ID:222,
    resourceName:'ATable'
}
Request.put(obj).then(function(data){
    //check whats the data
})

this is how it should be done
maybe not the best way but should work


text:
Q: After changing text in textarea is not changing when try to change using drop-down list text? I have three multi-select dropdown lists and after selection from these dropdown list user press the submit button and the list text show in textarea but if user change some text in textarea and then again select another list from the dropdown then press submit the text is not changing in textarea.
I tried some solutions such as one the guy said use $("#total_selections").val(""); instead of             $("#total_selections").html(""); but after this nothing is showing in textarea.

  <button type="button" class="btn btn-primary" id="selection_button" disabled>Select Tags</button>

@Html.TextAreaFor(m => m.Formula, new { @class = "form-control", id = "total_selections" })

$("#selection_button").click(function () {
            $("#tag_creation").prop('disabled', false);
            $("#total_selections").val("");
            SelectedItemArray();
        });
    });

    function SelectedItemArray() {
        var datas = new Array();
        var datas = $('.add_item option:selected').map(function ()
        {
            return $(this).text() || undefined;
            }).get();
        $.ajax({
            url: "@Url.Action("selectedTags","CalculatedTags")",
            type: 'Post',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify({ 'selectedTags': datas }),
            success: function (data) {
                $("#total_selections").append(data);
            }
        });
    }

A:

$("#selection_button").click(function () {
               var  sel = $('#add_item option:selected').val();
     const ele= `<p style = "display:inline; background-color: #e9ebee; color: black; margin: 2px; padding: 1px;"> ${sel} <span style="cursor: pointer" onclick= "this.parentElement.remove()"> x</span> </p>`;
     $("#total_selections").append(ele);
});

<select  id="add_item">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

  <button type="button"  id="selection_button" >Select Tags</button>

The append function changes the DOM, and this is not what you are trying to do here (This is what breaks the default behavior of the textarea element).


text:
Q: Get web methods dynamically for an asmx service We have number of asmx services. I want to give an user a page with a textbox to input service url like http://abc.win.com/myservice/customerdata.asmx. When user hit "Load" button, dynamically I add all the web methods to the dropdown. I need some pointers:
1. How to dynamically get all the methods?
2. How can I get the SOAP request for the method selected? So that, we can replace the parameter values with actual values?
Appreciate your help.

A: Kuul13 : You need to modify your webservice URL like http://abc.win.com/myservice/customerdata.asmx?wsdl when user clicks on load button. then you can use we "ServiceDescription" class to get wsdl description and then iterate that to get method names in 'WebMethodInfoCollection' class.
To get SOAP request you need to use SOAPExtension class.This will give you SOAP Request and Response XML.Refere this link for that : http://blog.encoresystems.net/articles/how-to-capture-soap-envelopes-when-consuming-a-web-service.aspx?www.microsoft.com
For dynamically calling webservice look a this V.Good article
http://www.codeproject.com/KB/webservices/webservice_.aspx
Please reply me for any comment.

A: System.Net.WebClient client = new System.Net.WebClient();
System.IO.Stream stream = client.OpenRead("http://www.webservicex.net/globalweather.asmx?wsdl");
ServiceDescription description = ServiceDescription.Read(stream);

ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12";
importer.AddServiceDescription(description, null, null);
importer.Style = ServiceDescriptionImportStyle.Client;
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

CodeNamespace nmspace = new CodeNamespace();
CodeCompileUnit unit1 = new CodeCompileUnit();
unit1.Namespaces.Add(nmspace);

ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
if (warning == 0)
{
    CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");

    string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
    CompilerParameters parms = new CompilerParameters(assemblyReferences);
    CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);

    object[] args = new object[1];
    args[0] = "India";

    object wsvcClass = results.CompiledAssembly.CreateInstance("GlobalWeather");
    MethodInfo mi = wsvcClass.GetType().GetMethod("GetCitiesByCountry");

    RegExpForCountryCity(mi.Invoke(wsvcClass, args).ToString());
}
else
{
    Console.WriteLine("Warning: " + warning);
}

void RegExpForCountryCity(string strHTML)
{
    Regex qariRegex = new Regex(@"
\s*<Country>(?<Country>[\s\S]*?)</Country>\s*<City>(?<City>[\s\S]*?)</City>\s*
", RegexOptions.IgnoreCase | RegexOptions.Multiline);

    MatchCollection mc = qariRegex.Matches(strHTML);

    string strCountryCity = "";

    for (int i = 0; i < mc.Count; i++)
    {
        if (string.IsNullOrEmpty(strCountryCity))
            strCountryCity = "Country: " + "" + mc[i].Groups["Country"].Value + "" + " " + "City: " + "" + mc[i].Groups["City"].Value + "" + "
";
        else
            strCountryCity += "
" + "Country: " + "" + mc[i].Groups["Country"].Value + "" + " " + "City: " + "" + mc[i].Groups["City"].Value + "" + "
";
    }
    Response.Write(strCountryCity);
}


text:
Q: ¿Por qué me aparecen componentes de material UI así? Tengo un dialog que contiene componentes de Form.
Estos son los estilos definidos:
const myStyle = makeStyles(theme => ({
  confclass: {
    background: '#8bc34a',
    borderRadius: 7,
    border: 0,
    color: 'white',
    padding: '0 30px',
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    textTransform: 'capitalize',
    margin: theme.spacing(3)
  },
  delclass: {
    background: '#c62828',
    borderRadius: 7,
    border: 0,
    color: 'white',
    padding: '0 30px',
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    textTransform: 'capitalize',
    margin: theme.spacing(3)
  },
  formControl: {
    marginLeft: theme.spacing(2),
    marginBottom: theme.spacing(2)
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  },
  dialogContent: {
    minHeight: 135,
    marginBottom: 25,
    overflow: 'hidden'
  },
  inputLabelAnsMsg: {
    marginBottom: 30,
    minHeight: 65,
    overflow: 'hidden'
  },
  divTextFields: {
    marginLeft: 20
  }
}));

Este es el código del componente Dialog:
const DialogQuestion = props => {
const classes = myStyle();

      return (
        <Dialog
          open={props.open}
          onClose={props.closeHandler}
          onExit={onExitDialogHandler}
          aria-labelledby='form-dialog-title'
          PaperProps={{
            style: {
              width: '75%',
              maxHeight: '80%',
              backgroundColor: '#e0e0e0'
            }
          }}
        >
          <DialogTitle id='form-dialog-title'>Nueva pregunta</DialogTitle>
          <DialogContent dividers className={classes.dialogContent}>
            <DialogContentText>
              Para crear una nueva pregunta es necesario completar los siguientes
              campos. Puedes cancelar esta acción con el botón Cancelar en la parte
              inferior o dando click por fuera de este cuadro.
            </DialogContentText>

            <TextField
              autoFocus
              id='question'
              label='Pregunta'
              onChange={textFieldQuestionHandler}
              type='text'
              fullWidth
              required
              variant='outlined'
              defaultValue={questionDetails.question}
              error={errorTextField}
              InputProps={{
                startAdornment: (
                  <InputAdornment position='start'>
                    <HelpIcon />
                  </InputAdornment>
                )
              }}
            />

            <input type='file' onChange={handleUploaded} />
          </DialogContent>
          {files.length > 0 && (
            <Carousel arrows>
              {files &&
                files.map(element => {
                  return ;
                })}
            </Carousel>
          )}

            <TextField
              select
              fullWidth
              label='Grupo'
              variant='outlined'
              value={questionDetails.category || group[0].value}
              onChange={event => selectChangeHandler(event, 'category')}
              style={{ marginBottom: 15 }}
            >
              {categoryList}
            </TextField>
            <TextField
              select
              fullWidth
              label='Complejidad'
              variant='outlined'
              value={questionDetails.level || complexity[0].value}
              onChange={event => selectChangeHandler(event, 'level')}
            >
              {levelList}
            </TextField>

          {answerListForm}

          <FormControl component='fieldset' className={classes.formControl}>
            <FormLabel component='legend'>Tipo de pregunta</FormLabel>
            <RadioGroup
              aria-label='questionType'
              name='questionType1'
              value={questionType}
              onChange={handleChangeQuestionType}
            >
              <FormControlLabel
                value={QUESTION_TYPES.OPEN}
                control={<Radio />}
                label='Abierta'
              />
              <FormControlLabel
                value={QUESTION_TYPES.MULTIPLE}
                control={<Radio />}
                label='Múltiple'
              />
              <FormControlLabel
                value={QUESTION_TYPES.BINARY}
                control={<Radio />}
                label='Binaria (T o F)'
              />
            </RadioGroup>
          </FormControl>

          <DialogActions>
            <Button
              className={classes.delclass}
              onClick={cancelDialogHandler}
              color='primary'
              key='cancelButtonNewQuestion'
            >
              Cancelar
            </Button>
            <Button
              className={classes.confclass}
              color='primary'
              key='successButtonNewQuestion'
              onClick={
                dialogAction === 0 ? addQuestionHandler : editQuestionHandler
              }
              disabled={errorChecks || errorOptions || errorTextField}
            >
              {props.dialogAction === 0 ? 'Crear' : 'Guardar cambios'}
            </Button>
          </DialogActions>
        </Dialog>
      );

}
Y esto es lo que aparece:

Debajo del campo de pregunta debería aparecer bien un "Seleccionar archivo" o algo como eso. El botón que se alcanza a ver sí sirve. Y más abajo del botón de "Seleccionar archivo" debería estar un grupo de radios que ni siquiera aparece.

A: Prueba cambiando en tu css la linea:
const myStyle = makeStyles(theme => ({

Por:
const myStyle = makeStyles({

A: Detecté el problema en los <DialogContent>. Los retiré y ajusté las secciones con un div y estilos, eso soluciona la altura de los componentes que no se muestran bien, pero no me satisface la solución. ¿Los <DialogContent> tienen la altura limitada?


text:
Q: ¿Por qué se recomienda utilizar el patrón de diseño en un proyecto web o de aplicación? ¿Por qué se recomienda utilizar el patrón de diseño en un proyecto web o de aplicación? Sólo uso MVC.
¿Depende del tipo de proyecto para usar un patrón de diseño? ¿O depende del equipo del proyecto?

A: Depende del proyecto es lo que debes de usar y también del nivel de conocimiento, si harás un proyecto que sea complejo y su posterior mantenimiento no lo harás tu o lo vas a delagar los patrones de diseño te pueden servir, por otro lado si el proyecto lo mantendrás tu y no quieres quebrarte la cabeza con patrones, modelos y demás cosas hazlo de la manera tradicional
No siempre lo que dicen los libros o lo que está de moda se acomoda a un proyecto, o a una manera de trabajar

A: Este artículo menciona en palabras simples la importancia de los patrones de diseño, en resumen se puede decir:

Los patrones de diseño son soluciones para problemas comunes y recurrentes que nos encontramos cuando desarrollamos un software, a pesar que nuestra aplicación sea única, esta tendrá algunas partes comunes con otras aplicaciones como por ejemplo: acceso a datos, creación de objetos con una sola instancia, integraciones con otras aplicaciones, etc. Todo este conjunto de problemas comunes lo podemos solucionar usando los respectivos patrones de diseño, ya que son soluciones probadas que garantizan su funcionamiento.

A: Encontré esto, hace un tiempo me hice la misma pregunta, la verdad creo que MVC en la actualidad esta algo corto para la cantidad de cosas que requiere un proyecto.
MVC, que ha quedado corto usamos mas de solo 3 elementos para elaborar un sitio web o app exitosa.
https://styde.net/porque-laravel-no-es-mvc-y-tu-deberias-olvidarte-de-mvc/


text:
Q: How to use select box option in vue? I have implemented select box in vue like this:
<select name="count" @change="change($event)">
  <option value="a">one</option>
  <option value="b">two</option>
  <option value="c">three</option>
</select>

I know that if you want to get the selected value from the script, you can receive the event and do event.target.value.
How can I get one,two,three values instead of a,b,c values?

A: You can get the text from the selected option like so,
  methods:{
    change: function(e){
        var id = e.target.value;
        var name = e.target.options[e.target.options.selectedIndex].text;
        console.log('id ',id );
        console.log('name ',name );
    },

<select name="count" @change="change($event)">
   <option value="a">one</option>
   <option value="b">two</option>
   <option value="c">three</option>
</select>

A: The <select> uses the <option> label (the inner text) as the value if the <option> has no value attribute, so you could just remove the value binding:
<select name="count" @change="change($event)">
  <option>one</option>
  <option>two</option>
  <option>three</option>
</select>

demo


text:
Q: Unhandled AccessViolationException Error calling a DLL into VB.Net I'm trying to call a C++-compiled DLL from VB.net and I'm running into some problems. Seems like there's an obvious solution, but I can't figure it out.
Here is the function declaration in C++:
 MyFunction(int trailingaveragesize, double sigmasize, int myflag, int sizeSeries, double *Xdata, double *Ydata, int sizeinputparameter, int *averagePairs, double *PositionsSize, double *PnLSize)

Here is how I'm calling it in VB.Net:
 Call MyFunction(200, 1, 1, 230, a_PriceSeries(0), a_PriceSeries(0), 1, a_Averages(0), a_PositionSeries(0), a_PnLs(0))

The maximum size of the input matrices are defined by sizeSeries (230), and the size of all my input matrices are 10000 (just so I won't accidentally overflow), yet still i'm getting an unhandled AccessViolationException error
 Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

My question is - If I'm not exceeding the bounds of my matrices, what other reasons would throw this error? Is it because I'm only passing the first entry in my matrices ByReference then it's trying to access other elements of that matrix? If so, how would I fix that?
EDIT:
Here's how I'm declaring it in VB
 Declare Function MyFunction Lib "C:\Dev\asdf.dll" (ByVal trailingaveragesize As Long, ByVal sigmasize As Double, ByVal myflag As Long, ByVal sizeSeries As Long, ByRef Xdata As Double, ByRef Ydata As Double, ByVal sizeinputparameter As Long, ByRef averagePairs As Long, ByRef PositionsSize As Double, ByRef PnLSize As Double) As Double

A: Declare Function MyFunction Lib "C:\Dev\asdf.dll" (ByVal trailingaveragesize As Long, _
  ByVal sigmasize As Double, ByVal myflag As Long, ByVal sizeSeries As Long,
  ByRef Xdata As Double, ByRef Ydata As Double, ByVal sizeinputparameter As Long,
  ByRef averagePairs As Long, ByRef PositionsSize As Double, ByRef PnLSize As Double) As Double

The declaration is simply wrong, this resembles a vb6 declaration.  An int in C code is an Integer in vb.net, not a Long.  The Xdata and Ydata are highly likely to be arrays, not a byref double.  Declare them as ByVal Double().  The other byref args are harder to guess.

A: p-invoke is platform invoke, and is how you call into native APIs with .NET.  Your declaration is not currently setup to pass arrays, and it should not be done ByRef.
Try changing the ByRef to ByVal for your array variables and declare them with the () to signify an array.

A: The error is that while I was declaring a variable as type long but it should be of type integer. The variabe rc was the one wrongly declared:
Here the code of my form Form1 (it has one Button and one TextBox):
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    End Sub

Here the code for Button.Click (it initialize some variables used to call a function in a dll):
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim arg1 As String
    Dim arg2 As String
    Dim ret As String

Here is the variable rc that I declared as long. It should be integer
    Dim rc As long
        ret = "123456789012345678901234567890123"
        arg1 = "123456"
        arg2 = "1234567890123456"
        rc = myFunction(arg1, arg2, ret)
        If (rc = 0) Then
            TextBox1.Text = ret
        Else
            TextBox1.Text = "Result not OK"
        End If
    End Sub
End Class

myFunction was declared as integer in myDll:
extern __declspec(dllexport) int __stdcall myFunction(unsigned char * pszArg1, unsigned char * pszArg2, char * pszReturn)

This is how I declared MyFunction in my Visual Basic Express 2010:
Module Module1

    Public Declare Function myFunction Lib "C:\Users\me\MyProjects\myDll\bin\Debug\myDll.dll" (ByVal Arg1 As String, ByVal Arg2 As String, ByVal ret As String) As Integer

End Module


text:
Q: How to access custom swagger vendor extensions in WSO2 API Manager WSO2 Api Manager supports swagger vendor extensions (x- prefix). They are used internally to support throttling. How to access own vendor extensions from code (in Handlers or Mediators)? I couldn't find any vendor extensions registry, or they are not present in MessageContext.
{
  "paths": {
    "/": {
      "post": {
        "x-auth-type": "Application & Application User",
        "x-throttling-tier": "Unlimited",
        "x-mycustom-extension": "someValue", <-- How to get access to this?
        "produces": [
          "application/json"
        ],
        "parameters": [

This is a fragment of swagger 2.0 spec (supported by WSO2 Api Manager). X-auth-type and x-throttling-tier are there already, but there is no way I can use my "x-mycustom-extension".