text:
Q: Clojure.spec - Why is it useful and when is it used I have recently watched Rich Hickeys talk at Cojure Conj 2016 and although it was very interesting, I didn't really understand the point in clojure.spec or when you'd use it. It seemed like most of the ideas, such as conform, valid etc, had similar functions in Clojure already.
I have only been learning clojure for around 3 months now so maybe this is due to lack of programming/Clojure experience.
Do clojure.spec and cljs.spec work in similar ways to Clojure and Cljs in that, although they are not 100% the same, they are based on the same underlying principles.

A: *

*Are you tired of documenting your programs?

*Does the prospect of making up yet more tests cause procrastination?

*When the boss says "test coverage", do you cower with fear?

*Do you forget what your data names mean?

For smooth expression of hard specifications, you need Clojure.Spec!

Clojure.spec gives you a uniform method of documenting,  specifying, and automatically testing your programs, and of validating your live data.
It steals virtually every one of its ideas. And it does nothing you can't do for yourself.
But in my - barely informed - opinion, it changes the economy of specification, making it worth while doing properly. A game-changer? - quite possibly.

A: At the clojure/conj conference last week, probably half of the presentations featured spec in some way, and it's not even out of alpha yet.  spec is a major feature of clojure; it is here to stay, and it is powerful.
As an example of its power, take static type checking, hailed as a kind of safety net by so many, and a defining characteristic of so many programming languages.  It is incredibly limited in that it's only good at compile time, and it only checks types.  spec, on the other hand, validates and conforms any predicate (not just type) for the args, the return, and can also validate relationships between the two.  All of this is external to the function's code, separating the logic of the function from being commingled with validation and documentation about the code.
Regarding WORKFLOW:
One archetypal example of the benefits of relationship-checking, versus only type-checking, is a function which computes the substring of a string.  Type checking ensures that in (subs s start end) the s is a string and start and end are integers.  However, additional checking must be done within the function to ensure that start and end are positive integers, that end is greater than start, and that the resulting substring is no larger than the original string.  All of these things can be spec'd out, for example (forgive me if some of this is a bit redundant or maybe even inaccurate):
(s/fdef clojure.core/subs

        :args (s/and (s/cat :s string? :start nat-int? :end (s/? nat-int?))
                     (fn [{:keys [s start end]}]
                       (if end
                         (<= 0 start end (count s))
                         (<= 0 start (count s)))))

        :ret string?

        :fn (fn [{{:keys [s start end]} :args, substring :ret}]
              (and (if end
                     (= (- end start) (count substring))
                     (= (- (count s) start) (count substring)))
                   (<= (count substring) (count s)))))

Call the function with sample data meeting the above args spec:
(s/exercise-fn `subs)

Or run 1000 tests (this may fail a few times, but keep running and it will work--this is due to the built-in generator not being able to satisfy the second part of the :args predicate; a custom generator can be written if needed):
(stest/check `subs)

