text:
Q: facebook login view does not have any option to close it I'm facing a strange problem here, i have used a sample code of graph api's (reallylongaddress-iPhone-Facebook-Graph-API-59e6399,  Created by , https://github.com/reallylongaddress/iPhone-Facebook-Graph-API) which was available on github. And i faced these problems:-
1)  I'm having a share button of my own , when i click on it to login to fb a white view (or popup ) apears for almost 5 seconds and it appears evry time when i click on share button to share something on my facebook wall, even if i'm logged in . I reduced this problem to only one time.
2)  The second and main problem now i'm facing is that on login it doesn't have any close button on it , and user must have to login ,other wise the application will not continue. Can i place a close button on this fb login web view?
NOTE:I have also used the fbconnect earlier but i dont wanna use publish dialog box ,, which shows user a dialog box and then user can press on "pulish" or "skip" button. instead i want that what ever the user wants to share on wall can be shared on just one tap on a button. That is why i have used this sample code, but it also has these two problems i have specified above.
Please help me with these 2 problems above or suggest me any other alternative option which does not have the "publish.stream" dialog box.
Thanks

A: In this condition Facebook controller are called by UINavigationController.

A: Finally i solved the problem and placed a close button on the login view. and on tab of this button i closed the login web view


text:
Q: Azure b2c concurrent user logins Is it possible to detect if a user is having concurrent logins to the same application over multiple browers/devices using Azure Active Directory B2C?

A: Unfortunately, Using B2C this is not currently supported, but there is an open feedback request out for this, which you can upvote.
you'd need your own session tracker which you might use via a rest api.
https://feedback.azure.com/forums/169401-azure-active-directory/suggestions/10686759-limit-conccurent-multiple-logins-in-b2c-ad

redpajama_set_name: RedPajamaStackExchange


text:
Q: WCF sessions with a wsHttpBinding and without windows security I need to create a WCF service that is hosted in IIS, uses http transport and hold state in the server's memory. While I'm aware that stateful services aren't a good idea, this last constrain is necessary to make the service work with a legacy client.
My first thought was to asp.net's session to store the values. I activated the asp.net compatibility mode in my service, which gave me access to the HttpContext, but values that were placed in the session object were not being persisted in memory. I assume this was because the http module that handles session state was not correctly configured, but when googling for answer I came across, WCF sessions and thought it might be a better idea to use them.
However, WCF sessions seem what under-document and place a strange set of prerequises on a service, and I haven't been able to find a configuration that suits my needs: must be hosted in IIS, must use http or https transport and can't reply on windows authentication because the client and server will not be part of the same domain. I'm trying to get this going using the wsHttpBinding, I had heard WCF sessions required either security or reliable message, but:
- Using the standard binding and when the servers are not part of the same domain it fails with a "SecurityNegotiationException The caller was not authenticated by the service" exception. This is fairly logical as it was using windows security.

*

*If I disable security complete it fails with a "Contract requires Session, but Binding 'WSHttpBinding' doesn't support it or isn't configured properly to support it."

*If while keeping security disabled I enable reliable message I get the exception "Binding validation failed because the WSHttpBinding does not support reliable sessions over transport security (HTTPS). The channel factory or service host could not be opened. Use message security for secure reliable messaging over HTTP."

*I've tried enabling transport level security but this doesn't seem to make any difference to the error generated
Is there any configuration that might work for me? Or should I just go back to the plan of using asp.net sessions?

A: You can have WCF hold session information in memory in a pretty simple way. To eliminate any possible external influences in my instructions, I'll assume you're starting with a brand new project:

*

*Create a new WCF Service Library project. This project will already contain a service with a WSHttpBiding binding preconfigured.

*Go to the service contract (IService1.cs) and change the ServiceContract attribute to the following:
[ServiceContract(SessionMode = SessionMode.Required)]

*Go to the service implimentation (Service1.cs) and add the following ServiceBehavior attribute to the service class (Service1):
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single)]

*Add session data as members of the service class (Service1):
public class Service1 : IService1
{
    ...

    private string UserFullName { get; set; }

    ...
}

*Use the members to present session specific data (remember to also add them to the service contract, IService1):
public class Service1 : IService1
{
    ...

    public string Welcome(string fullName)
    {
        UserFullName = fullName ?? "Guest";
        return string.Format("Welcome back, {0}!", UserFullName);
    }

    public string Goodbye()
    {
        return string.Format("Come back soon, {0}!", UserFullName ?? "Guest");
    }

    ...
}

SessionMode.Required ensures that your clients are session-tracked.
InstanceContextMode.PerSession ensures that an instance of your service class (Service1) is created for every session, so that you can retain session data in it and it will exist in memory across multiple calls in the same session.
ConcurrencyMode.Single ensures that only one thread can enter each service class instance (Service1), and prevents possible concurrency issues if you only access data from the service class (and external thread-safe locations).
EDIT: By default, WSHttpBinding only allows security sessions. But it also support reliable sessions, which allow establishing sessions without security enabled. The following binding configuration disables security and enables reliable sessions:
<wsHttpBinding>
    <binding name="wsHttpBindingConfiguration">
        <security mode="None" />
        <reliableSession enabled="true" />
    </binding>
</wsHttpBinding>

A: IMO this is what happens when you're using a technology with a poor abstraction over HTTP like WCF. The fact that WCF web services could in theory be hosted without HTTP (i.e. over NET TCP, MSMQ, etc) just makes it hard to use built-in features of HTTP without entering in configuration hell and start a game of "guess the correct configuration by trial and error" where you try every possible configuration permutation until you've found the correct one that works!
Ultimately if you couldn't use WCF and had to implement the web service from scratch you would simply set a cookie when the client successfully authenticated. Then with every client request  just grab the session information referenced by that cookie.
One possible solution if you had to use WCF is to take session management in your own hands (It's what I do when I'm unhappy with the effort required to get something to work) and have an explicit 'Session' property on all your web services that require a session/authentication (usually a guid generated on Authentication). So for each subsequent request you use the guid to rehydrate the session information associated with that client.
If you're interested in trying out different web service frameworks I maintain an Open Source Web Services Framework that lets you build configuration-free, DRY, testable web services where (without any configuration required) each web service you create is automatically accessible over REST XML, JSON, JSV, SOAP 1.1, SOAP 1.2 endpoints. Effectively it allows you to access your same web service via a HTTP GET url for REST-ful clients and easy debugging as well as SOAP endpoints (a popular choice still mandated by some enterprises). The Hello World tutorial should give you a good overview on some of its features and how it works.


text:
Q: Kendo Window Popup Issue : When hit enter key from the Window Popup2 it would open another window popup.
From my main page (1) I have button that will open a window popup (2) and when click on a image then a new window popup opens and when this closes out it should go back to popuup(2) ie. it's parent window. It does close it and goes to it's parent window, when when clicked enter it again open that window. Confirmed that no other calls are calling this openWindow..s till it opens it, somehow looks like that window gets open an enter event.
ListOf Survey page 1 -- Create Button --> which will open another kendo window popup and on this popup an add icon is there and an event when this image is clicked it should open a new popup kendowindow
ListOf Suvery Page : SurveyList.cshtml

<input type="button" id="idCreate" value="Create" class="ui-submit k-button saveGroup" />

 $('#idCreate').click(function () {
        openSurveyWindow(-1);   // -1 is for add mode
    });
function openSurveyWindow(idOfSurvey) {

    var window = $("#windowSurveyList").kendoWindow({
        content: {
            url: "/OrderSurvey/Survey",
            data: { surveyId: idOfSurvey }
        },
        width: "900px",
        height: "768px",
        title: "Create Survey",
        modal: true,
        actions: [

        ]
    });

    var kendoWindow = $("#windowSurveyList").data("kendoWindow");
    kendoWindow.open();
    kendoWindow.center();
}

On the popup page -- SurveyCreate.cstml ( this will be opened by the above window popup)

                    Sign Type

<input type="image"  id="idAddItem" src="Images/add-icon.png" name="image" width="28" height="28" title="Add an Item"/>

 $('#idAddItem').click(function () {

    openItemSelectWindow(); // Adding Mode

});

function openItemSelectWindow() {

            $("#windowSurveyPopup").html('');
            var window = $("#windowSurveyPopup").kendoWindow({
                content: {
                    url: "/OrderSurvey/Survey/AddItemSelect",
                    data: {}
                },
                width: "300px",
                height: "170px",
                title: "Add Item Select",
                modal: true,
                actions: [

                ],
                close: function () {

                }
            });

            var kendoWindow = $("#windowSurveyPopup").data("kendoWindow");
            kendoWindow.open();
            kendoWindow.center();

}

In the windowSurveyPopup window -- AdItemSelect.cstml

UPC:

         <input type="text" name="UPCFind" id="UPCFind" class="Dierbergs-label"  size="15" maxlength="15" onclick="clearTextOC(this)" onKeyUp="numericFilter(this);" />

         <input type="button" id="idFind" style="float:right" value="Find" class="ui-submit k-button saveGroup" />

So if you close the AdItemSelect popup, it comes back to SurveyCreate page but when I hit enter anywhere on the SurveyCreate  page it brings up the AdItemSelect popup and we are using amplifier to publish and subscribe so that we can pass the objects from different pages..


text:
Q: iOS app Video Capture Slows down in low light I have an iOS app that is using the front camera of the phone and setting up an AVCaptureSession to read through the incoming camera data. I set up a simple frame counter to check the speed of data incoming, and to my surprise, when the camera is in low light the frame rate (measured using the imagecount variable in the code) is very slow, but as soon as I move the phone into a brightly lit area the frame rate will almost triple. I would like to keep the high frame rate of image processing throughout and have set the minFrameDuration variable to 30 fps, but that didnt help. Any ideas on why this random behaviour?
Code to create the capture session is below:
#pragma mark Create and configure a capture session and start it running

- (void)setupCaptureSession
{

NSError *error = nil;

// Create the session
session = [[AVCaptureSession alloc] init];

// Configure the session to produce lower resolution video frames, if your
// processing algorithm can cope. We'll specify medium quality for the
// chosen device.
session.sessionPreset = AVCaptureSessionPresetLow;

// Find a suitable AVCaptureDevice
//AVCaptureDevice *device=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSArray *devices = [AVCaptureDevice devices];
AVCaptureDevice *frontCamera;
AVCaptureDevice *backCamera;

for (AVCaptureDevice *device in devices) {

    if ([device hasMediaType:AVMediaTypeVideo]) {

        if ([device position] == AVCaptureDevicePositionFront) {

            backCamera = device;
        }
        else {

            frontCamera = device;
        }
    }
}

//Create a device input with the device and add it to the session.
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:backCamera
                                                                    error:&error];

if (!input) {
    //Handling the error appropriately.
}
[session addInput:input];

// Create a VideoDataOutput and add it to the session
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];

// Configure your output.
dispatch_queue_t queue = dispatch_queue_create("myQueue", NULL);
[output setSampleBufferDelegate:self queue:queue];
dispatch_release(queue);

// Specify the pixel format
output.videoSettings =
[NSDictionary dictionaryWithObject:
 [NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
                            forKey:(id)kCVPixelBufferPixelFormatTypeKey];

// If you wish to cap the frame rate to a known value, such as 30 fps, set
// minFrameDuration.
output.minFrameDuration = CMTimeMake(1,30);

//Start the session running to start the flow of data

[session startRunning];

}

#pragma mark Delegate routine that is called when a sample buffer was written

- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
   fromConnection:(AVCaptureConnection *)connection
{
  //counter to track frame rate
  imagecount++;

  //display to help see speed of images being processed on ios app
  NSString *recognized = [[NSString alloc] initWithFormat:@"IMG COUNT - %d",imagecount];
  [self performSelectorOnMainThread:@selector(debuggingText:) withObject:recognized waitUntilDone:YES];

}

A: When there is less light, the camera requires a longer exposure to get the same signal to noise ratio in each pixel.  That is why you might expect the frame rate to drop in low light.
You are setting minFrameDuration to 1/30 s in an attempt to prevent long-exposure frames from slowing down the frame rate.  However, you should be setting maxFrameDuration instead: your code as-is says the frame rate is no faster than 30 FPS, but it could be 10 FPS, or 1 FPS....
Also, the Documentation say to bracket any changes to these parameters with  lockForConfiguration: and unlockForConfiguration: , so it may be that your changes just didn't take.


text:
Q: Is there a way to make a recursion method with unlimited depth in Python? For example, when writing some algorithms on graphs like
def f(graph):
    #graph is dictionary of pairs vertex_i:{set of edges (i,j)} for 1<=i,j<=n
    def g(vertex):
        for vertex1 in graph:
            do sth
            ...
            for (i,j) in graph[vertex1]:
                ...
                g(j)#recursive call
        ...
        return ...

    return g(1)

limited depth of recursion is sometimes very annoying, because code becomes much longer and more complicated if you have to avoid recursion.
Is there a way to reach unlimited depth?
Maybe you can describe your general solution of the problem on the following method
def nthNumber(n):
    if n==1: return 1
    else: return nthNumber(n-1)+1