Or, want to see if your app makes calls to subs that are invalid while it's running in real time?  Just run this, and you'll get a spec exception if the function is called and the specs are not met:
(stest/instrument `subs)

We have not integrated this into our work flow yet, and can't in production since it's still alpha, but the first goal is to write specs.  I'm putting them in the same namespace but in separate files currently.
I foresee our work flow being to run the tests for spec'd functions using this (found in the clojure spec guide):
(-> (stest/enumerate-namespace 'user) stest/check)

Then, it would be advantageous to turn on instrumenting for all functions, and run the app under load as we normally would test it, and ensure that "real world" data works.
You can also use s/conform to destructure complex data in functions themselves, or use s/valid as pre- and post- conditions for running functions.  I'm not too keen on this, as it's overhead in a production system, but it is a possibility.
The sky's the limit, and we've just scratched the surface!  Cool things coming in the next months and years with spec!


text:
Q: ajax function is not returning expected output controller is returning :
return Json(new { html = "HELLO" },JsonRequestBehavior.AllowGet);

which is simply a string 'HELLO'
my json function is as follows :
function callPrint() {
        var PrintCssContent = "";

        $.ajax({
            url: '@Url.Action("GetHtmlString", "Itinerary", new { area = "Travel" })',
            dataType: "text",
            success: function (data) {
                alert(data);

                WinPrint.document.write(data);
                WinPrint.document.write(DivMainContent.innerHTML.toString());
                WinPrint.document.write("");
                WinPrint.document.close();
                WinPrint.focus();
                WinPrint.print();
                WinPrint.close();
            },
            error:function(){
                alert('error');
            }
        });
        return false;
    }

but json alert is returning something like this :
{"html":"\u003chtml\u003e\u003cbody\u003eHELLO\u003c/body\u003e\u003c/html\u003e"}
how to simply return 'HELLO' using my json function?

A: You need to use JSON.Parse to return the JSON data. Change your alert statement as,
 var parseData = JSON.parse(data);
 alert(parseData.html);

Hope this helps!.

A: You need to convert the result to json, then print it out, here is the code:
function callPrint() {
    var PrintCssContent = "";

    $.ajax({
        url: '@Url.Action("GetHtmlString", "Itinerary", new { area = "Travel" })',
        dataType: "text",
        success: function (data) {
            var dataParsed = JSON.parse(data);
            WinPrint.document.write("");
            WinPrint.document.write(dataParsed.html);
            // WinPrint.document.write(DivMainContent.innerHTML.toString());
            WinPrint.document.write("");
            WinPrint.document.close();
            WinPrint.focus();
            WinPrint.print();
            WinPrint.close();
        },
        error:function(){
            alert('error');
        }
    });
    return false;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Order the numbers of each row I have a formula =SMALL(RIGHT($A3:$f3,1),{1,2,3,4,5,6}) and it works fine to extract one digit from the data.
Now I have a different set of data but I couldn't make it work with these data.
The data I have is like this:
L18 L2  R3  R19 R21 R22
L23 L12 L15 L17 L2  R13
L11 L17 L2  R2  R9  R24
L22 L5  L9  R9  R24 R27

With the function, I should be able to get these results:
2   3   18  19  21  22
2   12  13  15  17  23
2   2   9   11  17  24
5   9   9   22  24  27

So they have one letter and 1 or 2 digit numbers at the end. For each row, I would like to extract the digits and arrange them from smallest to largest. How can I do that?

A: Try this:
=SMALL(--MID($A1:$F1,2,255),{1,2,3,4,5,6})

Given your initial formula I presume you know that this is an array formula and needs to be entered using Ctrl+Shift+Enter

A: you can do this in two Phase
As given below
=VALUE(MID(A2,LEN(LEFT(A2,1))+1,LEN(A2)-1))
=SMALL($A8:$F8,1)


text:
Q: Loading NuGet packages online and pre-install them I know that I can pre-install NuGet packages in my project templates.
But I wasn't able to find out whether it is possible to load these packages online instead of having to store them somewhere in the project template.
If this is possible please give me a hint where I can find an example.

A: Older article, but answers the question:
http://blogs.msdn.com/b/marcinon/archive/2011/07/08/project-templates-and-preinstalled-nuget-packages.aspx

A frequent question is why not support downloading the nupkg files directly from http://nuget.org. We decided not to support such an option because users expect project templates to instantiate quickly and downloading files from the internet would slow things down. Also, it would not work on a plane or in other situations where a connection is not available.


text:
Q: How to create a unique name in a dataframe for similar strings? This is my current dataset.
persons<- c("James", "Michael", "Michael", "Robert", "Richard", "Harry", "Harry", "Ben", "Michael", "Harry")

Since the names here are common. I want to make every name unique.
To do this I used this set of code:
unique<- function(vec)
{
  sub('[.]',':',make.names(persons,unique = TRUE))
}
Strings<- unique(vec)

I got my desired output. But I want to have the same kind of result by using strsplit() and paste() function. Also I want to use collapse parameter of paste function.
My desired output:
James
Michael
Michael:1
Robert
Richard
Harry
Harry:1
Ben
Michael:2
Harry:2

A: This will accomplish the task:
sapply( strsplit( make.names(persons, unique = TRUE), split="[.]") , paste, collapse=":")

[1] "James"     "Michael"   "Michael:1" "Robert"    "Richard"   "Harry"
 [7] "Harry:1"   "Ben"       "Michael:2" "Harry:2"

The "tricks" are a) recognizing that using split="." inside strsplit will fail because the period is a regex wildcard, and b) learning to use the collapse parameter for paste to ligate items in a list item..


text:
Q: Why is my variable invisible to the debugger in an action method? I have the weirdest problem. For a quick test of instantiating my role provider, I run the following modified action method:
public ActionResult Login()
{
    Educ8RoleProvider p = new Educ8RoleProvider();
    var model = new LoginModel();
    return View(model);
}

The role provider looks more or less like this:
public class Educ8RoleProvider : RoleProvider, IDisposable
{
    private readonly IMemberRoleRepository _memberRoleRepository = new MemberRoleRepository();

    public Educ8RoleProvider()
    {
    }
}

The code in Login executes without any exceptions, but when I put a break point on the line var model = new LoginModel();, variable p has vanished. I get the same error trying to place a quickwatch on p as I do trying to inspect it in the immediate window:
The name 'p' does not exist in the current context

This morning I upgraded from VS11 Beta top VS2012 RC. I don't know if this might be due to a new setting somewhere or something.
ADDED: I found I had somehow strayed off my Debug config onto a release based one.

A: My guess is that it's been optimized away - after all, you're not using it for anything.
I'd expect it to be okay on a debug build, but gone for an optimized build. (The constructor should still be called, of course.)
I question whether you should have it at all if you're not going to use it, mind you - it's at least a code smell.
If this is really for a "quick test of instantiating [your] role provider" might I recommend unit tests instead? :)

A: Weird.  Only thing that springs to mind is that maybe VS2012 knocks variables out of scope the last time they are referenced.  Have you tried putting in a line to access p after and see if it lets you watch it then?


text:
Q: Automatically Running a Program Without Task Scheduler I have a small program that needs to be run without use of the Task Scheduler. It uses the QBFC API from Intuit, which demands to be run "within the context of a user." The program sweeps some data from a SQL server running on the same machine and pushes it into QuickBooks. Thus, the program needs to run every half-hour or so and requires no user interaction. The machine is running Windows Server 2008 R2.
If I manually run the program, it works as expected. Attempts to use the Task Scheduler have resulted in the program crashing when it attempts to connect to QuickBooks.

A:
I am guessing you want the application to start when the user logs into their profile? If you want the program to automatically start, in any other case, that would require a scheduled task.

actually, you can also just place it in startup. I placed it in startup in the registry (currentversion=>run) and I can confirm it works.
now to answer OP's actual question, I believe I found the answer to the question-> not necessarily a solution to reach the goal.

QB and QBXML SDK applications have to run in the context of a user.You will have to have a Windows session open, but the user does not have to be logged in to QB for your application to run against it. However, QB will have to be opened by an admin the first time your application makes the connection and you authorize unattended mode.

intuit.developer

Windows Scheduler has changed from Desktop base to Service based from Vista or Win7 onwards, and the new OS has the Scheduler as
  Service based.
QuickBooks and QODBC are desktop based application/driver.
QODBC uses QuickBooks SDK, and QuickBooks SDK uses QuickBooks
  Application to get data from company file.
QuickBooks SDK requires an active desktop session (someone to is
  logged in) to the machine because QuickBooks is a desktop-based
  application. If no one logged on the server/machine, you will get the
  error "Could not start QuickBooks".
Even if you have specified the username/password and have a user
  logged into the machine, you may notice the same error.  This is
  because task executed from Task Scheduler runs as a different user /
  new session.
The workaround is to use a Desktop Based Scheduler like Z-Cron or http://alternativeto.net/software/task-scheduler/?platform=windows.

source of quoted text
now this may not be the solution you want. but it does answer your question/problem and includes a workaround.
i am also facing the same dilemma and am looking for a solution. this may have to be the way i go. another option is to kick off your console application on any user login, and keep track of your last successful run, current application status (whether its currently running or not) - so you ensure you run within your specified schedule. but not only is it a relatively messy solution, you do not necessarily have a guarantee someone will login during your required time allotment (they may not even login for a week).
i tried to kick off a remote session, which causes the app to run from startup, from another server using task scheduler. but that gave me the exact same result.
im currently looking into QBWC, to see if either of those approaches would allow me to achieve the desired goal of communication with QB on a scheduled bases autonomously.
i regret that I could not provide a definitive solution for you, but I think you and others can gain from the research ive already done so far. Additionally I hope this information helps you find the right solution.


text:
Q: How to open a new Tkinter window in a while loop? How do I make a new Tkinter window in a while loop?
Tkinter is kind of new to me, so I would like some easy explanations. I would like it to open a Tkinter window in a while loop. Basically, a user says yes to a question, then a new window pops up, and it will ask the question again, and it should pop up again etc...
I have some "code" that would basically say what I mean. All of the other questions out there did not really work for me.
im stupid and didnt include code
#import modules
import time
import sys
from tkinter import *
from tkinter import ttk
from playsound import playsound
from threading import Thread

win = Tk()

win.geometry("900x350")

def lift_window():
   win.lift()
   win.after(1000, lift_window)

def sound_play():
    playsound('a sound')

while True:
   start = input("make new window? (y/n): ")
   if start == "y":
      Label(win, text="new window!", font=('Aerial 16 italic')).place(x=5, y=140)

      Thread(target = lift_window).start()
      Thread(target = sound_play).start()

      lift_window()
      win.mainloop()
   elif start == "n":
      print("ok")
      sys.exit()

Some error messages I get were
_tkinter.TclError: can't invoke "label" command: application has been destroyed

But that is all.

A: The error message is worded rather poorly. The "application" it speaks of is just the Tk instance that win points to. It's destroyed when you close the window, so you need to make a new one each time through the loop.
while True:
    start = input("make new window? (y/n): ")
    if start == "y":
        win = Tk()
        win.geometry("900x350")
        Label(win, text="new window!", font=('Aerial 16 italic')).place(x=5, y=140)
        win.mainloop()

Note that win being destroyed will also affect the win.lift and win.after calls in lift_window. I'm not entirely certain what you're trying to do there (you call lift_window twice, once from a new thread, and each call sets a timer to call it again?), so I can't comment on how to fix that part.


text:
Q: Is it possible to open the site zoomed in based on resolution of user's monitor? I have this site which was developed few years back. At that time it was developed keeping 1024x768 resolution in mind. Now a days people use much higher resolution.
I was thinking if it is possible to open the site zoomed in automatically if the resolution of user's monitor is set considerably higher than 1024x768?
Right now if I look my site on my macbook it looks like following:

I would like it to be opened up like following:

I hope I have explained the question correctly.

A: My browser settings are my own! It's none of the webeveloper's business to change anything in that area!
What you may be looking for however, are flexible layouts. (But that doesn't work well when you integrate pictures, as with zooming, they tend to get pixelated...)
Update
If you want to have a flexible layout that scales well and easily (also through scripting), you can consider using the em unit.
To have only a layout adjust to the screen width for instnace, you can also use percentage values.


text:
Q: Combination of word of string only replacing space I am trying to find the all combination of words of string in particular format for example
string="hello python world"

the output format must be like
'hello python world, hellopython world, hello pyhtonworld, hellopythonworld'


text:
Q: Populate a Partial View on page load Im developing an MVC project and im using Ajax for displaying a list of shifts.
Here's my parent page, shifts.chtml:
@model UI.ViewModels.ViewModelShiftList

Shifts

 @Ajax.ActionLink("View All Shifts", "AllShifts", "Shifts",
                                    new AjaxOptions
                                    {
                                        UpdateTargetId="searchResults",
                                        HttpMethod="GET", //default
                                        InsertionMode= InsertionMode.Replace, //replace
                                        LoadingElementId="progress"
                                    })

     @Html.RenderPartial("_ShiftList",model)

heres the controller action for the above page:
public ActionResult Shifts()
    {
        ViewModelShiftList viewModel = new ViewModelShiftList
        {
            Shifts = _shiftService.GetShifts().ToList()
        };
        return View(viewModel);
    }

Should I not be able to send the viewmodel produced here into the partial view? Or do I have to create another action for the partial view? If so, what is the correct way to send an action to the controller of a partialview?
The error im gettin is at this point:
@Html.RenderPartial("_ShiftList",model)

// cannot impilicty convert type void to object

A: This was a simple fix...I needed to add curly brackets like so..
@{Html.RenderPartial("_shiftlist", Model);}


text:
Q: Updating lookup fields of SharePoint list items using REST in C# I am using a service reference to listdata.svc to manipulate SharePoint lists. I have a list for companies and a list for people.
I can manipulate the data like this:
HomeDataContext proxy = new HomeDataContext(new Uri(url + "/_vti_bin/listdata.svc"));
proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
PeopleItem person = proxy.People.Where(p => p.Name.Equals(myName)).First();
PeopleItem boss = proxy.People.Where(p => p.Name.Equals(bossName)).First();
CompaniesItem company= proxy.Companies.Where(c => c.ID.Equals(companyName)).First();
company.Employees.Add(person);
company.Boss = boss;
company.Name = "New Name";
proxy.UpdateObject(company);
proxy.SaveChanges();

With this method I can edit basic properties of my listitems (like Name). However, I can't use this to update lookup fields (like Boss or the multiple lookup Employees). In the object model, it all appears to work and no exceptions are thrown, but after updating and saving, the fields are simply blank in SharePoint.

A: That above example isn't going to work.  for a single value look up field you need to set the id property.
For the company to have a look up to the boss you will need to go
company.BossId = boss.Id;
the above example won't write the changes to the sharepoint list, with lookup fields you need to set the Id property.

A: If person item is already present in sharepoint and you just want to add it in Company than you can use:
HomeDataContext proxy = new HomeDataContext(new Uri(url + "/_vti_bin/listdata.svc"));
proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
PeopleItem person = proxy.People.Where(p => p.Name.Equals(myName)).First();
PeopleItem boss = proxy.People.Where(p => p.Name.Equals(bossName)).First();
CompaniesItem company= proxy.Companies.Where(c => c.ID.Equals(companyName)).First();
//company.Employees.Add(person);
company.Boss = boss;
company.Name = "New Name";
proxy.UpdateObject(company);
proxy.SaveChanges();
//To remove employee from company
proxy.DeleteLink(company, "Employee", person);
proxy.SaveChanges();
//To Add person as employee
proxy.AddLink(company,"Employee",person);
proxy.SaveChanges();

You can also look at proxy.AddRelatedObject() method to create new person and link simultanously. For more information on these methods:
 http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicecontext.aspx


text:
Q: Relational Database for genetic variation I am trying to represent to genetic variation data in a database for my institution. We have discovered genetic variants, which have associated with them reference alleles, mutant alleles, chromosome, position, name, possible effect, gene, position in gene etc.
Though it's not essential for the question context is sometimes useful, I'll be building this with django, and the db backend will be either PostgreSQL or MySQL (suggestions about choice here also welcome, though not main focus of question)
To represent this information properly I have set about designing a relational database. I'm running into problems defining the most efficient structure however.
I could represent it as follows:
Variants belong to genes in a many to one relationship. i.e. one gene can have many variants but one variant cannot usually span more than one gene. (However sometimes this can happen with large CNVs or where two genes overlap, so perhaps a many to many relationship???)
Variants are also discovered in individuals. Individuals have genotypes, which is just two copies of the various combinations of alleles of the variant. I'm not sure about the best for this at all, perhaps a joint primary key of variant and individual and the record the genotype as the number of mutant alleles (0,1,2 for example)???
So my question is (sorry for all the preamble, and bio talk) what way do we thing is the best, or a better design for these three things:
Variants - the main thing I want to store information about, and Genes, and Individuals - both essential for any downstream analyses.
Any advice is much appreciated. Again sorry for the somewhat ephemeral nature of the question.

A: Well, I know nothing about genes, nor do I speak bio-lingo. However, I have gathered some propositions from your question and wikipedia and came up with this. Mostly as an exercise in modelling, using FCO approach. So here are some statements, you should be able to flag each one as true or false.

*

*Gene is a name given to some stretches of DNA.

*Gene occupies a given position on a chromosome.

*Chromosome is a single piece of coiled DNA containing many genes.

*Allele is a one of multiple alternative forms of a single gene.

*Allele is a gene.

*Variant is a DNA sequence.

*Variant spans gene.

*Variant spans allele.

*Genotype is two copies of alleles.

*Phenotype is person's observable trait.

*Genotype affects phenotype.

*One phenotype can be affected by many genotypes.

*One genotype may affect many phenotypes.

*Person has many genotypes.

*Person has many observed phenotypes.

*Variant can be discovered in a person.


text:
Q: Embedding script with timeout in case server goes down I am looking for a way to make sure an external script file won't block the viewed page,
if the server which serves it is "down" (for example port 80 is blocked for some reason).
Currently when I test by taking down the server (Apache) manually, or block that file via server's firewall,
I see the browser is trying to load the resource (script in that case), without success for long period of time, until it aborts.
Is there a way to get past this issue?

A: Perhaps it's time to start using jQuery?
Check out jQuery.ajax() info and search for timeout keyword.
UPDATE:
For this particular solution you could use getScript() to fetch and execute remote scripts.

A: A recent post from Steve Souders analyzes this problem : Frontend - Single Point of Failure, by browsers and type of failure


text:
Q: Bootstrap - How to show modal box using option from select? How can I enable modal box on Bootstrap using <option> from <select> I tried the default way but it's not working.
$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').focus()
});

<select class="form-control">
    <option>select</option>
    <option data-toggle="modal" data-target="#myModal">Second Option</option>
</select>

See my example for a better clarification.

A: Still not sure why OP insisting fiddle in question not working where I can see it's working may be I have too much coffee today :)
Quick solution is assign id to <select> in HTML <select class="form-control" id="myselect">
<select class="form-control" id="myselect">
    <option value="">select</option>
    <option value="secondoption">Second Option</option>
</select>

Add value in select options and taking advantage of jQuery Change Function get value of Second Option and use Comparison Operators
to compare value and if value true,  can open the modal with Bootstrap JS Modal via JavaScript.
$(document).ready(function(){ //Make script DOM ready
    $('#myselect').change(function() { //jQuery Change Function
        var opval = $(this).val(); //Get value from select element
        if(opval=="secondoption"){ //Compare it and if true
            $('#myModal').modal("show"); //Open Modal
        }
    });
});

Fiddle


text:
Q: linker command failed with exit code 1 clang:error Ld /Users/simona/Library/Developer/Xcode/DerivedData/HelvetiQuiz-euzcyknolfniushksjdmyofanxpr/Build/Intermediates/ArchiveIntermediates/Unity-iPhone/IntermediateBuildFilesPath/HelvetiQuiz.build/Release-iphoneos/Unity-iPhone.build/Objects-normal/armv7/HelvetiQuiz normal armv7
    cd /Users/simona/Desktop/Ios
    export IPHONEOS_DEPLOYMENT_TARGET=4.3
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk -L/Users/simona/Library/Developer/Xcode/DerivedData/HelvetiQuiz-euzcyknolfniushksjdmyofanxpr/Build/Intermediates/ArchiveIntermediates/Unity-iPhone/BuildProductsPath -F/Users/simona/Library/Developer/Xcode/DerivedData/HelvetiQuiz-euzcyknolfniushksjdmyofanxpr/Build/Intermediates/ArchiveIntermediates/Unity-iPhone/BuildProductsPath -filelist /Users/simona/Library/Developer/Xcode/DerivedData/HelvetiQuiz-euzcyknolfniushksjdmyofanxpr/Build/Intermediates/ArchiveIntermediates/Unity-iPhone/IntermediateBuildFilesPath/HelvetiQuiz.build/Release-iphoneos/Unity-iPhone.build/Objects-normal/armv7/HelvetiQuiz.LinkFileList -dead_strip -weak_framework CoreMotion -weak-lSystem -stdlib=libstdc++ -fobjc-link-runtime -miphoneos-version-min=4.3 -framework Foundation -framework UIKit -framework OpenGLES -framework QuartzCore -framework OpenAL -liconv.2 -liPhone-lib -framework AudioToolbox -framework CFNetwork -framework MediaPlayer -framework CoreLocation -framework SystemConfiguration -weak_framework iAd -framework CoreMedia -framework CoreVideo -weak_framework AVFoundation -framework CoreGraphics -weak_framework CoreMotion -weak_framework GameKit -Xlinker -dependency_info -Xlinker /Users/simona/Library/Developer/Xcode/DerivedData/HelvetiQuiz-euzcyknolfniushksjdmyofanxpr/Build/Intermediates/ArchiveIntermediates/Unity-iPhone/IntermediateBuildFilesPath/HelvetiQuiz.build/Release-iphoneos/Unity-iPhone.build/Objects-normal/armv7/HelvetiQuiz_dependency_info.dat -o /Users/simona/Library/Developer/Xcode/DerivedData/HelvetiQuiz-euzcyknolfniushksjdmyofanxpr/Build/Intermediates/ArchiveIntermediates/Unity-iPhone/IntermediateBuildFilesPath/HelvetiQuiz.build/Release-iphoneos/Unity-iPhone.build/Objects-normal/armv7/HelvetiQuiz

ld: library not found for -liPhone-lib
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I get this error whenn I try to compile my app. What can I do?

A: These articles may be of use:

*

*http://answers.unity3d.com/questions/538363/error-when-i-updated-to-xcode-5-to-get-import-to-i.html

*http://xyglo.com/blog/2013/11/06/xcode-linker-mystery/
Some quick googling turns up a lot of cases where unity users have had this issue and it is related to the Library Search Path settings (Project -> target -> build settings).


text:
Q: Accessing the raw file stream from a node-formidable file upload I am creating an application that takes some file uploads and send them straight up to S3.  I would prefer not to even have the tmp file on my server, so I am using the Knox module and would like to take the raw stream from Formidable and send it over Knox to S3.  I have done something similar using Knox to download a file using this code:
knox.downloads.get(widget.download).on('response',function(sres){
    res.writeHead(200, {
        'Content-Type':'application/zip',
        'Content-Length': sres.headers['content-length'],
        'Content-Disposition':'attachment; filename=' + widget.download
    });
    util.pump(sres, res);
}).end();

Now I would like to do something similar in the oposite direction (File upload from the browser to S3).
So far I have written an event handler to capture each piece of data from the file as it's being uploaded:
var form = new formidable.IncomingForm();
form.onPart = function(part){
    if(!part.filename){
        form.handlePart(part);
    }else{
        if(part.name == 'download'){
            // Upload to download bucket
            controller.putDownload(part);
        }else{
            // Upload to the image bucket
            controller.putImage(part);
        }
        //res.send(sys.inspect(part));
    }
}
form.parse(req, function(err, fields, files){
    if(err){
        res.json(err);
    }else{
        res.send(sys.inspect({fields:fields, files:files}), {'content-type':'text/plain'});
        //controller.createWidget(res,fields,files);
    }
});

controller.putDownload = function(part){
    part.addListener('data', function(buffer){
        knox.download.putStream(data,part.filename, function(err,s3res){
            if(err)throwError(err);
            else{
                console.log(s3res);
            }
        });
    })
    knox.downloads.putStream(part, part.filename, function(err,s3res){

        if(err)throwError(err);
        else{
            console.log(s3res);
        }
    });
}

But the data event only give me the buffer.  So is it possible to capture the stream itself and push it to S3?

A: Use multiparty instead. It supports this kind of streaming like you want. It even has an example of streaming directly to s3: https://github.com/superjoe30/node-multiparty/blob/master/examples/s3.js

A: In an Express middleware, I use formidable together with PassThrough to stream-upload a file to S3 (in my case, to Minio which is S3 compatible through Minio SDK; and I believe it works for AWS S3 too with the same Minio SDK)
Here is the sample code.
const formidable = require('formidable')
const { PassThrough } = require('stream')

const form = new formidable.IncomingForm()
const pass = new PassThrough()

const fileMeta = {}
form.onPart = part => {
  if (!part.filename) {
    form.handlePart(part)
    return
  }
  fileMeta.name = part.filename
  fileMeta.type = part.mime
  part.on('data', function (buffer) {
    pass.write(buffer)
  })
  part.on('end', function () {
    pass.end()
  })
}
form.parse(req, err => {
  if (err) {
    req.minio = { error: err }
    next()
  } else {
    handlePostStream(req, next, fileMeta, pass)
  }
})

And handlePostStream looks like below, for your reference:
const uuidv1 = require('uuid/v1')

const handlePostStream = async (req, next, fileMeta, fileStream) => {
  let filename = uuidv1()

  try {
    const metaData = {
      'content-type': fileMeta.type,
      'file-name': Buffer.from(fileMeta.name).toString('base64')
    }

    const minioClient = /* Get Minio Client*/
    await minioClient.putObject(MINIO_BUCKET, filename, fileStream, metaData)

    req.minio = { post: { filename: `${filename}` } }
  } catch (error) {
    req.minio = { error }
  }
  next()
}

You can find the source code on GitHub, and its unit tests too.

A: What you want to do is override the Form.onPart method:
IncomingForm.prototype.onPart = function(part) {
  // this method can be overwritten by the user
  this.handlePart(part);
};

Formidable's default behavior is to write the part to a file. You don't want that. You want to handle the 'part' events to write to the knox download. Start with this:
form.onPart = function(part) {
    if (!part.filename) {
        // let formidable handle all non-file parts
        form.handlePart(part);
        return;
    }

Then open the knox request and handle the raw part events yourself:
part.on('data', function(data) {
    req.write(data);
});
part.on('end', function() {
    req.end();
});
part.on('error', function(err) {
    // handle this too
});

As a bonus, if the req.write(data) return false that means the send buffer is full. You should pause the Formidable parser. When you get a drain event from the Knox stream you should resume Formidable.

A: There is no way for you to capture the stream, because the data has to be translated by Formidable. The buffer you're given is the file contents in chunks of buffer.length: this might be a problem because looking at Formidable's docs it appears that until the file is completely uploaded it can't reliably report the file size and Knox's put method might need that.
Never used Knox this way before, but you might have some luck with something like this:
controller.putDownload = function(part){
    var req = knox.download.put(part.filename, {
      'Content-Type': 'text/plain'
    });
    part.addListener('data', function(buffer){
    req.write(buffer);
    });
    req.on('response', function(res){
       // error checking
    });
    req.end();
}

A little unsure about the response checking bits, but....see if you can whip that into shape. Also, Streaming an octet stream from request to S3 with knox on node.js also has a writeup that may be useful to you.


text:
Q: combinations of combinations in R Say I have two vectors
upVariables<-c("up1", "up2", "up3", "up4", "up5")
downVariables<-c("down1", "down2", "down3", "down4", "down5")

Each of these will be used to look up an number in another vectors. I'm looking to find all possible sets of two ratios (all possible sets of four variables, two from each vector), where the numerator is always from upVariables, the demnominator is always from downVariables and final set doesn't use the same variable twice.
I've got as far as
upCombos<-combn(upVariables,2)
downCombos<-combn(downVariables,2)
combos<-arrange(expand.grid(upCombos=upCombos[,1],downCombos=downCombos[,1]),upCombos)

I'm only using the first possible combination here, to illustrate, but I'd want to iterate over all possible combinations. This  gives me:
> combos
  upCombos downCombos
1      up1      down1
2      up1      down2
3      up2      down1
4      up2      down2

What I'd like to produce from this though is two sets, something like:
> combos[1]
  upCombos downCombos
1      up1      down1
2      up2      down2

and
> combos[2]
  upCombos downCombos
1      up1      down2
2      up2      down1

So that in each case, each value from upCombos is used only once and each value from downCombos is used only once. Does that make sense? Any ideas on how one goes about this?
Ideally I'd like to then be able to generalize to sets of 3 sampled from the original vectors rather than sets of 2, but I'll be happy to get sets of 2 working for now.
** Edit
So Jota has provided a solution which provides the arrangements within any group of 4 variables (2 from upVariables, 2 from downVariables). I'm still failing to see how I iterate over all possible sets of 4 variables though. The nearest I've got is to sit Jota's suggestion inside two for loops (spot the not-yet-R-programmer). This this returns many fewer combinations than there should be.
n<-2
offset<-n-1
for (i in 1:(length(upVariable)-offset)){
  for (j in 1:(length(downVariables)-offset)){
    combos <- expand.grid(upVariables[i:(i+offset)], downVariables[j:(j+offset)])
    combos <- combos[with(combos, order(Var1)), ]  # use dplyr::arrange if you prefer
    mat <- matrix(1:n^2, byrow = TRUE, nrow = n)
    for(j in 2:nrow(mat) ) mat[j, ] <- mat[j, c(j:ncol(mat), 1:(j - 1))]
      pairs<-(split(combos[c(mat), ], rep(1:n, each = n)))
     collapsed<-sapply(lapply(pairs, apply, 1, paste, collapse = '_'), paste, collapse = '-')
      ratioGroups<-c(ratioGroups,collapsed)
  }
}

This returns only 16 sets of variables (each with 2 combinations, so 32 in all). With 5 variables in each set though, there's many many more possibilities.

A: You could use expand.grid to create combinations and prepare subsets
    with regular expressions
upVariables<-c("up1", "up2", "up3", "up4", "up5")
downVariables<-c("down1", "down2", "down3", "down4", "down5")

DF = expand.grid(upVariables,downVariables)

DF$suffix1 = as.numeric(unlist(regmatches(DF$Var1,gregexpr("[0-9]+",DF$Var1))))

DF$suffix2 = as.numeric(unlist(regmatches(DF$Var2,gregexpr("[0-9]+",DF$Var2))))

head(DF)
#  Var1  Var2 suffix1 suffix2
#1  up1 down1       1       1
#2  up2 down1       2       1
#3  up3 down1       3       1
#4  up4 down1       4       1
#5  up5 down1       5       1
#6  up1 down2       1       2

DF_Comb1 = DF[DF$suffix1==DF$suffix2,]
DF_Comb2 = DF[DF$suffix1!=DF$suffix2,]

DF_Comb1
#    Var1  Var2 suffix1 suffix2
# 1   up1 down1       1       1
# 7   up2 down2       2       2
# 13  up3 down3       3       3
# 19  up4 down4       4       4
# 25  up5 down5       5       5

head(DF_Comb2)
  # Var1  Var2 suffix1 suffix2
# 2  up2 down1       2       1
# 3  up3 down1       3       1
# 4  up4 down1       4       1
# 5  up5 down1       5       1
# 6  up1 down2       1       2
# 8  up3 down2       3       2

A: Here's what I came up with in response to the comments and the edited question.
# create combos and order them according to the first variable
combos <- expand.grid(upVariables[1:2], downVariables[1:2])
combos <- combos[with(combos, order(Var1)), ]  # use dplyr::arrange if you prefer
# if names are important, set them:
# names(combos) <- c("upCombos", "downCombos")

# create a matrix to use to sort combos
mat <- matrix(1:2^2, byrow = TRUE, nrow = 2)
# take some code from Carl Witthoft to shift the above matrix
# from: http://stackoverflow.com/a/24144632/640595
for(j in 2:nrow(mat) ) mat[j, ] <- mat[j, c(j:ncol(mat), 1:(j - 1))]

# use the matrix to sort combos, and then conduct the splitting
initialResult <- split(combos[c(mat), ], rep(1:2, each = 2))

$`1`
  Var1  Var2
1  up1 down1
4  up2 down2

$`2`
  Var1  Var2
3  up1 down2
2  up2 down1

To generate the rest of the combinations, we can iterate through and replace the up variables and down variables:
# use regular expressions with the stringi package to produce the rest of the combinations.
library(stringi)
# convert from factor to character for easier manipulation
initialResult <- lapply(initialResult, sapply, as.character)

# iterate through the columns of upCombos
intermediateResult <- lapply(seq_len(dim(upCombos)[2]),
    function(ii) {
        jj <- stri_replace_all_fixed(unlist(initialResult),
            pattern = c("up1", "up2"),
            replacement = c(upCombos[, ii]))
        relist(jj, initialResult)})

# iterate through columns of downCombos
finalResult <- lapply(seq_len(dim(downCombos)[2]),
    function(ii) {
        jj <- stri_replace_all_fixed(unlist(intermediateResult),
            pattern = c("down1", "down2"),
            replacement = c(downCombos[, ii]), vectorize_all = FALSE)
        relist(jj, intermediateResult)})

A: So I think I may have cracked it. I've pillaged a couple of answers to other questions. There's a function here called expand.grid.unique which removes duplicates if you put the same vector into expand.grid twice. And there's one here, called expand.grid.df which I'm not even going to pretend to understand which expands expand.grid to work on dataframes. However, combined, they do what I want them to do.
upVariables<-c("up1", "up2", "up3", "up4", "up5")
downVariables<-c("down1", "down2", "down3", "down4", "down5")
ratioGroups<-data.frame(matrix(ncol=2, nrow=0))
colnames(ratioGroups)<-c("mix1","mix2")

ups<-expand.grid.unique(upVariables,upVariables)
downs<-expand.grid.unique(downVariables,downVariables)
comboList<-expand.grid.df(ups,downs)
comboList <- data.frame(lapply(comboList, as.character), stringsAsFactors=FALSE)
colnames(comboList)<-c("u1","u2","d1","d2")

There's a bunch of faffing about in there converting everything back to strings because everything gets converted to factors for some reason.
If I put Jota's answer into a function:
getGroups<-function(line){
  n<-2 #the number ratios being used.
  combos <- expand.grid(as.character(line[1:2]), as.character(line[3:4]))
  combos <- combos[with(combos, order(Var1)), ]  # use dplyr::arrange if you prefer
  mat <- matrix(1:n^2, byrow = TRUE, nrow = n)
  for(j in 2:nrow(mat) ) mat[j, ] <- mat[j, c(j:ncol(mat), 1:(j - 1))]
  pairs<-(split(combos[c(mat), ], rep(1:n, each = n)))
  collapsed<-sapply(lapply(pairs, apply, 1, paste, collapse = '_'), paste, collapse = '-')
}

I can then use
ratiosGroups<-as.vector(apply(comboList,1,getGroups))

to return a list of all possible combinations. I'm guessing this still isn't the best way to achieve my larger goal, but it's getting there.


text:
Q: Cant change background size because of position absolute First of all the JSfiddle
I'm trying to make the div (or the element inside the div) background to take the image width and set the background width to it. Because I'm using jQuery position I must use the position: absolute property which for some reason disables the background-size in css and backgroundSize in jQuery. It can only work with those properties when I delete the position property which disable the jQuery position. I tried margin/padding it didn't work either.
HTML(Wont let me add a picture so couldn't add it)
JS/jQuery
$('#ShortText').css({
  left: screen.width * .4,
    top: screen.height * .4,
})

CSS
#ShortText{
position:absolute;
background-color: rgba(255, 255, 255,.6);
background-size:100%;
}

My final goal is one of those slideshow images with text on them which when you hover over the text more text shows and I need the background because I don't want to set different color to every text on every picture
EDIT:
Add code & fixed jsfiddle
&more info

A: Your position is absolute, this is not allowing things to change. Changing 'absolute' to 'relative' should fix this. It worked for me in your jsFiddle just by changing that property.


text:
Q: jump to specific id after php validation fails could anybody advise me how I can let page jump (or scroll) to specific id, where error message appears after php validation fails ?
I have a php page which is long that user has to scroll to the bottom. In the middle of the page, there is contact form where user can input email address and comment. After user press "send" button, php validation works. However, it jumps to very top of the page after pressing "send" button. Afterwards, I can see error message shown just below the contact form by scrolling down by myself. But, it's not the way how it should be as you all would agree...
Then, I tried to use javascript scrollTop as it's shown below. ScrollTop works, although there is no error message appearing....
I know that I am missing something, but I don't know what I am missing....
Could you please help me ?
index.php and top.js are shown below;
index.php
<?php

session_start();
if(isset($_POST['sendemail'])){

  $_SESSION['email'] = $_POST['email'];
  $_SESSION['message'] = $_POST['message'];

  if (!$_SESSION['email'] || !filter_var($_SESSION['email'],    FILTER_VALIDATE_EMAIL)) {
    $errEmail = 'please type correct email address';
  }

  if (!$_SESSION['message']) {
    $errMessage = 'please type message';
  }

  if (!$errEmail && !$errMessage) {
    header('Location: messagesent.php');
    exit;
  }
}
?>

  ..

    ...

    ...

        <input name="email" type="text">
        Email
        <?php echo "
$errEmail
";?>

        <textarea name="message"></textarea>
        Message
        <?php echo "
$errMessage
";?>

        <button id="contactbutton" type="submit" name="sendemail">Send</button>

   ...

  ...

top.js
$(function(){
  $('#contactbutton').click(function(){
    $('html,body').animate({
      scrollTop: $('#contact').offset().top
    }, 1000);
    return false;
  });
});

A: perhaps you can create an id for your message box:
<?php echo "
$errMessage
";?>

then in your validation you can do something like:
if (isset($errMessage) && !empty($errMessage)) {
    header("Location: index.php#errMessage");
  }

This will focus the cursor on the error message. You can also use the same technique to change focus on the text area and other fields that is required.

A: Assuming that you have a form element enclosing your inputs, you can set the form action to your current page using a fragment identifier:
<form action="#errors"> ... </form>

Then you can either assign an id to the error container:

Error list

Or place an empty anchor right before the error container:

Error list

The name and id values must be unique in the document. No explicit redirection is needed.


text:
Q: Can Entity Framework combine filtering logics in multiple methods and make ONE LINQ to SQL? If I call the public method GetSomeFilteredPizzas in the below by using Entity Framework 5,
How the entity framework manages the calls to the SQL server:

*

*Does it apply ghe call in the public method together with all the logic in the applyFilter1 and applyFilter2 methods and makes only one call to SQL server?

*Or it retrieves some by LINW to SQL and then applies those sample filtering methods in the memory -like combining LINQ to SQL and LINQ to Entities upon EF's internal preferences?

Sample below
public IEnumerable<Pizza> GetSomeFilteredPizzas (bool isWholeGrain, bool isColdPizza)
{
    var myPizzas = Context.Pizza.Include(p => p.Ingredients).Where(p => p.IntroducedToMarketAt == null);

    myPizzas = applyFilter1(isWholeGrain, myPizzas);
    myPizzas = applyFilter2(isColdPizza, myPizzas);

    return myPizzas.ToArray();
}

private static IQueryable<Pizza> applyFilter1(bool isWholeGrain, IQueryable<Pizza> pizzas)
{
    if (isWholeGrain)
    {
        pizzas = pizzas..Where(p => p.BreadType == "WholeGrain");
    }

    else
    {
        pizzas = pizzas..Where(p => p.BreadType == "Standard");
    }

    return pizzas;
}

private static IQueryable<Pizza> applyFilter2(bool isColdPizza, IQueryable<Pizza> pizzas)
{
    if (isColdPizza)
    {
        pizzas = pizzas..Where(p => p.TemperatureWise == "Cold");
    }

    else
    {
        pizzas = pizzas..Where(p => p.TemperatureWise == "Hot");
    }

    return pizzas;
}

A: The logic in your filter methods is executed before entity framework makes an effort to generate the query. EF parses the query applied to IQueryable when you ask it for the result in your case .ToArray() call at the end of GetSomeFilteredPizzas method. So both filters will be applied to your sql query in single go.
You can verify that by launching sql profiler on your database and see the query that was generated.


text:
Q: how to compress data using php codeigniter with mysql I am developing a system that includes a log history. In the log history is the record of actions taken by every users. Someone suggested that I have to compress the data annually because the database is expected to grow and so that I can save space. I have this table:
    delimiter $$

CREATE TABLE `actionhistory` (
    `historyID` int(11) NOT NULL AUTO_INCREMENT,
    `empID` int(11) NOT NULL,
    `item` varchar(50) NOT NULL,
    `actionTaken` varchar(15) NOT NULL,
    `type` varchar(15) NOT NULL,
    `dateActTaken` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`historyID`),
    KEY `emp` (`empID`)
) ENGINE=InnoDB AUTO_INCREMENT=429 DEFAULT CHARSET=latin1$$

What is the syntax in doing it? I want to do it annually regardless of how many rows it has per year.
EDIT: I have read about using ROW_FORMAT, KEY_BLOCK_SIZE but since the row per year is not constant, I didn't use it.

A: You have to take out Year (Y) form field dateActTaken to identify which year is it. Once you have year then you can fetch all records belonging to that year.
As far as compression, you can take it in zip file or you can save yearly data in your other mining databases.


text:
Q: Toplink, the DatabaseQuery class and oracle execution paths., Avoiding hardparses Abstract:
An application I work on uses top link, I'm having trouble finding out if and when top link automatically uses bind variables.
Problem Description:
Lets say I need to do something akin to validating if a vehicle full of people can travel somewhere, where each person could invalidate the trip, and provide error messages so the person could get their restrictions removed before the trip starts. A simple way to do that is to validate each member in the list, and display a list of errors. Lets say their info is stored on an oracle database and I query for each riders info using their unique ids, This query will be executed for each member in the list. A naïve implementation would cause a hard parse, a new execution path, despite only the unique id changing.
I've been reading about bind variables in sql, and how they allow for reuse of an execution path, avoiding cpu intensive hard parses.
A couple links on them are:

*

*http://www.akadia.com/services/ora_bind_variables.html

*https://oracle-base.com/articles/misc/literals-substitution-variables-and-bind-variables
An application I work on uses toplink and does something similar to the situation described above. I'm looking to make the validation faster, without changing the implementation much.
If I do something like the following:
Pseudo-code
  public class userValidator{
  private static DataReadQuery GET_USER_INFO;
  static{
    GET_USER_INFO = "select * from schema.userInfo ui where ui.id= #accountId"
    GET_USER_INFO.bindAllParameters();
    GET_USER_INFO.cacheStatement();
    GET_USER_INFO.addArgument("accountId", String.class);
  }

  void validate(){
     List<String> listOfUserAccountIds = getuserAccountIdList();
     list args;
     for(String userAccountId: listOfUserAccountIds){
        args = new ArrayList(1);
        args.add(userAccountId)
        doSomethingWithInfo(getUnitOfWork().executequery(GET_USER_INFO, args);
     }
  }
}

The Question:
Will a new execution path be parsed for each execution of GET_USER_INFO?
What I have found:
If I understand the bindAllParameters function inside of the DatabaseQuery class well enough, it simple is a type validation to stop sql injection attacks.
There is also a shouldPrepare function inside the same class, however that seems to have to do more with allowing dynamic sql usage where the number of arguments is variable. A prepared DatabaseQuery has its sql written once with just the values of the variables changing based on the argument list passed in, which sounds like simple substitution and not bind variables.
So I'm at a lost.

A: This seems answered by the TopLink documentation

By default, TopLink enables parameterized SQL but not prepared
  statement caching.

So prepared statements are used by default, just not cached.  This means subsequent queries will have the added cost of re-preparing statements if not optimized by the driver.  See this for more information on optimizations within TopLink


text:
Q: span within td doesn't generate properly

                    abc 123
                    another td
                    another td

Why my above code the span of the first td doesn't generate properly?
I want to have the result like this
=============================================
abc       =   another td   =   another td   =
123
=============================================

A: Use css display property to archive this,
view this jsFiddle
CSS
td{
    vertical-align: top;
}
td span {
    display:block;
}

HTML

        abc 123
        another td
        another td

A: Using a span tag does not deliver a result like you want. You need to have CSS rule for that.
add the following CSS to your page,
td {
    width: 100px;
}

td span {
    word-wrap: break-word;
    display: block;
}

This sets a width for  elements and the span is used to break the text line and move it to the next line.


text:
Q: Converting an approximation sum into an integral when sums are nested with dynamic bounds Some function $f(x)$ returns a probability of an event $E$ happening given condition $x$. Simply inputting some value of $x$ and getting an answer is simple enough. But lets say that $x$ can take any random value with known bounds $a<x<b$. Now (I think) the probability of E occuring is the average value of $f(x)$ between A and B: $$ f_{avg} = \frac{1}{b-a} \int^b_a f(x) dx$$
So far so good. I can calculate the probability of $E$ with one equation without iterating and/or approximating, but I've encountered an extra layer of complexity that I don't know how to solve. My equation is $f(x,y)$ and I'm trying to find the probability of $E$ with $a<x<b$ and $a<y<g(x)$. ($g(x)$ is a simple linear function)
I hardly know where to start. I can make a rough approximation by iterating through values of $x$ and $y$ like so: $$ \sum_{x= a+1}^{b-1} \sum_{y=a+1}^{g(x)} f(x,y)$$ But I need an exact answer. I thought maybe from here I would be able to use the limit-definition of an integral to convert the approximation sum into an integral to get the exact value, but I am completely lost at what to do since I have never dealt with nested integrals and the dynamic upper bound of the inner sum adds extra complexity. Can anyone help me figure out what to do?

A: I believe you can simply use
$$P(E)=\frac{1}{b-a}\int_a^b \frac{1}{g(x)-a}\int_a^{g(x)} f(x,y)dydx$$
assuming that $g(x)\gt a$ for all $x\in[a,b]$.
Here is why:
Let $P(E|x)$ represent the probability that $E$ occurs for some fixed $x$. This will be a function of $x$, since the value of $x$ is fixed and $y$ is random. We have then that
$$P(E|x)=\frac{1}{g(x)-a}\int_a^{g(x)}f(x,y)dy$$
Thus,
$$\begin{align}
P(E)
&=\frac{1}{b-a}\int_a^b P(E|x)dx\\
&=\frac{1}{b-a}\int_a^b \frac{1}{g(x)-a}\int_a^{g(x)}f(x,y)dydx\\
&=\frac{1}{b-a}\int_a^b \int_a^{g(x)}\frac{f(x,y)}{g(x)-a}dydx\\
\end{align}$$
That probably won't be much fun to integrate, though.


text:
Q: Node Js Authentication I'm developing a web application using node.js for home automation using raspberry pi.
As I have to open the web page to the outside, I would like you to advise me what is the best and secure way to do the user authentication to avoid not authorized people to enter the main web page that controls something in the house (ex. Switch on/off the heater).

A: If you are using express to render your website with node.js, you can use passportjs to easily add authentication using a variety of strategies.  http://passportjs.org/


text:
Q: How to determine iOS device has cellular capability to start significant-change location service or not? How to check whether iOS device has a cellular capability to start significant-change location service?
Arcording to my knowledge, significant-change location service using cellular tower to locate your device location. So I would like to check cellular capability on my device before start/don't start significant-change location service.
I also google, I found Reachability, but may be Reachability only detect current active connection.
Any advice was appreciated.

A: This might help.
 UIDevice- extension


text:
Q: Backbone.js: fetch({add: true}), trigger change event? I am wondering if there is any way to get the changed models when passing the add: true to fetch. It renders all the new models in the collection but I'd like to also know if there is any models that changed.
Is this possible?
I also considered the possibility of passing a different function as the success handler to fetch, a function that will re-render only certain portions of the view and not the entire view.

A: The usual pattern is to have a view that renders your models. You then:

*

*subscribe in the collection's view to the collection's add event in order to append the views of the added models.

*let your models' views subscribe to the model's change to re-render.

If you still want to have only one view, you:
 - subscribe to the collection's add event in order to append to the view.
 - subscribe to the collection's change event and update parts of the view.

A: As of version 0.9.10, you should use {update:true} instead of {add:true}. This will tell the collection to trigger a change event for each one of its models that has changed. (Note that the change event is triggered on the collection not the models)
If you want the collection to add and update models, but not remove them, you can accomplish this like so:
myCollection.fetch({update:true, remove:false});

Here's the relevant section in the Backbone.js documentation.

A: You can bind to the "add" event and trigger a method that only updates a portion of the view. You have to explicitly bind a collections events in order to re-render your view. So in other words you control which parts of the view should be rendered. Can you not just alter the function where you are rendering you view based on the collection "change" event?
Each model has a method isNew(), and hasChanged(). You could loop through your collection to see which models have changed. If there is an easier and more proficient way to do this, I am all ears.
Maybe you can post some code so we can see exactly what you are doing?


text:
Q: I get an error associated with the encoding I need help. I am sending an http request from the oracle database to Spring mvc. And in return, I get it HTTP Status 400 – Bad Request How can I fix this? Added
utl_http.set_body_charset (req, 'WINDOWS-1251'); and that didn't help either.
With Latin letters, everything works well. As soon as I change to Cyrillic, I get an error
request(plsql)
declare

content varchar2(4000) := '{"to":"996707332572","from":"Текст","text":"Тест текст"}';

    begin

       req := utl_http.begin_request(url, 'POST',' HTTP/1.1');
       utl_http.set_header(req, 'user-agent', 'mozilla/4.0');
       utl_http.set_header(req, 'Content-Type', 'application/json');
       utl_http.set_header(req, 'Content-Length', length(content));
       utl_http.set_body_charset ('UTF-8');
       utl_http.write_text(req, content);

       res := utl_http.get_response(req);

method in controller
    @ResponseBody
    @RequestMapping(value = "/send-msg",method = RequestMethod.POST,
            produces = "application/xml; charset=utf-8")
    public Object sendMsg(@RequestBody SmsBody smsBody) throws Exception


text:
Q: Custom view is measured incorrectly when placed with another view elements I created a custom view which I want to place in RelativeLayout with a button under it. The problem I'm having is that if I put a button under the custom view using android:layout_below="@id/customView", the customView takes full height, so there's no space on the screen to place the button, it's only placed below the bottom border of the screen and therefore invisible. The size I receive at the last call of customView's onMeasure() method should be already calculated, i.e. all another view sizes should be taken into account, but it seems that in this case height of the button is not.
Here's my layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/darkBlueBackground"
tools:context="com.example.TimePickerActivity">

<com.example.TimePicker
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="5dp"
    android:paddingRight="20dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:id="@+id/picker"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/picker"
    android:layout_weight="1"
    android:id="@+id/okButton"
    android:text="OK"/>

This is final sizes that were measured by onMeasure():
07-26 00:24:39.551 19930-19930/com.example D/TAG: width = 720 height = 1230
At the same time if I put the button above the customView everything looks pretty fine, onMeasure() receives correct height for the customView, so there's some space for button.
Here's layout for that case:
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:id="@+id/okButton"
    android:text="OK"/>

<com.example.TimePicker
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/okButton"
    android:paddingLeft="5dp"
    android:paddingRight="20dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:id="@+id/picker"/>

Final size from onMeasure is different:
07-26 00:24:39.551 19930-19930/com.example D/TAG: width = 720 height = 1134
Why is the custom view (TimePicker) measured correctly in one case and isn't in another?

A: Try setting android:layout_height=wrap_content" on the com.example.TimePicker view. Setting the height to match_parent causes the view to fill the parent's height, leaving no room for the button.


text:
Q: Project structure for API only Django project I want to create a Django based backend providing an API using django-rest-framework only. The admin interface is the only visual interface I need for end users. The API shall be used by/integrated with a JS frontend. The backend consists of several parts like configuration, visualization, etc. According to design best practices I'd first create a Django project my_project with django-admin startproject my_project . and add an app per part with python manage.py startapp configuration, python manage.py startapp visualization, etc. (In the django-rest-framework quickstart there is generated one Django app.)
To me it's not clear how I have to adopt the Django design best practice of using apps to RESTful API based JS frontend integration. In case I want to integrate the backend with a JS frontend how should I structure my codebase? Should I create apps configuration, visualization, ... (I don't create template based views) and define corresponding models with a single RESTful API. Where should I place the API sources w.r.t. project structure? How should I map the API to models?

A: DRF extends Django views and sort of replaces forms with serializers. So you can use exactly the same structure with Django. Or if you like, you can move the DRF modules to a separate api package either for each app or project-wide. It all depends on you. But to keep it simple since it's an API only project, you can just use the normal Django app structure with DRF modules flat in the apps


text:
Q: Embedded python crashes upon import of matplotlib.pyplot I am messing about, trying to build something similar to IPython/Jupyter notebooks. I'm writing my application in QT5, so much of this is related to 'embedding' Python in a native application.
I figured out how to embed python and how to allow it to execute scripts entered by the user. I would like to be able to use plotting libraries (such as matplotlib), and display their output in my application. (in fact, the thing I am  trying to do appears to be very similar to what is described in this question).
However, when I try to import the plotting library using import matplotlib.pyplot, my application segfaults (I tried debugging, but the crash is not in my code, so I can't get anything sensible out of it).
The code I use to initialize the embedded Python, and to run arbitrary scripts is shown at the bottom of this question.
I can import other libraries (such as sys or numpy) fine. I can import matplotlib fine. But when I try to import matplotlib.pyplot, it segfaults.
Does anyone have any suggestions?
EDIT:
I have determined that the cause lies (for some reason) with me using QT. When I compile a simple C or C++ program that imports matplotlib, it does not segfault...
My code:
#include "pythoninteractor.h"

#include <QString>
#include <Python.h>
#include <string>
#include <QList>

PythonInteractor::PythonInteractor()
{
    this->pyOutput_redir =
"import sys\n\
class CatchOutErr:\n\
    def __init__(self):\n\
        self.value = ''\n\
    def write(self, txt):\n\
        self.value += txt\n\
catchOutErr = CatchOutErr()\n\
sys.stdout = catchOutErr\n\
sys.stderr = catchOutErr\n\
"; //this is python code to redirect stdouts/stderr

    QString paths[] = {"",
                       "/home/tcpie/anaconda3/lib/python35.zip",
                       "/home/tcpie/anaconda3/lib/python3.5",
                       "/home/tcpie/anaconda3/lib/python3.5/plat-linux",
                       "/home/tcpie/anaconda3/lib/python3.5/lib-dynload",
                       "/home/tcpie/anaconda3/lib/python3.5/site-packages",};

    Py_SetProgramName(L"qt-notepad-tut");
    Py_Initialize();

    PyObject *pModule = PyImport_AddModule("__main__"); //create main module
    PyRun_SimpleString(this->pyOutput_redir.toStdString().c_str()); //invoke code to redirect

    PyObject *sys_path;
    PyObject *path;

    sys_path = PySys_GetObject("path");
    if (sys_path == NULL)
        return;

    PySequence_DelSlice(sys_path, 0, PySequence_Length(sys_path));
    for (size_t i = 0; i < sizeof(paths) / sizeof(QString); i++) {
        path = PyUnicode_FromString(paths[i].toStdString().c_str());

        if (path == NULL)
            continue;

        if (PyList_Append(sys_path, path) < 0)
            continue;
    }
}

QString PythonInteractor::run_script(QString script)
{
    QString ret = "";
    PyObject *pModule = PyImport_AddModule("__main__");
    PyRun_SimpleString(script.toStdString().c_str());
    PyErr_Print(); //make python print any errors

    PyObject *catcher = PyObject_GetAttrString(pModule,"catchOutErr"); //get our catchOutErr created above

    if (catcher == NULL) {
        Py_Finalize();
        return ret;
    }

    PyObject *output = PyObject_GetAttrString(catcher,"value"); //get the stdout and stderr from our catchOutErr object

    if (output == NULL) {
        return ret;
    }

    ret = QString(PyUnicode_AsUTF8(output));
    return ret;
}

A: The reason of this crash turned out to be a conflict between QT versions.
First of all, the issue can be reproduced using the following minimal code. Commenting out the "Q_OBJECT" line in main.h prevents the crash in all cases.
File main.h:
#ifndef MAIN_H
#define MAIN_H

#include <QMainWindow>

class test : public QMainWindow
{
    Q_OBJECT // Commenting out this line prevents the crash
};

#endif // MAIN_H

File main.cpp:
#include <Python.h>
#include "main.h"

int main()
{
    Py_Initialize();
    PyRun_SimpleString("import matplotlib.pyplot as plt");
    PyRun_SimpleString("print('If we are here, we did not crash')");

    Py_Finalize();
    return 0;
}

I am running Python3 through Anaconda. However, I had installed QT5 through my package-manager (in my case: apt-get on Ubuntu). I suspect the issue lies with the matplotlib of my Anaconda install using a different QT5 version than the one I had installed through my package-manager.
The fix is easy: installing matplotlib through my package-manager fixes the issue! (on my Ubuntu system: sudo apt-get install python3-matplotlib)


text:
Q: Gitlab CI/CD: "needs" not working in .gitlab-ci.yml I am using needs in .gitlab-ci.yml to run a job say job3 when either job1 and job2 are success or when either of jobs, job1 or job2 are failed. Below is my code
stages:
 - job1
 - job2
 - job3

job1:
  script:
        ----some code

job2:
  script:
        ----some code
job3:
  script:
        ----some code

  needs: [job1 & job2, !job1 | !job2]

Can someone guide me on this?


text:
Q: Why the last element from a multi-dimensional array is not getting accessed in foreach loop and the last element gets repeated in following scenario? I've a multi-dimensional array titled $result. The contents of array are as follows :
//Output of print_r($result);
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [rsvp_id] =>
                    [is_liked] =>
                    [group_name] =>
                    [event_id] => 333
                )

            [1] => Array
                (
                    [rsvp_id] => 1
                    [is_liked] =>
                    [group_name] => CHE100
                    [event_id] => 332
                )

            [2] => Array
                (
                    [rsvp_id] =>
                    [is_liked] =>
                    [group_name] =>
                    [event_id] => 294
                )

            [3] => Array
                (
                    [rsvp_id] =>
                    [is_liked] =>
                    [group_name] =>
                    [event_id] => 297
                )

            [4] => Array
                (
                    [rsvp_id] =>
                    [is_liked] =>
                    [group_name] =>
                    [event_id] => 296
                )

            [5] => Array
                (
                    [rsvp_id] =>
                    [is_liked] =>
                    [group_name] =>
                    [event_id] => 298
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [rsvp_id] => 1
                    [is_liked] =>
                    [group_name] =>
                    [event_id] => 334
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [rsvp_id] => 1
                    [is_liked] =>
                    [group_name] => CHE100
                    [event_id] => 336
                )

        )

    [3] => Array
        (
            [0] => Array
                (
                    [rsvp_id] => 2
                    [is_liked] =>
                    [group_name] => Student Organisation
                    [event_id] => 239
                )

        )

)

Now I'm trying to iterate over the above array in foreach loop and printing the key value as follows :
foreach ($result as $i => $key) {
  print_r($key); echo "
";
}
die;

It prints following output :
Array
(
    [0] => Array
        (
            [rsvp_id] =>
            [is_liked] =>
            [group_name] =>
            [event_id] => 333
        )

    [1] => Array
        (
            [rsvp_id] => 1
            [is_liked] =>
            [group_name] => CHE100
            [event_id] => 332
        )

    [2] => Array
        (
            [rsvp_id] =>
            [is_liked] =>
            [group_name] =>
            [event_id] => 294
        )

    [3] => Array
        (
            [rsvp_id] =>
            [is_liked] =>
            [group_name] =>
            [event_id] => 297
        )

    [4] => Array
        (
            [rsvp_id] =>
            [is_liked] =>
            [group_name] =>
            [event_id] => 296
        )

    [5] => Array
        (
            [rsvp_id] =>
            [is_liked] =>
            [group_name] =>
            [event_id] => 298
        )

)

Array
(
    [0] => Array
        (
            [rsvp_id] => 1
            [is_liked] =>
            [group_name] =>
            [event_id] => 334
        )

)

Array
(
    [0] => Array
        (
            [rsvp_id] => 1
            [is_liked] =>
            [group_name] => CHE100
            [event_id] => 336
        )

)

Array
(
    [rsvp_id] => 1
    [is_liked] =>
    [group_name] => CHE100
    [event_id] => 336
)

You can observe from the above output that the last element
Array
    (
        [rsvp_id] => 1
        [is_liked] =>
        [group_name] => CHE100
        [event_id] => 336
    )

is repeated.
The actual final array output should be as follows :
Array
(
    [0] => Array
        (
            [rsvp_id] =>
            [is_liked] =>
            [group_name] =>
            [event_id] => 333
        )

    [1] => Array
        (
            [rsvp_id] => 1
            [is_liked] =>
            [group_name] => CHE100
            [event_id] => 332
        )

    [2] => Array
        (
            [rsvp_id] =>
            [is_liked] =>
            [group_name] =>
            [event_id] => 294
        )

    [3] => Array
        (
            [rsvp_id] =>
            [is_liked] =>
            [group_name] =>
            [event_id] => 297
        )

    [4] => Array
        (
            [rsvp_id] =>
            [is_liked] =>
            [group_name] =>
            [event_id] => 296
        )

    [5] => Array
        (
            [rsvp_id] =>
            [is_liked] =>
            [group_name] =>
            [event_id] => 298
        )

)

Array
(
    [0] => Array
        (
            [rsvp_id] => 1
            [is_liked] =>
            [group_name] =>
            [event_id] => 334
        )

)

Array
(
    [0] => Array
        (
            [rsvp_id] => 1
            [is_liked] =>
            [group_name] => CHE100
            [event_id] => 336
        )

)

Array
(
    [0] => Array
        (
            [rsvp_id] => 2
            [is_liked] =>
            [group_name] => Student Organisation
            [event_id] => 239
        )

)

I'm not understanding why the last element([0][event_id] => 239) is not getting accessed and the last element([event_id] => 336) gets repeated.
Can you please help me in correcting the mistake I'm making in foreach loop iteration or any other mistake I'm making.
Thanks.


text:
Q: How to divide train and test datasets into ratios in R for a decision tree? Here's the instructions in the homework and I have two separate code implementations but I'm having trouble interpreting what the instructions are asking:
Use the following ratios to divide the data set;
a) 50 train: 50 test
b) 75 train: 25 test
c) 25 train: 75 test
d) 85 train: 15 test
The parameter SplitRatio in sample.split is confusing me, I've checked the documentation but it's not clear to me what it does, it looks like a percentage of success to me to determine true or false for the decision tree. Question: do I make SplitRatio 0.5 to have a 50 train, 50 test ratio or do I just have the dataset itself modified to include a random seed of 50 rows, 75, 25, etc.? I have SplitRatio set to 0.9 here and the dataset itself is modified to only include 50 entries. If I change it to 0.5 it dramatically changes the decision tree, same thing if I include the entire dataset instead of 50.
#---------------------------------
#    Ratio 50 Train : 50 Test
#---------------------------------

set.seed(1)
set50 <- sample(nrow(cancerdata), 50, replace=FALSE)
#set50

cancerset5050 <- cancerdata[set50,]
cancerset5050

?sample.split

spl = sample.split(cancerset5050$study.Diagnosis, SplitRatio = 0.9)
spl

dataTrain = subset(cancerset5050, spl==TRUE)
dataTest = subset(cancerset5050, spl==FALSE)

m5050 <- J48(as.factor(study.Diagnosis)~., dataTrain)

summary(m5050)

## visualization the model
## use partykit package
if(require("partykit", quietly = TRUE)) plot(m5050)

dataTest.pred <- predict(m5050, newdata = dataTest)
table(dataTest$study.Diagnosis, dataTest.pred)

A: I think your understanding of sample.split function is correct. If you set SplitRatio = 0.5, then you will have 50% of the samples in training set, and the remaining 50% in the test set as you have done it.
I think you should convert your response variable to factor before you separate the training and test sets.
That is
cancerset5050$study.Diagnosis <- as factor(cancerset5050$study.Diagnosis)

And the move on to train and test
dataTrain = subset(cancerset5050, spl==TRUE)
dataTest = subset(cancerset5050, spl==FALSE)

m5050 <- J48(study.Diagnosis ~., dataTrain)


text:
Q: Sorting the float data in the Array of dictionary in iPhone? I am having the array of Dictionary and it's in the formats of,
 resultsArray = {

id = 1;
name = test;
distance = 11.5;

id = 2;
name = test1;
distance = 0.5;

id = 3;
name = test2;
distance = 2.5;

id = 4;
name = test4;
distance = 1.5;

}
I want to sort the array using the distance key and my distance in the float type. So how can i sort the array using distance is in the ascending order?.
So i am expecting the results like this,
resultsArray = {

id = 2;
name = test1;
distance = 0.5;

id = 4;
name = test4;
distance = 1.5;

id = 3;
name = test2;
distance = 2.5;

id = 1;
name = test;
distance = 11.5;

}

Please help me out.
Thanks!

A: NSArray *sortedArray = [resultsArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"distance" ascending:YES]]];

A: [resultArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [[obj1 objectForKey:@"distance"] compare:[obj2 objectForKey:@"distance"]];
}];

A: And one more solution:
@interface NSDictionary(sortingByDistance)
-(NSComparisonResult) compareByDistance:(NSDictionary*)dict;
@end
@implementation NSDictionary(sortingByDistance)
-(NSComparisonResult) compareByDistance:(NSDictionary*)dict {
    return [[self objectForKey:@"distance"] compare:[dict objectForKey:@"distance"]];
}
@end

Now to sort array you can use sortUsingSelector method:
[resultArray sortUsingSelector:@selector(compareByDistance:)];


text:
Q: Embedding YouTube on CartoDB infowindows I am embedding my CartoDb as follows
$('#map').ready(function(e){
    cartodb.createVis('map', '//internetadventureclub.cartodb.com/api/v2/viz/617ba774-fd8c-11e4-9e57-0e4fddd5de28/viz.json', {https: true});
  });

How can i enable sanitizeTemplate:false in the above so that the YouTube Video can be played in the infowindow of CartoDB

A: Here you have an example of sanitization by using createViz:
 cartodb.createVis('map', 'viz.json', { description: true, search: true, shareable: true })
      .on('done', function(vis,layers) {

        var layer = layers[1].getSubLayer(0);
        //layer.infowindow.set('template', $('#infowindow_template').html());
        layer.infowindow.set('sanitizeTemplate', 'false');

        layer.on('error', function(err) {
          console.log('error: ' + err);
        });

      }).on('error', function() {
        console.log("some error occurred");
      });


text:
Q: Delete lines in a file by piping search pattern into Sed Is there anyway we can delete lines in a file like below.
grep {SearchPattern} {file} | cut -c 1-9 | Sed {file}
Whatever I am searching can actually occur fewer than lines I want to delete.
I want to actually search and take first 9 char and search again and delete whatever lines come in output.
my input file would like as below .
0002206993022      Enrollment Status             Terminated                              08/01/201412/31/9999
0003119343022      Enrollment Status             Terminated                              05/28/201512/31/9999
0003119343009999   Pay Status                    N/A                                     09/10/201405/28/2015

you can I would to search for all "Terminated" persons and take their IDs by taking first 9 digits in the first column. I would like to delete all of their records be it Pay Status or Enrollment Status or whatever

A: You want something like this:
awk '/Terminated/{$0=substr($0, 1, 9);print "^" $0}' file | grep -vf - file

Update:
Try (Non GNU grep):
awk '/Terminated/{$0=substr($0, 1, 9);print "^" $0}' file | grep -vf /dev/stdin file

Test:
$ cat file
0002206993022      Enrollment Status             Terminated                              08/01/201412/31/9999
0003119343022      Enrollment Status             Terminated                              05/28/201512/31/9999
0003119343009999   Pay Status                    N/A                                     09/10/201405/28/2015
1003119343009999   Pay Status                    N/A                                     09/10/201405/28/2015

$ awk '/Terminated/{$0=substr($0, 1, 9);print "^" $0}' file | grep -vf - file
1003119343009999   Pay Status                    N/A                                     09/10/201405/28/2015


text: Q: Почему в Linux Mint все папки в директории стали READ ONLY? Такая проблема, поставил на ноутбук рядом с виндой Linux Mint. И там есть жесткий диск D (остался с виндовса) который на файловой системе NTFS. Так вот вчера все файлы на данном диске были полностью доступны и с винды и с пингвина, а сегодня на Linux зашел и в этой директории все файлы и папки стали типа READ ONLY. В чем может быть проблема?? Эти файлы мне нужны в полном доступе на обеих ОС, да и с этим проблем не было до сегодня. Никакие права доступа и файловую систему не изменял. Так как все изначально работало то наверное проблема в чем то другом?? Спасибо.


text:
Q: ASP.NET MVC 4/Web API - How to configure SQL Server to allow access to API calls from a URL in browser? I have a server with a SQL Server 2012 Express database. I am authenticated to connect to it and am using it as the backend for an ASP.NET MVC 4 application.
With this application I'm also developing an API. Calling the API programmatically using jQuery within my own application works fine. Querying the database to get the information works as well.
However, when I run the application from VS2010 and try accessing the API by using a URL that would access the database, I get an HTTP 500 Error.
Just to make sure this issue isn't on my application's end, I then modified the API resource so it gets a local array (instead of information from the database) and when I hit the same URL, it returned the information in XML form on the localhost page.
The problem seems to be that the URL call to the API attempts to connect to the database not as the authenticated user (me), but from the browser.
How can I configure SQL Server to allow a URL call to the API in the browser to access the database and return the data in JSON/XML form? (eg. like you can do with the Twitter REST API)
UPDATE:
Debugging output on HTTP Request:
Request URL:http://localhost:5555/api/Performance/ShowMachines
Request Method:GET
Status Code:500 Internal Server Error
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:localhost:5555
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11
Response Headersview source
Cache-Control:private
Connection:Close
Content-Length:0
Date:Thu, 02 Aug 2012 16:40:11 GMT
Server:ASP.NET Development Server/10.0.0.0
X-AspNet-Version:4.0.30319

A: change the connection string to
<add name="PerfMonDataConnectionString" connectionString="Data Source=cloud\sqlperf,1433;Initial Catalog=PerfMonData;User=myusername;Password=mypassword providerName="System.Data.SqlClient" />

and ensure that whatever the user account is has permission to the database.
This may or not be the best way depending on your security requirements
Also the user/password keys are off the top of my head it may be UserId, www.connectionstrings.com is your friend

A: I resolved the issue and answered it here:
C#/ASP.NET - Calling Web API operation via URL? : HTTP Error 500
The issue was that when I created the .dbml file, and dragged and dropped the table into it, the automatically generated DataContext class created EntitySet objects to represent the foreign-key relationships. I created simple classes with gets sand sets to return the JSON, rather than the classes in the DataContext, excluding the EntitySet objects. As a result, it worked like a charm. Apparently EntitySets are not serializeable, and thus were giving the 500 Error.


text:
Q: Resize grayscale image by summing pixel intensities for every 2x2 grid I have a dataset of 36,000 tif images (grayscale, 16-bit) each of size 2048 x 2048 pixels. I want to resize them to 1024 x 1024 pixels by adding the intensities at each 2x2 grid to generate the intensity at each pixel in the resized image. I need to do this in Python. I have been doing this using ImageJ with Image>Transform>Bin, method = Sum. I cannot find a Python library which does this. Any help is appreciated. Thank you.

A: block_reduce from skimage_measure worked for me. Here's the code snippet:
import numpy as np
from skimage.measure import block_reduce
import skimage.io as tiffio

#read original 2k x 2k image
original_image = tiffio.imread(read_path+"/RawImage_00000.tif", plugin = 'tifffile')
#bin image by factor of 2 along both axes, summing pixel values in 2x2 blocks
sum2bin_image = block_reduce(original_image, block_size=(2, 2), func=np.sum)
#Numpy arrays are 64-bit float variables, so the following step restores the original unsigned 16-bit format
sum2bin_image = np.round(sum2bin_image).astype(np.uint16)
#save generated image
tiffio.imsave(save_path+'/'+'sum2bin_00000.tif', sum2bin_image, plugin='tifffile')


text:
Q: How to get dataset from prepare_data() to setup() in PyTorch Lightning I made my own dataset using NumPy in the prepare_data() methods using the DataModules method of PyTorch Lightning. Now, I want to pass the data into the setup() method to split into training and validation.
import numpy as np
import pytorch_lightning as pl
from torch.utils.data import random_split, DataLoader, TensorDataset
import torch
from torch.autograd import Variable
from torchvision import transforms

np.random.seed(42)

device = 'cuda' if torch.cuda.is_available() else 'cpu'

class DataModuleClass(pl.LightningDataModule):
    def __init__(self):
        super().__init__()
        self.constant = 2
        self.batch_size = 10

    def prepare_data(self):
        a = np.random.uniform(0, 500, 500)
        b = np.random.normal(0, self.constant, len(a))

        c = a + b
        X = np.transpose(np.array([a, b]))

        # Converting numpy array to Tensor
        self.x_train_tensor = torch.from_numpy(X).float().to(device)
        self.y_train_tensor = torch.from_numpy(c).float().to(device)

        training_dataset = TensorDataset(self.x_train_tensor, self.y_train_tensor)

        return training_dataset

    def setup(self):
        data = # What I have to write to get the data from prepare_data()
        self.train_data, self.val_data = random_split(data, [400, 100])

    def train_dataloader(self):
        training_dataloader = setup() # Need to get the training data
        return DataLoader(self.training_dataloader)

    def val_dataloader(self):
        validation_dataloader = prepare_data() # Need to get the validation data
        return DataLoader(self.validation_dataloader)

obj = DataModuleClass()
print(obj.prepare_data())

A: The same answer as your previous question...
def prepare_data(self):
    a = np.random.uniform(0, 500, 500)
    b = np.random.normal(0, self.constant, len(a))

    c = a + b
    X = np.transpose(np.array([a, b]))

    # Converting numpy array to Tensor
    self.x_train_tensor = torch.from_numpy(X).float().to(device)
    self.y_train_tensor = torch.from_numpy(c).float().to(device)

    training_dataset = TensorDataset(self.x_train_tensor, self.y_train_tensor)

    self.training_dataset = training_dataset

def setup(self):
    data = self.training_dataset
    self.train_data, self.val_data = random_split(data, [400, 100])

def train_dataloader(self):
    return DataLoader(self.train_data)

def val_dataloader(self):
    return DataLoader(self.val_data)

A: Simply call setup() on your DataModule object after calling prepare() on that object.  So:
dm = DataModuleClass()
dm.prepare_data()
dm.setup()


text:
Q: How can I pick single record from one to many relation? I have one to many relation based two tables users and games and there is also bridge table users_games (linking user_id to games).
I want to fetch a single record from games table based on provided game_id for specific user. I did some research and found whereHas() which is returning all games which are belongs to specific user. But I need to fetch one based on game_id. Can some one kindly let me know how can I fix issue in below script
$GameInfo = User::with('games')->whereHas('games', function ($query) use($request)
            {
                $query->where('game_id', '=', $request->game_id);
            })->find(request()->user()->id);

A: Is this what you're trying to do?
$GameInfo = $request
            ->user()
            ->games()
            ->where('game_id', $request->game_id)
            ->first();

A: If your relation 'games' is a hasMany() with table 'users_games', You can try this code
$GameInfo = User::with(['games' => function ($query) use($request)
        {
            $query->where('game_id', $request->game_id);
        }])
        ->where('users.id', <user_id_variable>)
        ->first();

And the relation 'games' in User Model as
public function games()
{
    return $this->hasMany('App\Models\UserGames', 'user_id', 'id');
}

A: try this:
$GameInfo = User::with(['games' => function ($query) use($request)
    {
        $query->where('game_id', $request->game_id);
    }])->whereHas('games', function ($query) use($request)
        {
            $query->where('game_id', '=', $request->game_id);
        })->find(request()->user()->id);


text:
Q: Как правильно отобразить данные из @extends в laravel? Такая вот проблема есть у меня файл layouts которые подключаю с помощью @extends() но вот отображаются эти файлы в обратном порядке. Данные второго файла показываются первыми а данные первого файла последними. Как с этим быть? Благодарю заранее     @extends('layouts.header')

A: не наследуйтесь от headera, сделайте 1 главный шаблон в котором будет включен хедер и футер, и наследуйтесь от него всеми остальными файлами. К примеру
  <body>

        @include('header')

        @yield('content')

        @include('footer')

    </body>

и затем в каком либо другом наследуемом файле
@extends('layout')

@section('content')
  //ваш html код
@endsection`

Вот здесь можно прочитать об этом https://laravel.com/docs/5.5/blade


text:
Q: Is it good to place a paper on a table and keep the laptop over it?Would it cause heat problems? I want to know whether it is alright to place a laptop over a table laid with paper as its tablecloth?

A: It is perfectly safe.  As long as the paper (or anything) doesnt block the air input or output vents on the laptop.  Additionally, the laptop isnt capable of blowing out air hot enough to damage the paper, or anything else.


text:
Q: i am developing an app with node js , it works perfectly locally but crashes anytime i try to upload it to heroku,it says cat find dotenv i am developing an app with node js , it works perfectly locally but crashes anytime i try to upload it to heroku,it says Error: Cannot find module 'dotenv.i have installed it serval times and also updated my package but the problem continues,
this is my package.json
{
  "name": "myapp",
  "description": "a really cool app",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "engines": {
    "node": "10.16.3",
    "npm": "6.13.4"
  },
  "dependencies": {
    "@mapbox/mapbox-sdk": "^0.9.0",
    "body-parser": "^1.19.0",
    "cookie-parser": "~1.4.4",
    "debug": "~4.1.1",
    "ejs": "~3.0.1",
    "ejs-mate": "^3.0.0",
    "express": "^4.17.1",
    "express-session": "^1.17.0",
    "faker": "^4.1.0",
    "http-errors": "~1.7.3",
    "method-override": "^3.0.0",
    "mongoose": "^5.8.1",
    "mongoose-paginate": "^5.0.3",
    "morgan": "~1.9.1",
    "passport": "^0.4.1",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^5.0.1",
    "serve-favicon": "^2.5.0"
  },
  "devDependencies": {
    "dotenv": "^8.2.0",
    "locus": "^2.0.4"
  }
}

this is my Procfile
web: node app.js
this is my git ignore file
/node_modules
.DS_Store
/*.env

A: Try movin dotenv from 'devDependencies' to 'dependencies'
Anything that is needed to actually run your app (lets call it "in production"), should be in 'dependencies'.
Anything that you may need while eg testing can be installed to 'devDependencies'


text:
Q: Minimum RBAC permission needed to view all Azure Container Groups within the Resource Group? My logic app creates new container groups within same Resource Group. I have contributor RBAC role on logic app, but I don't have any RBAC role at Resource Group level. What RBAC role should I ask so that I can view all Azure Container Groups that get created by logic app in resource group? or do I need to define any custom role?
We follow least permission model, so I will not get straight away 'Reader' / 'Contributor' role on Resource group for this.

A: Looks like operations are directly not available in built-in RBAC permissions .You may have to create custom role for the required operations .

*

*To create a custom role, check out the actions that are available to define your permissions for the container groups and create custom role from scratch.

Create a JSON file with actions and not actions declared.
Azure resource provider operations | Microsoft Learn
JSON:
{
   "assignableScopes": [
     "/subscriptions/<this is optional : you may limit the visibility to one or more subscriptions>"
   ],
   "description": "Get all the Container groups",
   "Name": "Read",
   "permissions": [
     {
       "actions": [
         "Microsoft.ContainerInstance/containerGroups/read",
         "Microsoft.ContainerInstance/containerGroupProfiles/read",
         ...

       ],
       "dataActions": [],
       "notActions": [],
       "notDataActions": []
     }
   ],
   "roleType": "CustomRole"
 }

Reference: Create or update Azure custom roles using the Azure portal - Azure RBAC | Microsoft Learn


text:
Q: Is it possible to record/screenshare on a kvm (with qemu) virtual machine to a host without a capture card I'm getting a pc today and I'm interested if it's possible to screenshare to (on discord) the virtual machine's screen to a host if i use kvm. I use linux now but my computer is nowhere good enough for me to be able to test it so I'm here to ask if it's 1. it's possible and 2. how to do it. preferably without a capture card or anything like that.

A: yes you can share the guest with any swoftware that can share/record windows or sections on your screen.
I've used recordmydesktop to capture videos of guests as well as sharing them via google meet.
I can't tell you how to do things in discord, but from a qemu/kvm perspective just use virt-manager or virt-viewer to view your guest which will give you a window which inside holds what the guest thinks is the full screen.
Then use your screen sharing/recording software to share that window or that area of your overall desktop.


text:
Q: Why irradiated color CMOS sensor shows white (not color) dots? I exposed CMOS imaging sensor (OmniVision OV2710) to radiation from Radium watch dial, through 2 glass layers (test tube + IR-cut filter, so all low energy particles were filtered out).
On the image that was captured over 2 minutes - there are some dots and lines caused by radiation which is expected. But they all white. Is there any explanation why they are white?
I expected that particles hitting R,G,B subpixels should cause color noise. Pixels are not clipped - some marks are far from 255 value. Also, I noticed that dots are typically larger than 1 pixel - does that mean that interaction volume is larger than 3x3µm (pixel size of OV2710)?


text:
Q: What is water pressure, really? It's easy for me to imagine gas pressure on a molecular level. More pressure means that more molecule bounce against the thing you are measuring, or the molecules hit it with more speed or the molecules are heavier.
But I can not imagine how water pressure works on a molecular level. Water is not compressible, so there can not be more water molecules per volume to increase pressure. But if the velocity increases, this should also increase the water temperature. However the bottom of a pool of water is not hotter than the surface. So I just don't understand it.

A: The fundamental difference between a liquid and an ideal gas is that in the gas, the molecules fly around free and only occasionally and briefly interact with each other, whereas in a liquid, the molecules are close enough together that they are always within the electromagnetic fields of their neighbors.  If two molecules in a liquid move apart a bit, there is a weak electromagnetic attractive force between them. If they move a bit closer together, there arises a repulsive force between them that grows rapidly as the separation decreases.  So it doesn't take much compression (but some) for the pressure to increase markedly.  Though things at the molecular scale are governed by quantum mechanics, it is fair to imagine a little free-body diagram for a molecule of water which is closest to the "thing you are measuring".  There would be a force on the molecule from the "thing", but also forces, on the whole in the opposite direction, from the neighboring molecules.