(I know it's simple stupid and please don't give answers like "You should have written just nthNumber(n): return n " - I'm intrested in general solution). Thanks for help!

A: Unlimited recursion would require infinite resources; every function call requires a stack entry, and there is only a finite amount of memory to hold those. So, no, you cannot have unlimited recursion depth.
You can raise the limit, by calling sys.setrecursionlimit().


text:
Q: Questions about updates with Entity Framework I am still in the process of getting to know all of the ins and outs of Entity Framework, and I currently find it helpful on a couple of bulk updates to use Entity Framework's ExecuteSqlCommand directly, as it is significantly faster when processing many many thousands of updates (especially when I only need to update a single field). My question is two-fold: first, is this a safe way to handle my updates? To my knowledge, the standard way of updating through EF would be something like
            if (user != null)
            {
                _Context.Entry(user).CurrentValues.SetValues(updatedUser);

                _Context.SaveChanges();
            }

or
            {
                _Context.Entry(updatedUser).State = EntityState.Modified;

                _Context.SaveChanges();
            }

but both of these methods bog down if the number of users to update exceeds ~5000.  Am I missing something, or is my use of ExecuteSqlCommand acceptable?
Second, if it is safe to rely on ExecuteSqlCommand, can I hold on to a context whose sole purpose is this task, rather than re-creating it each time I need it?  My understanding is that in general, contexts should never be maintained as they will slow down over time with use, but I'm wondering if this holds true for such a limited-use scenario as this as well.
If my fundamental approach to EF's use is in error, I would appreciate someone pointing that out as well.  Thanks!

A: EF does not handle bulk operations well at all, There are workarounds like hand writing queries via ExecuteSqlCommand (like you mentioned) or there are 3rd party extensions like EntityFramework.Extended.
For your 2nd part, If all you are going to be using the context for is to call ExecuteSqlCommand it might be better to just new up a normal SqlConnection and SqlCommand on demand and use those (even though you are newing them up every time you call, .NET will be using "Connection Pooling" behind the scenes to reuse connections)


text:
Q: Почему при определителе матрицы равном нулю, она не имеет обратной матрицы? Почему при определителе матрицы равном нулю, она не имеет обратной матрицы?

A: Ну, как вариант - например, потому что определитель произведения двух квадратных матриц равен произведению определителей сомножителей. Имея

получаем, что

Но если

то о какой обратной матрице вообще может идти речь? Если ее определитель просто не существует?


text:
Q: How to use mblox sms service with php I need to integrate mblox sms service via php to send and receive meaages. Is there any open source scripts or resources available to inetegrate mblox using php ?
Thanks in advance.

A: Send a request.  their servers or applications are not open source, but they can send you the API documents to use their systems.  It works both ways, send and receive, when you sign up for their services.  And it's a rather easy API to understand as well.

A: I did see a couple of PHP SDK's for SMS

*

*Link 1

*Link 2

*Link 3


text:
Q: vb.net winforms datagridview how to tell where the user clicked in a cell I am adding a custom column to a custom datagridview.  One of the options this new datagridcolumn has is the ability show a value and then a button to allow the user to click on the button and something will happen.  The button only takes up the right portion of the cell and the rest is a value.  This button and value are displayable always and the button should always be able to be clicked on.  In datagridview's display mode the value and button are painted.  What I need help on is how to tell whether the user clicked on the button portion of the cell.  Can someone please provide example code on how to do this?
Thanks,
Greg

A: Never mind I figured it out.  I just put some logic in the cellclick event of the datagridview to get the GetCellDisplayRectangle and converted that to screen points and got where the mouse is on the screen and did a bounds test with the rectangle contains method.


text:
Q: Format numbers in jTextField Learning Java. I have a made a GUI app.
Tax calculator of sorts.
I have a textfield where the user enters a number, say 1000000.
I want that number formatted to 1,000,000 after the user has exited the field.
How can can I pull it off?


text:
Q: Parser implementation using Jackson So far I have a tweet.json file which inside is collections of tweet. I have constructed a tweet.class which is a collection of objects from the key-value in the tweet.
now i want to implement a parses using jackson which should run through line-by-line in tweet.json and each tweet (line) is parsed to POJO. So each line is a single POJO
How do I do this
This is what I have done
ObjectMapper mapper = new ObjectMapper();
ParsedTweets tweets = mapper.readValue(new File("tweet.json"), tweet.class);

example of json file
 {"text": "MVA/Transport. Greater Hume (Hume Hwy, Holbrook, NSW 2644) at 7 Mar 2017 03:58 #NSWRFS #MVATransport", "user": {"id": "4721717942", "name": "NSW Fire Updates"}, "lang": "en", "coordinates": { "coordinates": [147.273696, -35.785469] , "type":"Point"}, "created_at": "Mon Mar 06 17:29:31 +0000 2017"}
{"text": "Yes! Everything happens for a reason. The rain doesn't want the Swedru people to go& flood Westhills mall this evening", "user": {"id": "724288148", "name": "Pyper Pebbles"}, "lang": "en","created_at": "Mon Mar 06 17:19:49 +0000 2017"}
{"text": "5 Sure-Fire Ways That Can Help You Achieve Better Success In Life , "user": {"id": "41049329", "name": "StarCentral Magazine"}, "lang": "en","created_at": "Mon Mar 06 17:08:36 +0000 2017"}

tweet.class
public class Tweet {
private String text;
private String created_at;
private User user;
private Coordinates coordinates;

public Tweet(){

}

public String getText()
{
    return text;
}

public void setText(String text)
{
    this.text = text;
}

public String getCreated_at()
{
    return created_at;
}

public void setCreated_at(String created_at)
{
    this.created_at = created_at;
}

public User getUser()
{
    return user;
}

public void setUser(User user)
{
    this.user = user;
}

public Coordinates getCoordinates()
{
    return coordinates;
}

public void setCoordinates(Coordinates coordinates)
{
    this.coordinates = coordinates;
}

@Override
public String toString()
{
    return "ClassPojo [text = "+text+", created_at = "+created_at+", user = "+user+", coordinates = "+coordinates+"]";
}

}
Update ReadWriteJson implementation
public class ReadWriteJson {

 public static void main(String[] args) throws IOException {
        assert args != null & args.length > 0;
        List<Tweet> tweet = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        try (BufferedReader reader = new BufferedReader(new FileReader("tweets.json"))) {
            String line;
            while ((line = reader.readLine()) != null){
                tweet.add(mapper.readValue(line, Tweet.class));
            }
        }
    }

A: Assuming the file contains tweets in the below format:
[{
    "id": "1",
    "text" : "abc"
}, {
    "id": "2",
    "text" : "def"
}]

And tweet class has the following fields:
class tweet {
    private String id;
    private String text;
    //getters and setters
    public String toString(){
        return this.id + "," + this.name + "," + this.text + "," + this.coordinates + "," + this.created_at;
}

You can use Jackson's TypeReference to deserialize the list, e.g.:
ObjectMapper mapper = new ObjectMapper();
List<tweet> tweets = mapper.readValue(new File("tweet.json"), new TypeReference<List<tweet>>(){});

Update
As per the updated class and file structures, you need to read the file line by line (as it's not a valid json) and deserialize it into Tweet object, e.g.:
public class Test {
    public static void main(String[] args) throws Exception {
        List<Tweet> tweets = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        try(BufferedReader reader = new BufferedReader(new FileReader("tweet.json"))){
            String line;
            while((line = reader.readLine()) != null){
                tweets.add(mapper.readValue(line, Tweet.class));
            }
        }
    }
}


text:
Q: como usar Order by em ENUM Ola gostaria de saber como usar o ORDER BY para fazer o seguinte na minha SQL tabela categoria coluna modulo eu tenho um ENUM com os seguintes modos 'media','filme','ova' gostaria de fazer uma aplicação para ordenar da seguinte forma no código abaixo para ordenar os itens na ordem media, ova e filme isso no ORDER BY am2.modulo e possível ?
    $medias_skin = $MySQLiconn->query("
    SELECT `am1`.id,`am1`.cat,`am1`.subcat,`am1`.numero,`am1`.episodioTipo,`am1`.fillerType,`am1`.duploType,`am1`.finalType, `am1`.autor,`am1`.fansub,`am1`.arquivo_nome,`am1`.url,`am1`.url2,`am1`.url3,`am1`.url4,`am1`.url5,`am1`.url6,`am1`.url7,`am1`.url8,`am1`.url13,`am1`.url14,`am1`.url15,`am1`.url16,`am1`.url17,`am1`.url18,`am1`.url19,`am1`.url20,`am1`.url25,`am1`.url26,`am1`.url27,`am1`.url28,`am1`.url29,`am1`.url30,`am1`.url31,`am1`.url32,`am1`.linknome01,`am1`.linknome02,`am1`.linknome03,`am1`.linknome04,`am1`.linknome05,`am1`.linknome06,`am1`.linknome07,`am1`.linknome08,`am1`.linknome13,`am1`.linknome14,`am1`.linknome15,`am1`.linknome16,`am1`.linknome17,`am1`.linknome18,`am1`.linknome19,`am1`.linknome20,`am1`.linknome25,`am1`.linknome26,`am1`.linknome27,`am1`.linknome28,`am1`.linknome29,`am1`.linknome30,`am1`.linknome31,`am1`.linknome32, `am1`.player,`am3`.`nome` as mediaNome, `am3`.`animes_categoria_url` as catUrl, `am3`.`animes_subcategoria_url` as subcatUrl, `am2`.`modo` as categoriaModo, `am2`.`modulo` as categoriaModulo, `am2`.`nome` as catNome
    FROM `m_medias` as am1 USE INDEX (medias_indexadas)
    INNER JOIN `m_categoria` as am2 USE INDEX (categoria_index) ON `am1`.`cat` = `am2`.`id`
    INNER JOIN `m_subcategoria` as am3 USE INDEX (subcategoria_index) ON `am1`.`subcat` = `am3`.`id` AND `am1`.`cat` = `am3`.`cat`
    WHERE am1.id IN ($media_id)
    GROUP BY `am1`.`id`,`am1`.`subcat`
    ORDER BY am2.modulo
    ");

A: Baseado no exemplo da documentação:

Valores ENUM são classificados com base em seus números de índice, que dependem da ordem em que os membros de enumeração foram listados na especificação da coluna. Por exemplo, os tipos "B" antes "a" para ENUM ('b', 'a'). Os tipos cadeia vazia antes strings não-vazias, e valores NULL vem antes de todos os outros valores de enumeração.
Para evitar resultados inesperados ao usar a cláusula ORDER BY em uma coluna ENUM, use um dos seguintes técnicas:

*

*Especifique a lista ENUM em ordem alfabética.

*Certifique-se de que a coluna é classificadas em ordem alfabética e não por número de índice de codificação ORDER BY CAST (col AS CHAR) ou ORDER BY CONCAT (col).

Para uma consulta usando o CAST, seria então:
SELECT enum_col FROM tbl_name ORDER BY CAST(enum_col AS CHAR);

Para o teu caso:
ORDER BY CAST(am2.modulo AS CHAR);

A: Para dados numéricos, considerando que media é 1, ova é 2 e filme é 3:

*

*am2.modulo -> 1 (media)

*am2.modulo -> 2 (mova)

*am2.modulo -> 3 (filme)
ORDER BY am2.modulo ASC
Para dados em formato char ou varchar, deverá criar uma tabela para indicar a ordem.
Exemplo
Tabela modulo_position
Colunas:
modulo_id
modulo_position

Por fim, tudo depende da modelagem.
Recomendo que utilize a segunda abordagem, criando uma tabela onde terá as referências de ordenação.


text:
Q: Embedding a webpage with d3 into shiny Here is some interesting/ annoying behavior.  The below code is the "Hello world" of shiny apps (old faithful geyser), with only one addition in the UI:
includeHTML('https://bl.ocks.org/mbostock/e6f9e160585c153fa5ec543bd12b81e9')

)
I also split it into tabPanels for clarity.
That link above is to a standard D3 example on bl.ocks.org.  However when it renders in shiny, the d3 block simply renders as "Not Found".
Any idea how to get around this and embed a website with d3 into shiny?
Full reproducible code:
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("Old Faithful Geyser Data"),
   tabsetPanel(
     tabPanel("main",
   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
         sliderInput("bins",
                     "Number of bins:",
                     min = 1,
                     max = 50,
                     value = 30)
      ),

      # Show a plot of the generated distribution
      mainPanel(
         plotOutput("distPlot")
      )
   )),
   ## Illustrate that d3 does not render
   tabPanel("no_d3",
     includeHTML("https://bl.ocks.org/mbostock/e6f9e160585c153fa5ec543bd12b81e9")
   )
))

# Define server logic required to draw a histogram
server <- function(input, output) {

   output$distPlot <- renderPlot({
      # generate bins based on input$bins from ui.R
      x    <- faithful[, 2]
      bins <- seq(min(x), max(x), length.out = input$bins + 1)

      # draw the histogram with the specified number of bins
      hist(x, breaks = bins, col = 'darkgray', border = 'white')
   })
}

# Run the application
shinyApp(ui = ui, server = server)


text:
Q: How to Integrate $\int\frac{(x^2)}{\sqrt{7-x^2}}dx$. I am trying to Integrate $\int\frac{(x^2)}{\sqrt{7-x^2}}dx$ and I have worked this problem a couple times and keep getting the same answer. So I will show my process and please point my errors out.
$$a=\sqrt{7}\hspace{10pt} x=\sqrt{7}\sin\theta\hspace{10pt}dx=\sqrt{7}\cos\theta d\theta \hspace{7pt}7-x^2=7\cos^2\theta$$
$$\int\frac{7\sin^2\theta \sqrt{7}\cos\theta d\theta}{\sqrt{7\cos^2\theta}}$$
$$7\int\sin^2\theta d\theta\rightarrow \frac{7}{2}\int1-\cos(2\theta)d\theta$$
$$\frac{7}{2}\left(\theta-\frac{\sin(2\theta)}{2} \right) \rightarrow \frac{7}{2}\left(\sin^{-1}\left(\frac{x}{\sqrt{7}}\right)-\frac{2\sin\theta\cos\theta}{2} \right)$$
$$\frac{7}{2}\left(\sin^{-1}\left(\frac{x}{\sqrt{7}}\right)-\frac{x}{\sqrt{7-x^2}}\frac{\sqrt{7-x^2}}{\sqrt{7}} \right)$$
$$\frac{7}{2}\left(\sin^{-1}\left(\frac{x}{\sqrt{7}}\right)-\frac{x}{\sqrt{7}} \right)$$
But apparently the answer is
$$\frac{1}{2}\left(7\sin^{-1}\left(\frac{x}{\sqrt{7}}\right)-x\sqrt{7-x^2} \right)$$
So how do I go about getting that answer? Thanks for all the help in advance.

A: I suppose that the error is when you worked $$\frac{2\sin\theta\cos\theta}{2}=\sin\theta\cos\theta$$ You had $\sin\theta=\frac{x}{\sqrt 7}$, so $\cos^2\theta=1-\frac{x^2}{ 7}$, $cos \theta=\sqrt{1-\frac{x^2}{7}}$ and then $$\sin\theta\cos\theta=\frac{x}{\sqrt 7}\sqrt{1-\frac{x^2}{7}}=\frac{1}{7}x\sqrt{7-{x^2}} $$
I am sure that you can take from here.
By the way, it could have been faster getting rid of the radical in denominator, setting $x=\sqrt{7-u^2}$, $dx=-\frac{u}{\sqrt{7-u^2}}$ so the integrand reduces to $-\sqrt{7-u^2}$ from which you start the substitution (just as you did).

A: You look like you are on the right path, and have the triangle drawn out correctly. I recommend using the substitution $\frac{x}{\sqrt{1-x^2}}=\tan(\theta)$. This should convert your integral into $$7\int \! \tan(\theta)\sin(\theta)\cos(\theta) \, \mathrm{d}\theta=7\int \!\sin^2(\theta) \, \mathrm{d}\theta$$ Now using the identity $sin^2(\theta)=\frac{1-\cos(2\theta)}{2}$ our integral becomes much easier. It should be obvious that $$7\int \! \frac{1-\cos(2\theta)}{2} \, \mathrm{d}\theta=\frac{7}{2}\left[\theta-\frac{1}{2}\sin(2\theta)+C \right]=\frac{7}{2}\left[\theta-\sin(\theta)\cos(\theta)+C \right]$$ Now we can go back to our substitutions from earlier and solve for $\theta$. Using the substitution $x=\sqrt{7}\sin(\theta)$ and $\sqrt{\frac{7-x^2}{7}}=\cos(\theta)$ it shouldn't be too difficult to get $\theta=\arcsin(\frac{x}{\sqrt{7}})$ and $\theta=\arccos\left(\sqrt{\frac{7-x^2}{7}}\right)$. Now we may plug the appropriate $\theta$ back into our indefinite integral to find $$\frac{7}{2}\left[\arcsin\left(\frac{x}{\sqrt{7}}\right)-\sin\left(\arcsin\left(\frac{x}{\sqrt{7}}\right)\right)\cdot\cos\left(\arccos\left(\sqrt{\frac{7-x^2}{7}}\right)\right)+C \right]$$ $$=\frac{7}{2}\left[\arcsin\left(\frac{x}{\sqrt{7}}\right)-\left(\frac{x}{\sqrt{7}}\right)\cdot\left(\sqrt{\frac{7-x^2}{7}}\right)+C \right]$$ This should be identical to your result above, once you factor in the ${7}$ out front.

A: $$\frac{x^2}{\sqrt{7-x^2}}=\frac{7-(7-x^2)}{\sqrt{7-x^2}}=7\cdot\frac1{\sqrt{(\sqrt7)^2-x^2}}-\sqrt{(\sqrt7)^2-x^2}$$
Now, $$\int\frac{dx}{\sqrt{a^2-x^2}}=\arcsin\frac xa$$
and $$\int\sqrt{a^2-x^2}dx=x\frac{\sqrt{a^2-x^2}}2+\frac{a^2}2\arcsin\frac xa$$
Reference : http://www.sosmath.com/tables/integral/integ13/integ13.html


text:
Q: What is the best way to redirect a user to mobile site based on device using custom handlerinterceptor in Spring Right now we are working on a project that will have a desktop and a mobile version of the site, created in Spring. We want the mobile and the desktop version to share the same Spring security system etc.
We are using Spring mobile to detect whether or not the device is mobile, and may possibly use the Spring site preference parameter.
We dont want to use the spring mobile redirector, as this appears to redirect to another domain (eg m.website.com), and would not use the same spring security easily.
So I am thinkin gof using a HandlerInterceptor to redirect to a specfic directory within the site - eg "/jsp/mobile/".
1) Is it possible in this extended HandlerInterceptor to use the Spring Mobile device detector in the preHandle method?
2) What is the best way to redirect? Is it a) to just use the http response, or b) to somehow change the viewResolver and change the prefix from "/jsp/" to "/jsp/mobile/"
Sorry for the long winded question, but I hoped to put as much info in as possible about what we are trying to do!
Cheers

A: I am currently using a HandlerInterceptor in the pre handler method makes the assessment of whether or not the application is a mobile device, if coming from a mobile device, through the method requestUri get current address and places as prefix "m" after the name of the application context. Then do a redirect:
response.sendRedirect("/application/m/.....") ( documentation )
Example
/application/user           //recived
/application/m/user         //sent

The problem is that this interceptor intercepts all requests, therefore it is necessary to assess the following:

*

*if the request comes with a path like "/application/m/....." not verify that comes from a mobile device, because the "m" and says it does me

*if you let spring handle static resources, the interceptor must not redirect if the requests come from a mobile device (the mobile version and the normal share these resources)

A: Thanks for the answer. What I did is use a HandlerInterceptor and changed the view name in the post handle method like so:
if (modelAndView.getViewName() != null)
{
    modelAndView.setViewName("/mobile/" + modelAndView.getViewName());
}
else
{
    modelAndView.setViewName("/mobile/");
}

Plus that is wrapped in an if else agains whether the device is mobile or not, by injecting DeviceResolver into the constructor and then resolving the local device.


text:
Q: How to make a reaction collector for a bot's message Now I'm making a reaction collector, and it worked, but the bot would add a reaction to my message instead of it's own, but when I made it add the reaction to itself, I can't use the variable I used in the promise for the collector.
import { ICommand } from 'wokcommands'
import { Message, MessageEmbed, MessageReaction, User } from 'discord.js'

export default {
    category: 'Testing',
    description: 'Tests the collector system',
    hidden: true,

    callback: ({ message, channel }) => {

        const answerUsernameEmbed = new MessageEmbed()
        .setTitle('Please confirm this action')
        .setColor('#1be730')
        message.reply({
            embeds: [answerUsernameEmbed]
        }).then((newMessage) => {
            newMessage.react('')
        })

        const filter = (r: MessageReaction, user: User) => {
            return user.id === message.author.id
        }

        const collector = message.createReactionCollector({
            filter,
            max: 1,
            time: 1000 * 10,
        })

        collector.on('collect', reaction => {
            console.log(reaction.emoji.name)
        })

        collector.on('end', collected => {
            if (collected.size === 0) {
                const badCollector = new MessageEmbed()
                .setTitle('You did not react in time...')
                .setColor('#ff0000')
                message.reply({
                    embeds: [badCollector]
                })
                return
            }

            let text = 'Collected:\n\n'

            collected.forEach((message) => {
                text += `${message.emoji.name}\n`
            })

            message.reply(text)
        })
    }
} as ICommand

As you can see, I could use .then to make the bot react to its own message, but then newMessage is inaccessible outside of the scope of the promise, and I can't put the collector inside the promise, because that gives me like 8 errors at once...

A: When trying to react to messages, it's best to use the await function and set the message to a variable. As in:
const reactMsg = await message.reply({embeds:
    [answerUsernameEmbed]}).then(reactMsg.react(''))

This should avoid your message variable being inside or outside of the global scope. Now you can use it anywhere, and you still get the reaction on the correct message as it's literally waiting for it to send, then reacting to it.
https://discordjs.guide/popular-topics/reactions.html#reacting-to-messages.
The DJS guide has some helpful information on this if you need more help and haven't checked it out yet.


text:
Q: jquery submit() ignores changes to input tags I have a jquery.submit() event handler. What I am trying to do is to catch the submit, and based on certain criteria, modify some of the values (actually, wipe them blank) of the input tags on the submitted form. When I step through with a debugger, I see that the fields are correctly being modified, but once the form submits, I see that it has submitted the original values. Is there a way to do what I am trying to do?

$('#views-exposed-form-find-a-rep-page-1').submit(function(event) {
    //$('.find-a-rep-search').click(function() {
        var address = $('#edit-geo-location');
        var countyField = $('#edit-field-county-value');
        //var stateField = $('#edit-state');
        var postalField = $('#edit-postal-code');
        var contact = $('#edit-field-rep-contact-name-value');
        var disabled = $('input:disabled');
        if(address.val() !== "") {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode( { 'address': address.val()}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) { //if the input wasn't total garbage
                    var county = '';
                    var state = '';
                    var postal = '';
                    ....more logic here....                    }
                    //LOGIC:
                    //1) If we have county and state, use that to validate
                    //2) If we don't have county, use state and zip to validate
                    if (county !== '' && state !== '') {
                        countyField.val(county + ", " + state);
                        //stateField.val(state);
                        postalField.val(postal); //don't need this, but don't think it will harm
                        contact.val(""); //wipe this field so that it doesn't show up in the search url
                        disabled.prop('disabled', false); //undisable any disabled fields so views query works correctly
                        //$('#edit-name-or-location-0-wrapper input[name="name-or-location"][value="0"]').attr('checked','checked'); //reset this
                        //$('#views-exposed-form-find-a-rep-page-1').submit();
                    }
                    else if(county == "" && state !== '') {
                        var message = 'Location not specific enough, please re-enter.';
                        $('.message-box').html(message);
                        event.preventDefault();
                    }
                    else if (county == '' && state == '') { // use zip code instead
                        countyField.val(""); //wipe
                        //stateField.val(state);
                        postalField.val(postal);
                        disabled.prop('disabled', false); //undisable any disabled fields so views query works correctly
                        //@todo - do we want it to die here if the geocode doesn't have a county field?
                        //$('#views-exposed-form-find-a-rep-page-1').submit();
                    }
                }
                else {
                    var message = 'Invalid location, please re-enter.';
                    $('.message-box').html(message);
                    event.preventDefault();
                }
            });

        }
        else if(contact.val() !== "") {
            countyField.val(""); //wipe these fields
            //stateField.val("");
            postalField.val("");
            address.val("");
            disabled.prop('disabled', false); //undisable any disabled fields so views query works correctly
            //$('#views-exposed-form-find-a-rep-page-1').submit();
        }
        else {
            var message = 'No representative name or location has been provided.';
            $errorMessageBox = $('.section div.messages.error');
            if($errorMessageBox.length){
                $errorMessageBox.html(message);
            }else{
                $('#content-area').prepend('' + message + '');
            }
            event.preventDefault();
        }
    }); //end click function

A: You need to attach a click event to the submit button and change the values there and in the submit the form
$('#submit_button').click(function(event) {
    event.preventDefault();
   // make the changes here and afterwards submit the form
    $('#views-exposed-form-find-a-rep-page-1').submit();
});

You can also try it like this
$('#views-exposed-form-find-a-rep-page-1').submit(function(event) {
    event.preventDefault();
   // make the changes here and afterwards submit the form
    $('#views-exposed-form-find-a-rep-page-1').submit();
});


text:
Q: How to display HashSet objects in preserve order? Basically HashSet following insertion order is not preserved, but I want to display HashSet objects in the form of preserve order in Java.
Is it possible? If yes then can you please share some ideas.
Thanks in advance
JP.

A: Use LinkedHashSet instead of HashSet. LinkedHashSet will maintain the insertion order.

A: For Set there is LinkedHashSet and for Map there is LinkedHashMap - both retain the order in which items were inserted although there is a very small performance impact.
There is also the option of TreeMap and TreeSet which do not retain the order in which elements were inserted but instead keeps them in a specified order (either their natural ordering or as specified by a comparator).

A: If the order of insertion is important, maybe you should use an ArrayList.

A: You can use LinkedHashSet, which preserves insertion order.

A: Use LinkedHashSet it preserves the order of insertion.
Set<String> set = new LinkedHashSet<String>();
    for(int i = 0; i <5; i++)
    {
        set.add( i+"" );
    }
    // insertion order is 0,1,2,3,4
    for(String str : set)
    {
        System.out.println(str);
    }

    //output 0,1,2,3,4


text:
Q: The Picker isnt getting the data from the array which is being pulled from firebase I have 2 pickers here and the values of the pictures are assigned to the data that is being pulled from firebase. It is assigned to an array and then those values are assigned to the picker. This isn't working and I'm not really sure why.
Here is my code:
import UIKit
import Firebase
import FirebaseDatabase
class SearchSelectVC: UIViewController, UIPickerViewDelegate , UIPickerViewDataSource{

    @IBOutlet weak var locationPicker: UIPickerView!
    @IBOutlet weak var datePicker: UIPickerView!
    @IBOutlet weak var locationLB: UILabel!
    @IBOutlet weak var dateLB: UILabel!

    var locData: [String] = [String]()
    var dateData : [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        initPickers()
        getLoc(onCompletion: { (data) in
            print(data)
            self.locData = (data)
            print(self.locData)
       })
    }

    func getDate(onCompletion: @escaping ([String]) -> ()) {
        var data : [String] = []
        let selectedLoc = locationLB.text
        var dateRef: DatabaseReference!
        dateRef = Database.database().reference().child("launch").child((selectedLoc)!)
        dateRef.observe(.value) { (snapshot) in
            for child in snapshot.children {
                let snap = child as! DataSnapshot
                let key = snap.key
                data.append(key)
                print("date = \(key)")
                //print(data)

            }
            onCompletion(data)
        }
    }
    func getLoc(onCompletion: @escaping ([String]) -> Void){
        print("here3")
        var data : [String] = []
        var locRef: DatabaseReference!
        locRef = Database.database().reference()
        print("here4")
        locRef.child("launch").observe(.value) { snapshot in
            for child in snapshot.children {
                let snap = child as! DataSnapshot
                let key = snap.key
                data.append(key)
                print("location = \(key)")
                //print(data)

            }
            onCompletion(data)
        }

    }
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        if(pickerView == locationPicker){
            return 1
        }
        else if(pickerView == datePicker){
            return 1
        }
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if (pickerView == locationPicker) {

            return locData.count
        }
        else if (pickerView == datePicker) {

            return dateData.count
        }
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView == locationPicker) {
            return locData[row]
        }
        else if(pickerView == datePicker){
            return dateData[row]
        }
        return "thisisbad"
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        if(pickerView == locationPicker){
            updateLabelLoc()
            getDate(onCompletion: { (data) in
                print(data)
                self.dateData = data
            })
        }
        else if(pickerView == datePicker){
            updateLabelDate()
        }
    }
    func updateLabelLoc(){
        let location = locData[locationPicker.selectedRow(inComponent: 0)]
        locationLB.text = location
    }
    func updateLabelDate(){
        let date = dateData[datePicker.selectedRow(inComponent: 0)]
        dateLB.text = date
    }
    func initPickers(){
        locationPicker.delegate = self
        locationPicker.dataSource = self
        datePicker.delegate = self
        datePicker.dataSource = self
    }

}

The data is in a completion handler and on completion, it returns the data from the database correctly. The pickers display without any data inside of them.
Thanks!

A: create:
func updatePickers() {
   locationPicker.reloadAllComponents()
   datePicker.reloadAllComponents()
}

After the print(self.locData) (in getLoc(onCompletion:) (in viewDidLoad()), put:
self.updatePickers()


text:
Q: LibreOffice doesn't display images My LibreOffice is not showing images. They look like this:

Can someone help?

A: Maybe displaying images is disabled? This is possible and very useful to speed up working with large documents holding a lot of images. Check Menu Tools > Options > LibreOffice Writer > View:

Make sure Graphics and Objects isn't disabled.


text:
Q: On the level of measure theory, what does it mean for a drift to be deterministic? Given a drift $F\in W^{1,2}([0,T])$ adapted to the filtration of a Brownian motion $B(t)$ on Wiener space $(C[0,T],\mathcal B(\|\cdot \|_\infty)$ with Wiener measure $\mu_0$, there is another measure $\mu\ll \mu_0$ on Wiener space so that $B(t)$ under $\mu$ is $F(t)+\tilde B(t)$ by Cameron Martin Girsanov.
What does it mean for $F$ to be deterministic on the level of $\mu$? More precisely, is there a convex function $D$ defined on the space of all Girsanov measures so that $D(\mu)=0$ if and only if $\mu$ corresponds to a deterministic drift?
I know of one such function, but it is not convex (I don't think).
Let $$D(\mu)=D_{KL}(\mu||\mu_0)-\frac12\int_0^T\left(\partial_sE_\mu[\omega(s)]\right)^2ds$$
Then this is simply
$$\int_0^T\operatorname{var}_\mu(F'(s))ds$$
Is there a way of making this convex?


text:
Q: Problem when requiring module in ionic framework In my project (using the ionic-framework 3) I have used following statement to require the dialogflow module:
const dialogflow = require('dialogflow');

On compilation it's throwing the following error:

cannot find name 'require'.

How can I resolve this?

A: Add types to tsconfig.json
"types": [
    "node"
],
"typeRoots": [
    "node_modules/@types"
]


text:
Q: Parse mutually exclusive input arguments with MATLAB's input parser I have a function that has at least two required input arguments. Depending on the value of the second argument, there might be a third required input argument. I am wondering what is the best way to code a robust function that incorporates these requirements using MATLAB's input parser?
The function may look like this:
function vout = test(ReqInpArg1, ReqInpArg2, varargin)

ReqInpArg2 may hold the following string content:

*

*'cash'

*'absHurdleRate'

*'none'
If the user chooses cash, than another input argument numCashTicker needs to be defined as part of varargin, e.g. 'numCashTicker', 4. If absHurdleRatehas been choosen, a different input parameter has to be defined, e.g. 'hurdleRate', 0.2. If, on the other hand, none has been chosen, none of these input parameter must be defined. As a matter of fact, numCashTicker and hurdleRate are mutually exclusive, i.e. they must not be defined at the same time. In addition, if the user didn't chose none, he must define one of the other varargin input arguments.
What is best practice / the best strategy in order to implement these requirements?

A: I came up with the following solution:
function vout = test(timeSeries, hurdleRate, varargin)
    p = inputParser;
    expectedTypes = {'none', 'cash' 'absHurdleRate'};
    default_numCashTicker = [];
    default_absHurdleRate = [];
    p.addRequired('timeSeries');
    p.addRequired('hurdleRate',@(x) any(validatestring(x,expectedTypes)));
    p.addParameter('numCashTicker', default_numCashTicker);
    p.addParameter('absHurdleRate', default_absHurdleRate);

    parse(p, timeSeries, hurdleRate, varargin{:});

    numCashTicker = p.Results.numCashTicker;

    switch hurdleRate
        case 'none'
            if ~isequal(numCashTicker, default_numCashTicker)
                throw(MException('test:ParsingError', ...
                    '"none" does not require the "numCashTicker" parameter values"'));
            elseif ~isequal(absHurdleRate, default_absHurdleRate)
                throw(MException('test:ParsingError', ...
                    '"none" does not require the "absHurdleRate parameter values"'));
            end

        case 'cash'
            if ~isnumeric(numCashTicker)
                throw(MException('test:ParsingError', ...
                    '"cash" requires a numeric "numCashTicker" parameter value'));
            elseif ~isequal(absHurdleRate, default_absHurdleRate)
                throw(MException('CSmomRoC:ParsingError', ...
                    '"cash" does not require the "absHurdleRate parameter values"'));
            end

        case 'absHurdleRate'
            if ~isnumeric(absHurdleRate)
                throw(MException('CSmomRoC:ParsingError', ...
                    '"absHurdleRate" requires a numeric "absHurdleRate" parameter value'));
            elseif ~isequal(numCashTicker, default_numCashTicker)
                throw(MException('CSmomRoC:ParsingError', ...
                    '"absHurdleRate" does not require the "numCashTicker" parameter value.'));
            end
    end

    ...
    ...
    ...
end;


text:
Q: Reducing the cyclomatic complexity with getters and setters, from multiples POJOS this question is for Spring java. I have a problem with the bunches of If statements:
Actually I have two pojos in a service layer.
I get the field from one pojo. If this field contains info, I'll set the response to the other pojom passing through an especific decrypt method.
Original Example:
if (clReq.getIdCliente() != null && clReq.getIdCliente().trim().equals("")) {

entity.setFiId(Integer.valueOf(RijndaelCrypto.decrypt(clReq.getIdCliente(), IV, this.privateKey)));

} else {

throw new ClientesBOException("3-FALTA DATOS REQUERIDOS-ERROR");
}

Example 2: I reduce the main condition in an external method:
if (validaCha(clReq.getIdCliente())) {
entity.setFiId(Integer.valueOf(RijndaelCrypto.decrypt(clReq.getIdCliente(), IV, this.privateKey)));
}

External Method:
public static final boolean validaCha(String val) throws ClientesBOException {
    if(StringUtils.isBlank(val)) {
       throw new ClientesBOException("ERROR!, Mandatory data missing");
    }
    return true;
  }

The main problem!! The pojo contains 30 fields. I must validate each field, because the Decryption. Now I have this 30 times, with different attributes.
     if (validaCha(clReq.getIdCliente())) {
 entity.setFiId(Integer.valueOf(RijndaelCrypto.decrypt(clReq.getIdCliente(), IV, this.privateKey)));
          }

I´m looking for help.
I read about make the condition inside set methods from entity pojo.
Use Map.
Use patterns.
Finally I dont find the light
Thanks!!!!!!


text:
Q: How to extract 20-80 relations from data (Pareto principle)? There are certain input-output processes that display a "20-80 relation". That is, given Y depending on X, there are subsets of X consisting 20% of the input set that generate 80% of the output.  For example, 20% of clients may generate 80% of revenues (or complaints), 20% of product flaws generate 80% of complaints, etc.
Are there known methods to see if a given data set satisfies this 20-80 principle?


text:
Q: Can't recieve data from JSON - PHPMyAdmin I have a PHP script that I use to get some information from a BBDD:
<?php
//Creating a connection
$con = mysqli_connect("localhost:3306","root","","database");

if (mysqli_connect_errno())
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql= "SELECT * FROM tQuestions";

$result = mysqli_query($con ,$sql);

while ($row = mysqli_fetch_assoc($result))
{
    $array[] = $row;
    (ONLY USED ON SECOND TRY) echo $row;
}
header('Content-Type:Application/json');

echo json_encode($array);

mysqli_free_result($result);

mysqli_close($con);
?>

When I use it on my Android App I receive a null value. Also when I go the correct link I receive a page with no information and a void JSON file.
When I put an echo $row to see what I'm receiving, I have a string like this: ArrayArrayArrayArray, which has 50 "Array" words which are the same as the rows I have on the database.
What am I doing wrong?
This is my Android code:
private void getQuestionsFromDB() {

    AsyncTask<Void, Void, JSONArray> asyncTask = new AsyncTask<Void, Void, JSONArray>() {
        @Override
        protected JSONArray doInBackground(Void... params) {

            JSONArray array = null;
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://www.am-motion.eu/scriptsapp/preguntas.php")
                    .build();
            try {
                Response response = client.newCall(request).execute();

                array = new JSONArray(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return array;
        }

        @Override
        protected void onPostExecute(JSONArray array) {
            try {
                for (int i = 0; i < array.length(); i++) {
                    JSONObject object = null;
                    object = array.getJSONObject(i);

                    listQuestions.add(object.getString("Question"));

                    listAnswers.add(object.getString("Answer1"));
                    listAnswers.add(object.getString("Answer2"));
                    listAnswers.add(object.getString("Answer3"));
                    listAnswers.add(object.getString("Answer4"));

                    listCorrectAnswer.add(object.getString("Answer"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    asyncTask.execute();
}

A: Your problem is that you're passing all the array to the 'json_encode' function. You have to use a for or foreach cycle to parse the values:
for ($i = 0; $i < sizeof($array); $i++) {
    echo json_encode($array[$i]);
}

And if you want a JSONArray you can use:
for ($i = 0; $i < sizeof($array); $i++) {
    if($i==0){
        echo '[';
        echo json_encode($array[$i]);
    } else if ($i == sizeof($array) -1) {
        echo json_encode($array[$i]);
        echo "]";
    } else {
        echo json_encode($array[$i]);
        echo ",";
    }
}


text:
Q: Custom Legend multiple colors in Google Chart I am facing a problem that I cannot custom the default legend color of this chart to multiple colors, please help me.
This is image describe my problem , I am using stacked bar chart. This is my code:
//dump data arr
var data = google.visualization.arrayToDataTable([[["","0 times (never)",{"role":"style"},"1 times",{"role":"style"},"2 times",{"role":"style"},"3 times or more",{"role":"style"}],["A class",0.581,"#b4ddfd",0.109,"#84bfef",0.21,"#559ad2",0.1,"#4277a1"],["nationality",0.481,"#ffddba",0.209,"#ffc384",0.25,"#ffac5b",0.06,"#fa993f"]],[["","0 times (never)",{"role":"style"},"1 times",{"role":"style"},"2 times",{"role":"style"},"3 times or more",{"role":"style"}],["A class",0.1,"#b4ddfd",0.2,"#84bfef",0.3,"#559ad2",0.4,"#4277a1"],["nationality",0.4,"#ffddba",0.3,"#ffc384",0.2,"#ffac5b",0.1,"#fa993f"]],[["","0 times (never)",{"role":"style"},"1 times",{"role":"style"},"2 times",{"role":"style"},"3 times or more",{"role":"style"}],["A class",0.5,"#b4ddfd",0.5,"#84bfef",0,"#559ad2",0,"#4277a1"],["nationality",0,"#ffddba",0,"#ffc384",0,"#ffac5b",1,"#fa993f"]],[["","0 times (never)",{"role":"style"},"1 times",{"role":"style"},"2 times",{"role":"style"},"3 times or more",{"role":"style"}],["A class",0.01,"#b4ddfd",0.02,"#84bfef",0.03,"#559ad2",0.94,"#4277a1"],["nationality",0.4,"#ffddba",0.3,"#ffc384",0.2,"#ffac5b",0.1,"#fa993f"]]]);
var options = {
        series: {
            0: {
                color: '#b4ddfd'
            },
            1: {
                color: '#84bfef'
            },
            2: {
                color: '#559ad2'
            },
            3: {
                color: '#4277a1'
            },
        },
        vAxis: {
            textStyle: {fontSize: 11},
            titleTextStyle: {italic: false},
        },
        chartArea: {
            width: '85%',
            height: areaHeight,
            top: 30,
            left: '13%'
        },
        bar: {groupWidth: '35%'},
        legend: {
            position: 'bottom',
            textStyle: {fontSize: 11},
        },
        isStacked: 'percent',
        hAxis: {
            ticks: [0, 1],
            textStyle: {fontSize: 13},
            minValue: 0,
            maxValue: 1,
        },
        callbackLegend: function(legend) {
            // my problem here
            // var legend_div = document.getElementById(graphId + '_legend');
            // legend_div.innerHTML = legend.innerHTML;
        },
        width: 920,
        height: areaHeight + 100
    };
var chart = new google.visualization.BarChart(document.getElementById('#chart_div'));
    chart.draw(data, options);

Please help me, I am deadlocking.

A: the standard legend on a google chart will not display multiple colors.
in fact, when using the style column role,
the legend will not match the colors used in the style columns in the data table.
instead, we can build a custom legend to display the multiple colors for each series.
to build the legend, we need to add a container to hold the legend entries.
we can use a
 element placed just below the chart.

we can use css to style the legend container and use the same width of the chart.
#legend_div {
  font-family: Arial;
  font-size: 11px;
  text-align: center;
  width: 920px;
}

in the following example, I extract the colors for each series from the data table.
using the values provided in the style column roles.
to create the legend content, I use the following html templates.
one for the legend entry itself...

and another for each color to be displayed for that series...

in this example, only two rows exist in the data table,
so two colors will be displayed for each legend entry.
the legend is built during the chart's 'ready' event,
so as soon as the chart is finished drawing,
the legend will be displayed.
during which, the colors are extracted from the data table and used to build the legend entries.
a click event is added for example purposes, in case there are actions you would like to take when a legend entry is clicked.
in this example, the chart series is selected to highlight which legend entry was clicked.

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ["","0 times (never)",{"role":"style"},"1 times",{"role":"style"},"2 times",{"role":"style"},"3 times or more",{"role":"style"}],
    ["A class",0.581,"#b4ddfd",0.109,"#84bfef",0.21,"#559ad2",0.1,"#4277a1"],
    ["nationality",0.481,"#ffddba",0.209,"#ffc384",0.25,"#ffac5b",0.06,"#fa993f"]
  ]);

  var options = {
    vAxis: {
      textStyle: {
        fontSize: 11
      },
      titleTextStyle: {
        italic: false
      }
    },
    chartArea: {
      width: '85%',
      top: 30,
      left: '13%'
    },
    bar: {
      groupWidth: '35%'
    },
    legend: {
      position: 'none'
    },
    isStacked: 'percent',
    hAxis: {
      ticks: [0, 1],
      textStyle: {
        fontSize: 13
      },
      minValue: 0,
      maxValue: 1
    },
    width: 920,
    height: '100%'
  };

  var chart = new google.visualization.BarChart(document.getElementById('chart_div'));

  // chart ready event
  google.visualization.events.addListener(chart, 'ready', function () {
    // legend container
    var legend = document.getElementById('legend_div');
    legend.innerHTML = '';

    // build legend from chart data
    var colorPallette = [];
    for (var colIndex = 0; colIndex < data.getNumberOfColumns(); colIndex++) {
      // determine if style column
      if (data.getColumnRole(colIndex) === 'style') {
        // save colors for entire series (all rows)
        var seriesColors = '';
        for (var rowIndex = 0; rowIndex < data.getNumberOfRows(); rowIndex++) {
          seriesColors += renderTemplate('template-legend-entry-color', {
            color: data.getValue(rowIndex, colIndex)
          });
        }

        // add legend for series (all colors)
        legend.insertAdjacentHTML('beforeEnd', renderTemplate('template-legend-entry', {
          colors: seriesColors,
          index: colIndex - 1,
          label: data.getColumnLabel(colIndex - 1)
        }));
      }
    }

    // add click event to legend entries
    var legendEntries = legend.getElementsByClassName('legend-entry');
    Array.prototype.forEach.call(legendEntries, function(entry) {
      entry.addEventListener('click', function (e) {
        // find legend entry
        var entry = e.target || e.srcElement;
        if (entry.className.toLowerCase() !== 'legend-entry') {
          entry = entry.parentNode;
        }

        // get data table column index from legend entry
        var columnIndex = parseInt(entry.getAttribute('data-columnIndex'));

        // display legend entry that was clicked
        document.getElementById('message_div').innerHTML = 'legend entry clicked = ' + data.getColumnLabel(columnIndex);

        // select chart series
        chart.setSelection([{row: null, column: columnIndex}]);
      }, false);
    });
  });

  // render html template
  function renderTemplate(templateId, templateProps) {
    var content = document.getElementById(templateId).innerHTML;
    for (var handle in templateProps) {
      if (templateProps.hasOwnProperty(handle)) {
        content = content.replace('{{' + handle + '}}', templateProps[handle]);
      }
    }
    return content.trim();
  }

  // draw chart
  chart.draw(data, options);
});
#legend_div {
  font-family: Arial;
  font-size: 11px;
  text-align: center;
  width: 920px;
}

.legend-entry {
  display: inline-block;
  padding: 16px 4px 8px 4px;
}

.legend-entry-color {
  display: inline-block;
  height: 12px;
  width: 12px;
}


text:
Q: Restrict global color transition on certain elements Hello I am using the global code for transition color
* {
    transition: color 0.6s ease 0s;
}

and I don't want it to be active on the hover state on the main menu tabs labeled HOME, MYTEAM, GAMEDAY, etc.
website
http://www51.myfantasyleague.com/2017/home/36888#0
When I add transition none, it doesn't work.
.myfantasyleague_tabmenu #homepagetabs li:hover {
    background-color: rgba(218, 54, 54, 0.7);
    box-shadow: none;transition:none;
}

I must not have the correct code to stop the transition color on the tabs, can you please help me there.
Thx

A: You should put the transition on the element and not in the hover..
.myfantasyleague_tabmenu #homepagetabs li{
   -webkit-transition-property: none;
-moz-transition-property: none;
-o-transition-property: none;
transition-property: none;
}

I suggest not using the * selector to set the transition... , because it will set to all the elements.. A better way would be applying in to a class an using it where is needed

A: You must put the transition: none to your li but not in the :hover state:
.myfantasyleague_tabmenu #homepagetabs li {
    /* other css*/
    transition: none;
}


text:
Q: Dijkstra's shortest path algorithm optimization I want to start by saying my code works as intended, and is reasonably fast. However profiling it, most of the time is spent on one very specific portion, which leads me to ask: is there any generally accepted better solution for this?
Here is my implementation:
            var cellDistance = new double[cells.Count];
            cellDistance.SetAll(idx => idx == startCellIndex ? 0 : double.PositiveInfinity);

            var visitedCells = new HashSet<int>();

            do
            {
                // current cell is the smallest unvisited tentative distance cell
                var currentCell = cells[cellDistance.Select((d, idx) => (d, idx)).OrderBy(x => x.d).First(x => !visitedCells.Contains(cells[x.idx].Index)).idx];

                foreach (var neighbourCell in currentCell.Neighbours)
                    if (!visitedCells.Contains(neighbourCell.Index))
                    {
                        var distanceThroughCurrentCell = cellDistance[currentCell.Index] + neighbourCell.Value;
                        if (cellDistance[neighbourCell.Index] > distanceThroughCurrentCell)
                        {
                            cellDistance[neighbourCell.Index] = distanceThroughCurrentCell;
                            prevCell[neighbourCell] = currentCell;
                        }
                    }

                visitedCells.Add(currentCell.Index);
            } while (visitedCells.Count != cells.Count && !visitedCells.Contains(endCell.Index));

Most of the time is spent on this line, which takes the unvisited node with the lowest partial cost:
var currentCell = cells[cellDistance.Select((d, idx) => (d, idx)).OrderBy(x => x.d).First(x => !visitedCells.Contains(cells[x.idx].Index)).idx];

And more specifically, in the last lambda, not the sort (which I found very surprising):
x => !visitedCells.Contains(cells[x.idx].Index)

Since visitedCells is already a HashSet, there isn't much I can improve with just the built-in data structures, so my question is: is there a different way of storing the partial costs that make this specific query (ie, the unvisited node with the lowest partial cost) noticeably faster?
I was considering some kind of sorted dictionary, but that I'd need one that sorts by value, because if it's sorted by key I'd have to make the partial cost the key, which makes updating it costly and then poses the problem as to how I map this structure to my cost array, and this still doesn't solve my visitedCells lookup.

A: Using an array of flags instead of HashSet
HashSet can have amortized insertion time and expected query time of O(1). However, since your node ids are simply indices into an array, they are sequential and they don't grow much. Also, you will eventually have all ids in the HashSet. In this case, you have faster O(1) options than using "any" generic hash table. You can use  an array of booleans that show if a node was visited, and index into it using node ids.
Simply allocate a boolean array with size equal to node count. Fill it with false. Set the value at node id to true when you visit a new node.
Iterating over all nodes instead of sorting them for selecting the next node
Your current code has to sort all nodes with respect to their distances, and then go through them one by one to find the first non-visited one. This takes θ(nlogn) time in most cases due to sorting. (An optimization could be made to partially-sort the nodes, but it would be very surprising if a compiler/library could see that opportunity by itself.) Your total time complexity becomes θ(n^2 * logn) with this approach. Instead, you can go through the nodes once, keeping track of the minimum-distance non-visited node seen so far. This works in θ(n). Total time complexity is O(n^2), as Dijkstra should be.
With these two changes, your code will not have much left that is unneeded for Dijkstra's shortest path.

I was considering some kind of sorted dictionary, but that I'd need
one that sorts by value, because if it's sorted by key I'd have to
make the partial cost the key, which makes updating it costly and then
poses the problem as to how I map this structure to my cost array

There is a data structure called min-heap that can be used to extract the minimum value from a set (along with its satellite data). A simple binary min-heap can extract the minimum key or decrease some key it holds in θ(logn) worst-case time.
In the case of Dijkstra, you need to have a sparse graph for this to be more efficient than iterating over all distances (sparse graph ≈ number of edges is much less than number of nodes squared). Because the algorithm may need to decrease a distance each time it relaxes an edge.
If there are θ(n^2) edges, this makes the worst-case total time complexity θ(n^2 * logn).
If there are θ(n^2 / logn) edges, time taken in relaxations becomes O(n^2). Then, you need a more sparse graph than this one, for a binary heap to be more efficient than using a simple array.
In the worst case, extracting all minimum-distance nodes from the heap takes θ(nlogn) time, relaxing all edges takes θ(e * logn) time, where e is edge count, and total time is θ((n+e)logn). As I said, this can be more efficient than θ(n^2) only if e is asymptotically smaller than n^2 / logn.


text:
Q: Azure monitoring: MetricsAlert vs AlertRules, can't see AlertRules in Monitor I have an ARM template with these two monitoring types:

*

*Microsoft.Insights/alertrules

*microsoft.insights/metricAlerts

The Microsoft.Insights/alertrules looks like this:
{
  "apiVersion": "2014-04-01",
  "name": "[concat('CPUHigh ', parameters('hostingPlanName'))]",
  "type": "Microsoft.Insights/alertrules",
  "location": "[resourceGroup().location]",
  "dependsOn": [
    "[resourceId('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
  ],
  "tags": {
    "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
    "displayName": "CPUHighAlertRule"
  },
  "properties": {
    "name": "[concat('CPUHigh ', parameters('hostingPlanName'))]",
    "description": "[concat('The average CPU is high across all the instances of ', parameters('hostingPlanName'))]",
    "isEnabled": true,
    "condition": {
      "odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
      "dataSource": {
        "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
        "resourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
        "metricName": "CpuPercentage"
      },
      "operator": "GreaterThan",
      "threshold": 90,
      "windowSize": "PT15M"
    },
    "action": {
      "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
      "sendToServiceOwners": true,
      "customEmails": []
    }
  }
}

And the microsoft.insights/metricAlerts looks like this
   {
      "type": "microsoft.insights/metricAlerts",
      "apiVersion": "2018-03-01",
      "name": "CreatedThisFromARM",
      "location": "global",
      "properties": {
        "description": "Created this from ARM. Does it show up or not?",
        "severity": 3,
        "enabled": true,
        "scopes": [
          "/subscriptions/4ec6f523-de5f-4e8a-a6e7-45e4f53170df/resourceGroups/AzureResourceGroup4/providers/Microsoft.Web/serverFarms/plantestmonitor"
        ],
        "evaluationFrequency": "PT1M",
        "windowSize": "PT5M",
        "criteria": {
          "allOf": [
            {
              "criterionType": "StaticThresholdCriterion",
              "name": "MemoryFromARM",
              "metricName": "MemoryPercentage",
              "dimensions": [],
              "operator": "GreaterThan",
              "threshold": 90,
              "timeAggregation": "Average"
            }
          ],
          "odata.type": "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria"
        },
        "actions": []
      }
    }

When I enter my monitor tab I can see microsoft.insights/metricAlerts but not the Microsoft.Insights/alertrules. I would expect to see both. If I go to the Insights (preview) tab under the Monitoring menu of the resource group, I can see both.
I am wrong in my opinion that i should see both types under the Monitor --> Alerts? Or?
Maybe I am not understanding the difference between the two clearly enough (and my google foo hasn't been able to bring me to some doc that describe it for me). Maybe I am misunderstanding the two concepts?

A: After a while the alertRule is appearing in the classic alerts section that is referred to when entering "Alerts" in monitor. So I can see both from the Monitor. You just have to wait a bit.
As I can see the "Alerts(Classic) will be retired on August 31st. Use the voluntary migration tool to upgrade to the faster, simpler, and more scalable metric alerts platform", so the classic alerts must be Microsoft.Insights/alertrules. So metricAlerts is the future of Azure monitoring. Please correct me if I am wrong.


text:
Q: Calculate Metrics for Keras CNN model I have a CNN model that recognize the human postures in total 4 postures, I would to test the performance of my model by calculating the metrics recall, precision, fmeasure, accuracy. the accuracy is calculated by default in Keras library, but the other one I need to implement them. I found the source code to calculate these metrics but I think the is for binary classification :
def precision(y_true, y_pred):

true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision

def recall(y_true, y_pred):

true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall

def f1(y_true, y_pred):

def recall(y_true, y_pred):

    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
    recall = true_positives / (possible_positives + K.epsilon())
    return recall

def precision(y_true, y_pred):

    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    return precision
precision = precision(y_true, y_pred)
recall = recall(y_true, y_pred)
return 2*((precision*recall)/(precision+recall+K.epsilon()))

model.compile(loss='binary_crossentropy',
          optimizer= "adam",
          metrics=[mcor,recall, f1])

I think this is for binary classification only, so please I need your help, if I can't use this for multi-label classification, what is the method that I can use ?

A: as your final output can have 4 labels. in the model.compile part change
loss='binary_crossentropy'   to   loss='categorical_crossentropy'
and in the last layer of your neural network architecture change the activation function to 'softmax'' also the number of output neurons should be changed.
other changes like your input shape will depend upon the data you are giving to the model.
refer to this blog to know more about CNN.
https://towardsdatascience.com/convolutional-neural-networks-for-beginners-practical-guide-with-python-and-keras-dc688ea90dca
refer to this blog to know more about How to Calculate Precision, Recall, F1, and More for Deep Learning Models
https://machinelearningmastery.com/how-to-calculate-precision-recall-f1-and-more-for-deep-learning-models/


text:
Q: Python error when renaming files in windows I am attempting to give all the jpg files in a folder a random name, so they appear in semi random order on my digital picture frame
This is the code I'm trying to use:
import os
import random

for filename in os.listdir("."):
    hold = random.randint(1,100000)
    f=str(hold)+'.jpg'

    if(filename.endswith('.jpg') or (filename.endswith('.JPG'))):
        os.rename(filename,f)

However when I run it I get:
WindowsError: [Error 82] The directory or file cannot be created.

Everything I've seen makes it look like my code should work, I don't know why it won't run.
EDIT: It seems like its due to the fact that there are spaces in the name of the file I'm trying to rename
EDIT2:I was copying the files to an SD card formatted as FAT and the folder I was running it in had the maximum number of items in it. I solved it by moving a couple of the files to a subdirectory.

A: Probably your rename is failing. Try adding some debug print to your code and see, when exactly it is failing. Before renaming add print 'Renaming %s to %s' % (filename, f) and see, when the rename fails.

A: The problem as far as I can see it is that the variable filename isn't an actual file, but a string. os.listdir() returns a list of strings that are the filenames in that folder. You need to use open("w", filename) to open the file and then rename it and then save it.

A: Taking a look at the documentation for os.rename(), in Windows, it will raise OSError if the file you're trying to rename it to already exists (as there's no way to implement an atomic rename on the OS).  That is to say, if the file you're renaming your JPEG to is already present in the directory, os.rename will fail on Windows.
It could be the case that you're attempting to rename a file in your current directory to another file that already exists.  You would have to add code to check against that, which isn't too difficult:
filelist = os.listdir('.')
for filename in filelist:
    hold = random.randint(1,100000)
    f=str(hold)+'.jpg'

 if filename.lower().endswith('.jpg') and f not in filelist:
    os.rename(filename,f)

A: I was copying the files to an SD card formatted as FAT and the folder I was running it in had the maximum number of items in it. I solved it by moving a couple of the files to a subdirectory.


text:
Q: How does LINQ's left-join `join ... into` and `DefaultIfEmpty()` work? How does LINQ's join ... into and .DefaultIfEmpty() work to express a left-join?
Does .DefaultIfEmpty() get evaluated just once, or n times?

A: Assuming we're talking about LINQ to Objects, DefaultIfEmpty will be evaluated once per element in the result. It will be evaluated on the sequence which is the group of values matching the "left" part of the join. So if we have:
from x in foo
join y in bar into z
let g = z.DefaultIfEmpty()
select new { x, g.Count() }

then for each x value, there will be an invocation of DefaultIfEmpty. For non-empty sequences, that will just pass values through. For empty sequences, the default value is returned (once) instead.
See my Edulinq blog post on it for more information.


text:
Q: JPA self-reference OneToMany mapping with extra fields I have a Phone and a Phone4Phone_Map tables, the second table set up rules so when a phone is broken it can be changed for another similar phone.
Phone:
------
idPhone INT(11) PK
name VARCHAR()
model VARCHAR()
price LONG

Phone4Phone_Map:
----------------
idPhone_in INT(11) PK
idPhone_out INT(11) PK
valid_since TIMESTAMP
reason VARCHAR()

I'm having a hard time to understand how to do the mappings. I was wondering if a @OneToMany self-reference on Phone would just do fine, but I don't know how to include the extra fields from Phone4Phone_Map (valid_since and reason), this is me thinking of not mapping the second table which I don't know if it's even possible.

A: If Phone has a list of Phone4Phone_Map
You could do the following
The class Phone would have many Phone4Phone_Map objects
class Phone{
    private Integer idPhone;
    private String name;
    private String model;
    private Long price;

    @OneToMany(mappedBY="phone")
    private List<Phone4Phone_Map> phone4Phone_Map;

    //Getters/Setters
}

and every instance of the class Phone4Phone_Map would reference a phone
If the foreign_key in Phone4Phone_Map is the idPhone_out (the broken phone) the mapping would be:
class Phone4Phone_Map{

    private Integer idPhone_in
    private Integer idPhone_out
    private Date valid_since
    private String reason

    @ManyToOne
    @JoinColumn(name="idPhone_out")
    private Phone phone;

    //Getters/Setters
}

NOTE that both classes considered @Entity
The field types/names is just for example and you can change them. I avoid other necessary annotations (e.g. @Id) to keep the example simple.
With that structure your tables would be
Phone:
------
idPhone INT(11) PK
name VARCHAR()
model VARCHAR()
price LONG

and
Phone4Phone_Map:
----------------
idPhone_in INT(11) PK
idPhone_out INT(11) PK
valid_since TIMESTAMP
reason VARCHAR()
idPhone_out FK references Phone(idPhone)


text:
Q: Solve returns format I don't understand with dollar sign ($) I have the following function
K[theta_, phi_] := Module[{c1, c2, c3, Phi, PhiPr, x, y},
  {c1, c2, c3} =
   1 - 3 Sin[theta]^2 Cos[phi - 2 Pi (# - 1)/3]^2 & /@ {1, 2, 3};
  Phi = Sqrt[((c2 + c3)^2 - c1^2)/(4 c2 c3)];
  PhiPr = ((c3 - c2)/c1) Phi;
  If[0 <= Phi^2 <= 1,
   {x, y} /.
    Solve[Sin[Sqrt[3] x/2] == Phi &&
      Sin[3 y/2] ==
       PhiPr && (c2 + c3) Cos[Sqrt[3] x/2] == -c1 Cos[3 y/2] && -Pi <=
        x <= Pi && -Pi <= y <= Pi, {x, y}]
   , Null]
  ]

Sometimes it behaves itself and returns me either a Null (as desired) or an actual number. However sometimes it is a naughty function and returns something strange. For example if I compute K[0.1,0] it returns me {x$17889, y$17889}.
What is this output? I don't understand. Many thanks

A: You can identify the problem by performing the steps in your function one at a time for theta = .1 and phi = 0..
{c1, c2, c3} = 1 - 3 Sin[0.1]^2 Cos[0 - 2 Pi (# - 1)/3]^2 & /@ {1, 2, 3}
{* {0.9701, 0.992525, 0.992525} *}

Phi = Sqrt[((c2 + c3)^2 - c1^2)/(4 c2 c3)]
{* 0.87245 *}

PhiPr = ((c3 - c2)/c1) Phi
{* 0. *}

Because 0 <= Phi^2 <= 1 is True, the Solve is executed:
{x, y} /. Solve[Sin[Sqrt[3] x/2] == Phi && Sin[3 y/2] ==
    PhiPr && (c2 + c3) Cos[Sqrt[3] x/2] == -c1 Cos[3 y/2] && -Pi <= x <= Pi && -Pi <= y <= Pi,
    {x, y}]

returning the error message Solve::ratnz and {x, y} instead of an answer.  Returning now to your original function, a Module, x and y are temporary variables, which have names beginning with $, which is what you are getting.
Addendum
Replace the If statement in the Module by
If[0 <= Phi^2 <= 1, Check[{x, y} /. Solve[Sin[Sqrt[3] x/2] == Phi &&
  Sin[3 y/2] == PhiPr && (c2 + c3) Cos[Sqrt[3] x/2] == -c1 Cos[3 y/2] && -Pi <= x <= Pi &&
  -Pi <= y <= Pi, {x, y}], Null], Null]]

to obtain a Null response is such cases.


text:
Q: Sharing rules on Community Users I need to create a Account and have a lookup from account to Account as (Partner). Lookup will determine if related Account, related Contacts and Opportunities are visible to these Partner Community Users. I have to create Sharing Rules that enable Partner Account Contacts (as Community Users) to access their related Account and Contact's records.
Please guide me how to create a Sharing rule for this scenario.

A: Quick caveat to my answer, there could be a way to accomplish this with sharing sets but I don't have enough knowledge of that particular feature to say one way or another. The best way I would go about accomplishing this is by managing sharing with apex. You would need a trigger on account and user that calls a helper class that has method to accept both a list of users and list of accounts passed in from the trigger.
The user method, needed only on insert, would find all child accounts associated with the user's community account and insert a sharing row for each.
The account method is trickier, as it would need to operate in all contexts (update, delete, insert, etc.). This method would need to fire when the parent account is not null (and on update probably be isolated to only when the parent account changes), and you would then find all users associated with the parent account and grant access to the account, contacts, etc. being listed as a new child. This is a relatively complex trigger, as you will need to make it bulk safe, which will require a few maps in your apex method(s). You'll also want to make sure to clean up and delete sharing rows when a parent/child relationship is changed or severed.


text:
Q: Using EF Core with ASP.NET Core MVC and Sqlite - proper class structure I'm relatively new to programming and I have some questions. I'm currently simultaneously trying to learn ASP.NET MVC from the official Microsoft book because I'm looking to get the certification in a few months and at the same time working on a small project for a colleague. Instead of doing things with .net framework i decided to just do everything in .net core and there are some discrepancies between what I learned in the book and what seems to be available in EF Core.
I'm using Sqlite for my database and I've already plugged that in for the most part but I'm running into some issues where various people on the internet are providing me with conflicting information.
So in the .net framework version of ASP.NET, the way Microsoft said you should do things is, You have a Model PersonModel and a context PersonContext that goes in the Model file and inherits DbContext. This PersonContext contains various DbSet<T> objects depending on which tables you want to make etc. This has remained the same for me in .net core. However after this Microsoft tells me to make a PersonInitializer which is supposed to inherit DropCreateDatabaseAlways<PersonContext> and then override the Seed method (conveniently thats also where a getFileBytes method is placed for images etc).
Now, in core, there is no DropCreateDatabaseAlways class to inherit, leading me to believe this structure is actually not intended at all by .net core. I've heard various things on here about using various CLI commands but in the end I'm basically just very confused about what the "proper" thing to do is here?

A: It think your largest problem at this point is just sourcing information properly. Admittedly, it's a bit confusing, especially for someone completely new on the scene.
A little background to start: there's ASP.NET, ASP.NET MVC, and ASP.NET Core. ASP.NET is really nothing, although it became short hand for ASP.NET Web Forms, as that was the only thing you had to work with at the time. Then, Microsoft introduced ASP.NET MVC, which took the foundation of ASP.NET and layered on an attempt at a modern web application framework modeled after the MVC (model-view-controller) pattern. It was a vast improvement over Web Forms, but did not fundamentally break away from the older system enough to make it a truly great application development framework. Because of it's reliance on System.Web (a monolithic family of DLLs) and the full .NET Framework, it was slow, hard to deploy and completely incompatible with things like containerization. Enter ASP.NET Core, which was a complete rewrite from the ground up.
ASP.NET MVC had a sister framework in ASP.NET Web Api, and technically you could still employ ASP.NET Web Forms in the same project. In fact, a single project could utilize all three frameworks at once, which is as convoluted as it sounds. ASP.NET Core, at least initially, did away with this confusion by just having a single system for both traditional web applications and APIs. As such, if you're looking for information about Core, it's just "Core". Looking for ASP.NET Core MVC is just going to lead you to outdated information.
That said, frustratingly, Microsoft decided in their infinite wisdom that Web Forms, though reviled by most every developer who had ever used a real web application framework, were actually so awesome that they should be resurrected, at least in spirit. Thus was born Razor Pages, and ever since it's been necessary to make a distinction between ASP.NET Core Razor Pages and ASP.NET Core Proper, which has now been relabeled as ASP.NET Core MVC, making it that much more difficult for people to filter out information on one framework versus another. At least for the time being, Razor Pages are still not as prominent as the MVC-style, and thankfully, they at least don't change much in the core functionality of Core to warrant differing discussions on most things. Long and short, you should pretty much just prefix every search with "asp.net core" (in quotes, so it's done as a phrase search). That will generally always give you relevant information - for the most part.
The next set of issues is that ASP.NET Core was developed with high visibility, fully out in the open and with many, many previews, alphas, betas, and even full releases. On the one hand, that's great and is a large part of why it's as good as it is. Developers were able to provide input and steer the development, making it the first web application framework developed by Microsoft actually designed by and for the people actually in the trenches, building web applications.
The downside, though, is that things changed - a lot - and still do. Though, it now seems to be leveling off pretty well after 2.1, which I consider to be pretty much the first truly feature complete release. However, before we got here, we had ASP.NET vNext, ASP.NET MVC 6, DNX, and then ASP.NET Core 1.0, 1.1, 2.0, and finally 2.1 - all of which fundamentally changed at least how some things work. In other words, even if you confine your searches to ASP.NET Core, there's still a lot of outdated and incorrect information out there, simply because it was written about a previous version and things have changed since. To better your odds, you should consider confining your search to things published within the last year (2018+, 2017 if you can't find anything newer). Any older than that, and you're going to have to take the article with a big, huge grain of salt.
And then that brings us to Entity Framework. Oh my. EF has had a storied history, most of it steeped in failure. The original EF wasn't even viable until version 3. The previous versions were so bad they were literally unusable for any serious production work. Even then, it wasn't until EF 4 that it could really even be consider truly ready for prime time, and finally began having some significant uptake among developers as a result. It was also the release where Code First was finally introduced (technically in 4.1).
Before that time there was what the EF team referred to as Database First or Model First. The only meaningful difference was that one would generate your models from an existing database, while the other would let you design your models and then generate a database from that. In either case, you ended up with a monstrosity called EDMX, an XML beast that attempted to keep up with your database state and all the translation of VB/C# classes to that entails. It was an absolutely nightmare to maintain, almost never worked correctly, and a constant source of frustration.
Code First provided an alternative - a shining light in the darkened pit of EDMX hell. You could use POCOs (plain old class objects) and EF would be able to generate migrations from changes you made to those to update your database accordingly. It could even be used to work with existing databases, though it's name prevented it from being used as much as it should have been in that area (many people wrongly believe that if you had an existing database, you had to continue using the old horrible Database First methodology). In truth, Code First was a complete alternative approach to managing databases, both new and existing. EF 5 and EF 6 continued to refine this new approach, and when it came time to work on EF 7, Microsoft decided it was high time EDMX went to its well-deserved grave.
However, work on EF 7 coincided with the development of ASP.NET Core, which itself spawned off .NET Core and eventually .NET Standard. EF was firmly rooted on the full .NET Framework, so it became apparent that a rewrite was in order. As such, development of EF 7 was cancelled, and EF Core was born. EF Core, though, had a rough ride. ASP.NET Core was moving along like a freight-train, but had no native way to interact with databases. You could use old EF, but then you were forced to target the full .NET Framework, instead of .NET Core. As such, EF Core was rushed to release way too soon, and 1.0 was a train-wreck of epic proportions. There was so much basic functionality missing and the workarounds were so obtuse that virtually no one in their right mind actually would take anything into production with it. Then, 1.1 was release and things improved somewhat but still not enough. Then came 2.0, and finally, it was workable ORM, you could actually feel comfortable using in production. The release of 2.1 has brought even more improvements and refinements.
Now that you've had your history lesson, all I can say is that finding good documentation is still unfortunately a bit of a crap-shoot. You need to be very specific with your searches, using the right terms (which is part of why I wanted to give you the history). You also need to pay close attention to dates. Consider suspect anything that existed before 2017 and treat even stuff from that year with a grain of salt. The official docs are your best friend. Microsoft has actually done a pretty fantastic job with their documentation and keeping it up to date and accurate. It covers the largest majority of things is the ultimate source of truth.

*

*Official ASP.NET Core Docs

*Official EF Core Docs
Books are not going to be your friend here. The publication process takes far too long and ASP.NET Core has moved far too fast. Any book on Core is outdated the minute it hits the streets. However, if you have a subscription to Safari Books, you might have luck due to their prelease and alpha offerings there. You have to deal with more technical mistakes, grammatical errors, etc., but at least the information will be closer to the actual truth.
Pluralsight has some truly excellent videos that can help you. Unfortunately, video production has a similar problem as book publication, and there's more than few courses that are now so outdated as to be useless.
Hope this at least gives you some better context and helps improve your ability to source good and accurate information. Honestly, I still struggle myself with that a lot of times, and I think most developers working in this space has the same issue. It's fun and exciting, but it's not without its cons. Having to wade through a sea of information to find some pearls is one of them. Good luck.