text:
Q: Retrieving specific properties from value of ObjectResult I am calling a HTTP endpoint which returns the follow below as an ObjectResult (variable name = Food):
{
"fruit": "apple",
"vegetable": "carrot",
"meat": "steak"
}

Within Food, of type ObjectResult, how do I return the value of... let's say fruit?
I would like the output to be "fruit": "apple"
It looks like these values are within Food.Value. However, I can't pick specific properties (Fruit) from them.
Any help is appreciated.

A:
Within Food, of type ObjectResult, how do I return the value of... let's say fruit?

If you'd like to get data from an ObjectResult, you can refer to the following code snippet.
var objresult = new ObjectResult(Food);

dynamic data = objresult.Value;
var fruit = data.fruit;

Test Result


text:
Q: Geometric series $\sum_{n=0}^\infty x^n$ when $x=0$ The infinite geometric series $\sum_{n=0}^\infty x^n=\frac{1}{1-x}$ and so is convergent for $|x|<1$.
While working on a trigonometry problem I came across the case of what happens when $x=0$. Clearly the sum is $1$ with the convention $0^0=1$ (this convention is discussed in several threads here on MathSE).
However Wolfram Alpha says about $\sum_{n=0}^\infty 0^n$:

(sum does not exist due to singularity at one or more evaluation points)
By the geometric series test, the series diverges.

My assumption is that Wolfram Alpha doesn't know what to do with $0^0$. There have also been several threads on MathSE about various ways in which Wolfram Alpha fails or uses certain unstated conventions.
Is there something else I am missing?
Ultimately I am interested in $\sum_{n=0}^\infty (\arctan(\sin(\theta)))^n$ (which is not hard to analyze), and had a problem evaluating it at $\theta=0$ on Wolfram Alpha. I'm including this problem on an upcoming test, so I wan't to make sure I wasn't overlooking anything. I suppose I could just start at $n=1$ to avoid any possible issue.

EDIT: The answer was provided by @Masacroso in the first comment below. See indeterminate forms on Wolfram Alpha. Wolfram Alpha does indeed consider $0^0$ to be undefined.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fail to start application debugging - combined C/java android application in Eclipse NDK_LOCATION is set correctly. The ndk-build command finishes fine and I can see the library in /libs/areabi-v7a - I tried also building all platforms but the message remains. The app doesn't start with this message in eclipse console:
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] Android
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] NDK:
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] Could
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] not
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] find
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] platform
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] files
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] (headers
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] and
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] libraries)
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient]
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient]
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient]
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient]
Android
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] NDK:
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] Please
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] run
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] build/tools/gen-platforms.sh
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] to
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] build
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] the
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] corresponding
[2014-02-26 15:56:16 - fgeclient] Unknown Application ABI:
[2014-02-26 15:56:16 - fgeclient] directory.
[2014-02-26 15:56:16 - fgeclient] Unable to detect application ABI's

Before I converted app to combined java/C++ project in eclipse I was able to run it (I was building the native part manually) though I was getting errors at native level - hence my attempt to debug it.
My environment is Win7/Cygwin.
As for suggestion to run build/tools/gen-platforms.sh - this script is used for generating debugging libraries for kernel android stuff (and that is already prebuild and included as part of ndk)
Does anyone have any suggestions how to fix it ?
I tried at home and at work with the same result (that can mean I make the same mistake twice but it can be some systematic error)
For reference I've packed my project & uploaded here - http://ulozto.cz/xQurLAUV/fgeclient-zip

A: The logs showing here that ndk didn't find relevant ABI, Have to tried running build/tools/gen-platforms.sh script as prompted in logs.


text:
Q: virtual machine is stored is almost full yet Window C drive says 29GB free Getting message vmware has paused this virtual machine because the disk which virtual machine is stored iss almost full. to continue, free up 962 MB of disk space.
My Mac has over 160GB free. Bootcamp has 40GB but shows only 1GB free. VMware virtual machine COPY has 5 GB and VMware virtual machine has 25GB. Yet when I go into VMware vitual machine the C drive says 40GB size and 11GB used with 29GB free. Where do I free up space??

A: To avoid file system free space percentage, the following forum refers to an advanced parameter to add in the VMX text configuration file:
mainMem.freeSpaceCheck = "FALSE"

But then you have to be careful to have enough free space, maybe with another tool to check it for you.
Another option is to use "shrink" action, that will reclaim unused space from the disk image. But not all virtual disk image types support "shrinking" and that operation may require at least 2 GiB free space or at worst the same disk image size itself.
I recommend the virtual disk type "1 : growable virtual disk split in 2GB files" to ease disk management. VMWare Virtual Disk Manager tools is useful to create, grow and convert image disks. It is available in Workstation product or as a standalone executable in VMWare Server.

A: Try the option in VMware to "shrink" your disk.  I believe it will reclaim unused space.


text:
Q: TextBox's text not changing in from upload_complete event handler I have the following code in AsyncFileUpload's upload complete event handler:
Protected Sub AsyncFileUpload1_UploadedComplete(ByVal sender As Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs) Handles AsyncFileUpload1.UploadedComplete

    Dim oapp As Excel.Application
    Dim oWBa As Excel.Workbook
    Dim oWS As Excel.Worksheet
    Dim oRng As Excel.Range
    oapp = New Excel.Application
    AsyncFileUpload1.PostedFile.SaveAs(Server.MapPath("tempfile2.xlsx"))
    oWBa = oapp.Workbooks.Open(Server.MapPath("tempfile2.xlsx"))
    oWS = DirectCast(oWBa.Worksheets(2),
    Excel.Worksheet)
    'Here tns is a textbox contained in a panel
    tns.Text = Integer.Parse(oWS.Range("W44").Value) + Integer.Parse(oWS.Range("W55").Value)
    oWBa.Close()

    File.Delete(Server.MapPath("tempfile2.xlsx"))
End Sub

The autopostback property of tns is turned on so why does it not change its text when a file is uploaded? Also there is no question of error in logic of reading the excel file because I have debugged it using VS 2010 and Uptil the line tns.text..., I get the correct value in the watch.So how shall I get round it?

A: Replace setting of tns.Text property in AsyncFileUpload1_UploadedComplete with code below:
var resultString = Integer.Parse(oWS.Range("W44").Value) + Integer.Parse(oWS.Range("W55").Value);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "result", "top.$get(\"" + tns.ClientID + "\").value = '" + resultString + "';", true);

P.S. this workaround and a lot of other you can find in the AjaxControlToolkit sample site available for download from codeplex


text:
Q: Using boost::mpl::lambda to remove types from a boost::mpl::list based on static const member variable I have a list of types defined as:
typedef boost::mpl::list<Apple, Pear, Brick> OriginalList;

I would like to create a second list that does not contain any fruit, i.e. the resultant list formed from the first list would contain a single type Brick. Fruit is identified through a static const variable defined within the types, e.g.:
struct Apple
{
    static const bool IsFruit = true;
};

I currently have a solution that involves creating a meta-function class, and using boost::mpl::remove_if. I believe I should be able to make this more elegant by using boost::mpl::lambda to remove the need for the separate RemoveFruit struct. Any suggestions on how to do this?
Full code as it currently stands:
include <boost/static_assert.hpp>
#include <boost/mpl/list.hpp>
#include <boost/mpl/remove_if.hpp>
#include <boost/mpl/size.hpp>

#include <iostream>

struct Apple
{
  static const bool IsFruit = true;
};

struct Pear
{
  static const bool IsFruit = true;
};

struct Brick
{
  static const bool IsFruit = false;
};

typedef boost::mpl::list<Apple, Pear, Brick> OriginalList;
BOOST_STATIC_ASSERT(boost::mpl::size<OriginalList>::type::value == 3);

// This is what I would like to get rid of:
struct RemoveFruit
{
  template <typename T>
  struct apply
  {
    typedef boost::mpl::bool_<T::IsFruit> type;
  };
};

// Assuming I can embed some predicate directly in here?
typedef boost::mpl::remove_if<
  OriginalList,
  RemoveFruit
  >::type NoFruitList;

BOOST_STATIC_ASSERT(boost::mpl::size<NoFruitList>::type::value == 1);

int main()
{
  std::cout << "There are " << boost::mpl::size<OriginalList>::type::value << " items in the original list\n";
  std::cout << "There are " << boost::mpl::size<NoFruitList>::type::value << " items in the no fruit list\n";

  return 0;
}

A: I think the best you can do is to define an IsFruit struct like
template  <typename T> struct isFruit : boost::mpl::bool_<T::IsFruit> {};

And then you can define your no-fruit list as
typedef boost::mpl::remove_if<
  OriginalList,
  boost::mpl::lambda< isFruit< boost::mpl::_1 > >::type
  >::type NoFruitList;

The additional struct is needed to get access to the IsFruit field in your classes.
Note that if you want to get rid of the additional struct entirely, you'll have to rename the boolean members of your other classes.  If you follow the boost::mpl convention and call them value instead of IsFruit, you can define NoFruitList as
typedef boost::mpl::remove_if<
      OriginalList,
      boost::mpl::lambda<boost::mpl::_1>::type
      >::type NoFruitList;


text:
Q: Error running Hello World in main.dart The following error shows up when i'm trying to run the hello world default code when you create a project in with project type: Dart Chrome App
[error] Can't read 'package:chrome/chrome_app.dart' (ChromeService error: Could not resolve reference: package:chrome/chrome_app.dart
the code is as follow:
import 'dart:html';

import 'package:chrome/chrome_app.dart' as chrome;

int boundsChange = 100;
int count = 0;

void main() {
  querySelector('#text_id').onClick.listen(resizeWindow);
}

void resizeWindow(MouseEvent event) {
  chrome.ContentBounds bounds = chrome.app.window.current().getBounds();

  bounds.width += boundsChange;
  bounds.left -= boundsChange ~/ 2;

  chrome.app.window.current().setBounds(bounds);

  boundsChange *= -1;

  querySelector("#count").text = (count++).toString();
}


text:
Q: creating a sorted list in database So basically I have a table named contents where users can store their items. Normally here when a user add a new item, The item is added at the end of rows.
Something like:
|ID | Name | Item  |
--------------------
|1 | Jack  | pen   |
|2 | Mark  | apple |
|3 | albert| orange|
|4 | Jack  | pencil|

But the problem with above is that it might take a lot of time when we have a lot of users and items like Jack's first item is at row ID 40 and item #2 is at 1000048 and so which might take a while to search for all the items that belongs to Jack So I was wondering how to sort them up by their Name so it could be something like:
|ID | Name | Item  |
--------------------
|1 | Jack  | pen   |
|2 | Jack  | pencil|
|3 | Mark  | apple |
|4 | albert| orange|

And if the user added a new item it should be added to the end of his rows list.
All replies are much appreciated, Thank:)

A: Add index(es) for any column (or combination of columns) you want to search for and/or want to order by.
Do not reorder the table, nor re-number the ids.
If you are talking about 1000 rows, you are unlikely to notice any performance problems even if you don't do proper indexing or normalization.  With a million rows, you will notice.


text:
Q: How to change SKscene size every time i run my app in my simulator the view scale always comes out to 768,1024 how do you change this to 1024,768. here is the default size code
    class GameViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()

    if let scene = GameScene(fileNamed:"GameScene") {
        // Configure the view.
        let skView = self.view as! SKView
        skView.showsFPS = true
        skView.showsNodeCount = true

        /* Sprite Kit applies additional optimizations to improve
rendering performance */
        skView.ignoresSiblingOrder = true

        /* Set the scale mode to scale to fit the window */
        scene.scaleMode = .AspectFill

        skView.presentScene(scene)
    }
}

A: 1) If you use .sks files (the spriteKit visual editor)
Just go to the GameScene.sks file (not swift) in you project where  you can change the scene size in the inspector on the right.
You can check this article here where they show this if you scroll down a tiny bit. Its a good tutorial you should ready if you plan on working with the visual editor.
https://www.raywenderlich.com/118225/introduction-sprite-kit-scene-editor
2) Not using .sks files, loading scenes in code
If you dont use .sks files you can delete the GameScene.sks file and load the scene like so.
 override func viewDidLoad() {
super.viewDidLoad()

    // Configure the view.
    guard let skView = self.view as? SKView else { return }

    let scene = GameScene(size: CGSize(width: 1920, height: 1080))

    skView.showsFPS = true
    skView.showsNodeCount = true

    /* Sprite Kit applies additional optimizations to improve rendering performance */
    skView.ignoresSiblingOrder = true

    scene.scaleMode = .AspectFill

    skView.presentScene(scene)
  }

Hope this helps


text:
Q: Powershell Error: The string is missing the terminator: ". / The string is missing the terminator: "@ When running the following code, either in ISE or Powershell window:
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$username="username"
$password="password"
$credPair = "$($username):$($password)"
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credPair))

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("content-type", "application/vnd.emc.apollo-v1+xml")
$headers.Add("Authorization", "Basic $encodedCredentials")

$body = "<runReportParameters>
`n<report>
`n<name>Report Namer</name>
`n</report>
`n<nodes>
`n<node>
`n<id>1a5e8e1a-2c47-449f-a8d4-535549fe1d69</id>
`n</node>
`n</nodes>
`n<timeConstraints type=`"window`">
`n<window>
`n<name>Last Day</name>
`n</window>
`n</timeConstraints>
`n<formatParameters>
`n<formatType>CSV</formatType>
`n</formatParameters>
`n</runReportParameters>"

[string]$response = ""
[string]$pattern = ""
[string]$url = ""

$response = Invoke-WebRequest -UseBasicParsing -Uri 'https://<hostname>:<port>/api/report' -Method 'POST' -Headers $headers -Body $body

$pattern = "<link>(.*)</link>"
$url = [regex]::match($response, $pattern).Groups[1].Value

Invoke-RestMethod "$url" -Method GET -Headers $headers

It fails with the following errors:

PSMessageDetails      : Exception             : System.Net.WebException: The remote server returned an error: (503)
Server Unavailable.
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest
request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
TargetObject          : System.Net.HttpWebRequest CategoryInfo
: InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest)
[Invoke-RestMethod], WebException FullyQualifiedErrorId :
WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
ErrorDetails          :
https://:/api/report/result/8179ad5b-e6f8-4964-8e4f-8233df6656a2
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at , : line 1
PipelineIterationInfo : {} Errors                      : Message
: The string is missing the terminator: ". ErrorRecord
: The string is missing the terminator: ". WasThrownFromThrowStatement
: False Data                        : {} InnerException              :
TargetSite                  :
System.Collections.ObjectModel.Collection1[System.Management.Automation.PSObject] Invoke(System.Collections.IEnumerable) StackTrace                  :   at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input) at Microsoft.PowerShell.Executor.ExecuteCommandHelper(Pipeline tempPipeline, Exception& exceptionThrown, ExecutionOptions options) HelpLink                    : Source                      : System.Management.Automation HResult                     : -2146233087 Errors                      : Message                     : The string is missing the terminator: "@. ErrorRecord                 : The string is missing the terminator: "@. WasThrownFromThrowStatement : False Data                        : {} InnerException              : TargetSite                  : System.Collections.ObjectModel.Collection1[System.Management.Automation.PSObject]
Invoke(System.Collections.IEnumerable) StackTrace                  :
at
System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable
input)
at Microsoft.PowerShell.Executor.ExecuteCommandHelper(Pipeline
tempPipeline, Exception& exceptionThrown, ExecutionOptions options)
HelpLink                    : Source                      :
System.Management.Automation HResult                     : -2146233087
writeErrorStream      : True PSMessageDetails      : Exception
: System.IO.FileNotFoundException: The specified module 'PSReadline'
was not loaded because no valid module file was found in any module
directory. TargetObject          : PSReadline CategoryInfo          :
ResourceUnavailable: (PSReadline:String) [Import-Module],
FileNotFoundException FullyQualifiedErrorId :
Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
ErrorDetails          : InvocationInfo        :
System.Management.Automation.InvocationInfo ScriptStackTrace      :
PipelineIterationInfo : {0, 1, 0}

But, if I print the var $url a couple of times and then the Invoke-RestMethod, it works fine:
PS C:\Users\jump\Music> $url
https://<hostname>:<port>/api/report/result/15d56f05-b317-4cb5-8c36-59dc264ebf6f

PS C:\Users\jump\Music> Invoke-RestMethod "$url" -Method GET -Headers $headers
Server,Proxy,Job Count,GB Modified Sent
server1,proxy1,6,1.057
server2,proxy4,5,0.911
...

Any idea about the variable setup in ISE or Powershell??
Thank you.

A: Finally found the issue. The thing is that the report takes some time to be generated hence the error. Adding a "sleep" solved the issue, just before the GET method:
Start-Sleep -s 30
Invoke-RestMethod "$url" -Method GET -Headers $headers


text:
Q: Laravel policy view resource not triggered I have this route :
Route::Resource('/additional_role_countries', 'AdditionalRoleCountryController');

In the controller I have this authorization :
class AdditionalRoleCountryController extends Controller
{
    public function __construct() {
        $this->authorizeResource(AdditionalRoleCountry::class, 'additional_role_countries');
    }
}

And finally I have this policy for the model :
class AdditionalRoleCountryPolicy extends AbstractAuthorization
{
    use HandlesAuthorization;

    public function __construct()
    {
        var_dump('je suis dans le construct de la policy');
    }

    /**
     * Determine whether the user can view any additional role countries.
     *
     * @param  Member  $member
     * @return mixed
     */
    public function viewAny(Member $member)
    {
        //
    }

    /**
     * Determine whether the user can view the additional role country.
     *
     * @param  Member  $member
     * @param  AdditionalRoleCountry  $additionalRoleCountry
     * @return mixed
     */
    public function view(Member $member, AdditionalRoleCountry $additionalRoleCountry)
    {
        var_dump('titi');
        return true;
    }

    /**
     * Determine whether the user can create additional role countries.
     *
     * @param  Member  $member
     * @return mixed
     */
    public function create(Member $member)
    {
        return $this->isAuthorizedBranch($member);
    }
}

My problem is that all is running  fine for the POST (= create). It sends a 403 error if necessary.
BUT for a GET (= view), it is not working. It even never executes the __construct methods. And it returns directly a 403.
Why might this be happening?
Edit
I tried to change this :
$this->authorizeResource(AdditionalRoleCountry::class, 'additional_role_countries');

with this :
$this->authorizeResource(AdditionalRoleCountry::class);

And now it seems it is working for the post and the get. Does it mean that the second parameter is not mandatory ?

A: It does not work because you are passing the incorrect route parameter to authorizeResource.
Route::resource('additional_role_countries') generates the following route parameter
additional_role_country

but you are passing
additional_role_countries

The problem is that Laravel can not find the model corresponding to additional_role_countries but still runs a can check but returns false by default (403).

Solution
Removing the second parameter or changing it to additional_role_country should solve the problem.
$this->authorizeResource(AdditionalRoleCountry::class, 'additional_role_country');

$this->authorizeResource(AdditionalRoleCountry::class);

Why it worked for your store request
As you can see here Laravel does not use the second parameter for the methods index, create and store, instead it uses the Classname from the first parameter, in your case AdditionalRoleCountry.


text:
Q: Add an expandable text box to every post So I am building a comment system and have loaded a bunch of comments to a page, then have generated a reply box for each. Below is what my reply box looks like, but there are many identical ones on each page. As you can see, the first portion is a div that contains a toggle (show/hide) for the reply box.
I am posting because I cannot get the reply toggle to fire.
Here is my html:

        Reply

    <form class="form-horizontal" role="form" accept-charset='UTF-8' data-parsley-validate novalidate>
        <fieldset>

                    <textarea class="form-control" name="post-body" id="new_post_textarea" rows="5" cols="30" placeholder="Try to be as specific as possible when posting!"></textarea>

                    <button id="submit_reply_button" type="submit" class="btn btn-primary btn-block">Submit Reply</button>

        </fieldset>
    </form>

Here is my jquery:
$("#reply-toggle a").click(function() {
                alert("running");
                $('#reply-div').slideToggle("slow");
            )};

I recognize I am not very good in jquery, so I am sure it's something simple, however, I also recognize that I will have to use jquery(closest) to only toggle the reply box associated with the proper comment thread. I have not gotten to this step yet, but it would be greatly appreciated If I could receive some guidance in regards to that as well.
Sincere thanks for any help!

A: $(document).on('click', '#reply-toggle', function() {
    $(this).closest('.col-sm-offset-1').next('#reply-div').slideToggle('slow');
});

edit:added a period to the col-sm-offset-1 class

A: Your link selector does not match anything. $("#reply-toggle a") will return all  tags that have a parent with ID reply-toggle.
You should change this to simply $("#reply-toggle").
Edit: As an aside, you say you have multiple of these Reply buttons - I would strongly recommend you change the ID selector to a class selector as browsers expect only one element with a specific ID per page.

A: "#reply-toggle a" looks for  elements within an element that has id "reply-toggle". Maybe $("a#reply-toggle") would fix your firing issue?
You might want to generate a specific id for each reply toggle and div, say reply-toggle-1and reply-div-1. However, this approach needs a click()defined for each toggle. Use class declarations instead (i.e. not id="reply-toggle", but class="reply-toggle").


text:
Q: xml parser in python for xbmc I would like to get your help with my .py script.
I'm using xml file to store the parser path for the images.
Here's the xml file that I use:
<?xml version="1.0" encoding="utf-8"?>
<window type="dialog">
    <allowoverlay>no</allowoverlay>
<coordinates>
<system>1</system>
<posx>0</posx>
<posy>0</posy>
</coordinates>

<controls>
    <control type="image" id="1">
       <posx>0</posx>
       <posy>0</posy>
       <width>1280</width>
       <height>720</height>
       <texture>background-defeat.png</texture>
       <animation effect="fade" start="0" end="100" time="6500">WindowOpen</animation>
    </control>

     <control type="image" id="2">
      <description>Image 2</description>
      <posx>307</posx>
      <posy>7</posy>
      <width>154</width>
      <height>95</height>
      <visible>true</visible>
      <texture>Image 2.png</texture>
      <animation effect="fade" start="0" end="100" time="1500">WindowOpen</animation>
    </control>

     <control type="image" id="3">
      <description>Image 3</description>
      <posx>460</posx>
      <posy>7</posy>
      <width>188</width>
      <height>95</height>
      <visible>true</visible>
      <texture>Image 3.jpg</texture>
      <animation effect="fade" start="0" end="100" time="1500">WindowOpen</animation>
    </control>

    <control type="image" id="4">
      <description>Image 4</description>
      <posx>648.5</posx>
      <posy>7</posy>
      <width>165</width>
      <height>95</height>
      <visible>true</visible>
      <texture>recorded_blue.jpg</texture>
      <animation effect="fade" start="0" end="100" time="1500">WindowOpen</animation>
    </control>

    <control type="image" id="5">
      <description>Image 5</description>
      <posx>813.5</posx>
      <posy>7</posy>
      <width>149</width>
      <height>95</height>
      <visible>true</visible>
      <texture>Image 5.jpg</texture>
      <animation effect="fade" start="0" end="100" time="1500">WindowOpen</animation>
    </control>
</controls>
</window>

Here is the .py script:
import xbmc
import xbmcgui
import os

#get actioncodes from keymap.xml
ACTION_MOVE_LEFT = 1
ACTION_MOVE_RIGHT = 2
ACTION_MOVE_UP = 3
ACTION_MOVE_DOWN = 4
ACTION_PREVIOUS_MENU = 10
ACTION_BACKSPACE = 110

class MyClass(xbmcgui.WindowXML):
  def onAction(self, action):

    if action == ACTION_BACKSPACE:
         self.close()

    if action == ACTION_PREVIOUS_MENU:
         self.close()

    if action == ACTION_MOVE_LEFT:

         if os.path.exists('Q:\\resources\skins\Default\media\image 4.jpg') == True:
             self.strAction = xbmcgui.ControlLabel(300, 200, 600, 200, '', 'font14', '0xFF00FF00')
             self.addControl(self.strAction)
             self.strAction.setLabel('Image is exist')

Here's the xml parser:
import xml.etree.ElementTree as ET

filename = 'script-tvguide-mainmenu.xml'
tree = ET.parse(filename)
root = tree.getroot()
controls = root.find('controls')

for control in controls.findall('control'):
    #how do you create the if statement to check for the image through on xml if they are exist?
    # Here are the image filenames, focus and nofocus.
    focus = control.find('texturefocus').text
    nofocus = control.find('texturenofocus').text
    print('texturefocus={0}, texturenofocus={1}'.format(focus, nofocus))

I tried with:
if action == ACTION_MOVE_LEFT:
         filename = 'script-tvguide-mainmenu.xml'
         tree = ET.parse(filename)
         root = tree.getroot()
         controls = root.find('controls')

         for control in controls.findall('control'):
             texture = control.find('texture').text

             if texture == 'tvguide_yellow.png':
                  self.strAction = xbmcgui.ControlLabel(300, 200, 600, 200, '', 'font14', '0xFF00FF00')
                  self.addControl(self.strAction)
                  self.strAction.setLabel('Image is exisit')

I want to know how to do you use to write in python for xml parser include if statement that if I have the image called "Image 2.jpg" which is return as true then I could do something?

A: Here's the simplest way to adapt your code to find the control whose texture is Image 2.jpg:
First, you're looking for an element named texturefocus. But in your XML sample, there is no such element—and even if there were, the one you're looking for is named texture. So obviously you need to fix that:
texture = control.find('texture').text

Second, you're looking for an image Image 2.jpg, but there is no such image in your XML, so you're not going to find it. There is an Image 2.png, but that's not the same thing. So, presumably you need to fix that as well.
And now, the if statement is trivial:
if texture == 'Image 2.png':

The question is, what do you want to do when you find it? Just printing out a string isn't going to help the rest of your code use that value.
Let's say that what you want to do is to write a function that returns the description if there's an image whose texture is Image 2.png, or returns None otherwise. Then:
def find_image2(filename):
    tree = ET.parse(filename)
    root = tree.getroot()
    controls = root.find('controls')

    for control in controls.findall('control'):
        texture = control.find('texture')
        if texture and texture.text == 'Image 2.png':
            return control.find('description').text


text:
Q: Div with sprite-animation doesn't change properly during window.resize event I am trying to imitate 3d-model rotation with a sprite sheet. I found a perfect example on Codepen, but it was not responsive.
What I tried to do is to write divs, containers and spritesize (in script) in vw, and then it is being checked in the window.resize event. It does work, but unfortunately not DURING window resize.
I put my snippet and three pictures in the post —

*

*I opened website and everything is perfect - image

*I started to change the size of my browser window and as you can see something is wrong - image

*Now I tried to "rotate" the "model" with resized window and all is fine again - image

var spriteslider = document.createElement('div');
var clientWidth = document.getElementById('spritetarget').clientWidth;

document.body.appendChild(spriteslider);

spriteslider.slider = document.getElementById('spriteslider');
spriteslider.sprite = document.getElementById('spritetarget');
spriteslider.spritesize = clientWidth;
spriteslider.spritecount = 20;
spriteslider.pixelsperincrement = 5;
spriteslider.multiplier = spriteslider.lastmultiplier = 0;

Draggable.create(spriteslider, {
  type: 'x',
  trigger: spriteslider.slider,
  bounds: {
    minX: 0,
    maxX: 0,
    minY: 0,
    maxY: 0
  },
  edgeResistance: 0,
  cursor: 'e-resize',
  onDrag: function() {
    if (this.isDragging) {
      var t = this.target;
      t.multiplier = Math.floor(this.x / t.pixelsperincrement) + t.lastmultiplier;
      // TweenLite.set(t.sprite, { backgroundPosition: (-t.multiplier * t.spritesize) + "px 0"});
      TweenLite.set(t.sprite, {
        backgroundPosition: (-t.multiplier * t.spritesize) + "px 0"
      });

    }
  },
  onDragEnd: function() {
    var t = this.target;
    t.lastmultiplier = t.multiplier % t.spritecount;
  }
});

window.addEventListener('resize', function(event) {
  var clientWidth = document.getElementById('spritetarget').clientWidth;
  spriteslider.spritesize = clientWidth;
  TweenLite.set(t.sprite, {
    backgroundPosition: (-t.multiplier * t.spritesize) + "px 0"
  });
}, true);
body {
  text-align: center;
  font: normal 12px sans-serif;
  background: #000000;
  color: #91E600;
}

.spriteslider {
  margin: 20px auto;
  padding: 60px;
  width: 20vw;
  height: 20vw;
  background: #FCFEFC;
  border-radius: 5px;
}

#spritetarget {
  width: 20vw;
  height: 20vw;
  background-size: cover;
  background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/29123/heart.png);
  /* horizontal spritesheet - image from http://preloaders.net */
  background-repeat: repeat-x;
}

Drag the box left/right to control the sprite's position.

A: The issue is because you're referencing t in the window.resize event handler, yet that variable has been defined in a different scope, and is not accessible from that location.
To fix this issue you can replace t in that function with the spriteslider variable, as that's what t is expected to contain. Try this:

var spriteslider = document.createElement('div');
var clientWidth = document.getElementById('spritetarget').clientWidth;

document.body.appendChild(spriteslider);

spriteslider.slider = document.getElementById('spriteslider');
spriteslider.sprite = document.getElementById('spritetarget');
spriteslider.spritesize = clientWidth;
spriteslider.spritecount = 20;
spriteslider.pixelsperincrement = 5;
spriteslider.multiplier = spriteslider.lastmultiplier = 0;

Draggable.create(spriteslider, {
  type: 'x',
  trigger: spriteslider.slider,
  bounds: {
    minX: 0,
    maxX: 0,
    minY: 0,
    maxY: 0
  },
  edgeResistance: 0,
  cursor: 'e-resize',
  onDrag: function() {
    if (this.isDragging) {
      var t = this.target;
      t.multiplier = Math.floor(this.x / t.pixelsperincrement) + t.lastmultiplier;
      TweenLite.set(t.sprite, {
        backgroundPosition: (-t.multiplier * t.spritesize) + "px 0"
      });

    }
  },
  onDragEnd: function() {
    var t = this.target;
    t.lastmultiplier = t.multiplier % t.spritecount;
  }
});

window.addEventListener('resize', function(event) {
  var clientWidth = document.getElementById('spritetarget').clientWidth;
  spriteslider.spritesize = clientWidth;
  TweenLite.set(spriteslider.sprite, {
    backgroundPosition: (-spriteslider.multiplier * spriteslider.spritesize) + "px 0"
  });
}, true);
body {
  text-align: center;
  font: normal 12px sans-serif;
  background: #000000;
  color: #91E600;
}

.spriteslider {
  margin: 20px auto;
  padding: 60px;
  width: 20vw;
  height: 20vw;
  background: #FCFEFC;
  border-radius: 5px;
}

#spritetarget {
  width: 20vw;
  height: 20vw;
  background-size: cover;
  background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/29123/heart.png);
  /* horizontal spritesheet - image from http://preloaders.net */
  background-repeat: repeat-x;
}

Drag the box left/right to control the sprite's position.


text:
Q: Fourier transform of Gaussian is equal to derivative of Fourier transform of Gaussian times constant I'm working on a few problems in Reed & Simon, and I ran across this problem.
Compute the Fourier transform of $f(x) = e^{-\alpha x^2/2}$ via the following steps.
(a) Prove that $-\lambda \hat{f}(\lambda)= \alpha \frac{d}{d\lambda}\hat{f}(\lambda)$ and conclude that $\hat{f}(\lambda) = ce^{-\lambda^2/(2\alpha)}$.
This is what I have so far (with help from first comment):
\begin{align*}
-\frac{\alpha}{\lambda} \frac{d}{d\lambda} \hat{f}(\lambda) &= -\frac{\alpha}{\lambda \sqrt{2\pi}} \int \frac{d}{d\lambda} e^{-i\lambda x}e^{-\alpha x^2/2} dx \\
&= \frac{\alpha i}{\lambda\sqrt{2\pi}} \int x e^{-\alpha x^2/2} e^{\frac{2i\lambda}{\alpha}} dx \\
&= \frac{\alpha i}{\lambda\sqrt{2\pi}} \Big[-\frac{i\lambda}{\alpha} e^{-\frac{\lambda^2}{2\alpha}}\sqrt{\frac{2}{\alpha\pi}}\Big] \\
&=\frac{1}{\sqrt{\alpha}\pi}e^{-\frac{\lambda^2}{2\alpha}}
\end{align*}
I'm not entirely sure where to go from here. I am going to keep thinking about it, but any hints would be appreciated.
Edits: I fixed the computations, all I have left to figure out on my own is the second portion of the problem, which probably isn't too bad using $u$-substitution and the fact that $e^{-x^2/2}$ is its own Fourier transform. The accepted answer provides a different and interesting way of looking at this problem as well.

A: Theorem: The characteristic function of a standard normal random variable $X$ is
$
\varphi_{X}(t)=e^{-t^{2}/2}
$.
Proof. Note that
\begin{align*}
\varphi_{X}(t)=\mathbb{E}\left[e^{itX}\right] & =\frac{1}{\sqrt{2\pi}}\int_{\mathbb{R}}e^{-\frac{x^{2}}{2}}e^{itx}dx\\
 & =\frac{1}{\sqrt{2\pi}}\left(\int_{-\infty}^{0}e^{-\frac{x^{2}}{2}}e^{itx}dx+\int_{0}^{\infty}e^{-\frac{x^{2}}{2}}e^{itx}dx\right)\\
 & =\frac{1}{\sqrt{2\pi}}\left(\int_{0}^{\infty}e^{-\frac{x^{2}}{2}}e^{-itx}dx+\int_{0}^{\infty}e^{-\frac{x^{2}}{2}}e^{itx}dx\right)\\
 & =\frac{2}{\sqrt{2\pi}}\int_{0}^{\infty}e^{-\frac{x^{2}}{2}}\cos(tx)dx.
\end{align*}
Now, take the derivative with respect to $t$ to get
$$
\varphi_{X}^{\prime}(t)=-\frac{2}{\sqrt{2\pi}}\int_{0}^{\infty}e^{-\frac{x^{2}}{2}}x\sin(tx)dx.
$$
Integrate by parts to get
\begin{align*}
\varphi_{X}^{\prime}(t) & =\frac{2}{\sqrt{2\pi}}\left(e^{-\frac{x^{2}}{2}}\sin(tx)\mid_{0}^{\infty}-t\int_{0}^{\infty}e^{-\frac{x^{2}}{2}}\cos(tx)dx\right)\\
 & =-\frac{2t}{\sqrt{2\pi}}\int_{0}^{\infty}e^{-\frac{x^{2}}{2}}\cos(tx)dx\\
 & =-t\varphi_{X}(t).
\end{align*}
Note that
$$
\varphi_{X}^{\prime}(t)=-t\varphi_{X}(t)
$$
is an ODE with solution
$$
\varphi_{X}(t)=ce^{-t^{2}/2}.
$$
We can figure out the value of the constant $c$ by recalling that the characteristic function has to satisfy $\varphi_{X}(0)=1$ so that $c=1$, as desired.


text:
Q: How to auto refresh weather forecast in javascript I am trying to add auto refresh to this block of code can someone correct this for me please need to roundup this project thanks in advance
this is the code I get so far
<script src="js/jquery.js"></script>
<script>
$(document).ready(function() {
    getLocation();

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            alert("Geolocation is not supported by this browser.");
        }
    }

    function showPosition(position) {

        var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + position.coords.latitude + "," + position.coords.longitude + "&sensor=true";
        //var url ="http://maps.googleapis.com/maps/api/geocode/json?latlng=43.428852, -80.472206&sensor=true";
        $(document).ready(function() {

            $.get(url, function(data, status) {
                //console.log(data)

                if (data == null) {
                    alert("")
                } else {
                    var city = data.results[2].formatted_address;
                    document.getElementById("cityname").innerHTML = city;

                    var country = "cd";
                    var url2 = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22" + city + "%2C%2" + country + "l%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
                    $(document).ready(function() {

                        $.get(url2, function(data, status) {

                            if (data == null) {
                                alert("Error, No Weather Report in this location")

                            } else {
                                //console.log(data)
                                var results = data.query.results;
                                if (results == null) {
                                    alert("Error, No Weather Report in this location")
                                } else {
                                    var location = data.query.results.channel.location;
                                    var forecasts = data.query.results.channel.item.forecast;
                                    var code = data.query.results.channel.item.condition.code;

                                    if (code >= 3 && code <= 16) {
                                        //rain
                                        document.getElementById("myimage").src = "images/rain.png";
                                    } else if (code >= 26 && code <= 30) {
                                        //cloudy
                                        document.getElementById("myimage").src = "images/clouds.png";
                                    } else if (code >= 31 && code <= 32) {
                                        //sun
                                        document.getElementById("myimage").src = "images/sun.png";
                                    } else if (code >= 33 && code <= 34) {
                                        //fair
                                        document.getElementById("myimage").src = "images/forecast.png";
                                    } else {
                                        //Nill
                                    }
                                    document.getElementById("myweathertext").innerHTML = data.query.results.channel.item.condition.text;
                                    document.getElementById("weathernow").innerHTML = toCelsius(data.query.results.channel.item.condition.temp) + "°<span>C<span>";
                                    setInverval(getLocation, 6000);
                                    //console.log(toCelsius(data.query.results.channel.item.condition.temp));

                                }
                            }
                        });
                    });
                }
            });
        });
    }
});

A: Your description is a bit confusing but from what I understand you are trying to run your getLocation() function every 6 seconds. If that is the case, then instead of just calling getLocation() one time in the $(document).ready() function, also call setInterval() with your function.
$(document).ready(function () {
  getLocation();
  setInterval(getLocation(), 6000);
}

You should also remove the call to setInterval() from the getLocation() function as it will set the function to call its self every 6 seconds every time it runs.


text:
Q: Error with tabula in python regarding dependency (colab and locally) I am working on extracting data from a number of pdf documents in python, testing in colab.
A solution would be great on colab, but also locally if that is not possible.
There is a lot of interesting entries per page, so I chose tabula.
Code works great for most of the files, but crashes for others...
Can I import the missing .jar etc. somehow in colab, or if not, how to install it locally to run?
Thanks in advance!
Got stderr: Oct 26, 2021 5:54:00 AM org.apache.pdfbox.pdmodel.font.FileSystemFontProvider loadDiskCache
WARNING: New fonts found, font cache will be re-built
Oct 26, 2021 5:54:00 AM org.apache.pdfbox.pdmodel.font.FileSystemFontProvider <init>
WARNING: Building on-disk font cache, this may take a while
Oct 26, 2021 5:54:00 AM org.apache.pdfbox.pdmodel.font.FileSystemFontProvider <init>
WARNING: Finished building on-disk font cache, found 17 fonts
Oct 26, 2021 5:54:00 AM org.apache.pdfbox.pdmodel.font.PDTrueTypeFont <init>
WARNING: Using fallback font 'LiberationSerif' for 'TimesNewRomanPSMT'
Oct 26, 2021 5:54:00 AM org.apache.pdfbox.contentstream.PDFStreamEngine operatorException
SEVERE: Cannot read JPEG2000 image: Java Advanced Imaging (JAI) Image I/O Tools are not installed
Oct 26, 2021 5:54:00 AM org.apache.pdfbox.contentstream.PDFStreamEngine operatorException
SEVERE: Cannot read JPEG2000 image: Java Advanced Imaging (JAI) Image I/O Tools are not installed
... (multiple lines)

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-10-987da78e7e88> in <module>()
      2 regions = []
      3 for i in range(0,len(regions_raw)):
----> 4     regions.append(regions_raw[i]['data'][0][0]['text'])
      5

IndexError: list index out of range

Code: (just one region printed, mostly from # https://towardsdatascience.com/how-to-extract-tables-from-pdf-using-python-pandas-and-tabula-py-c65e43bd754)
import tabula as tb
from tabula import read_pdf
import PyPDF2 # just for pagecount
from PyPDF2 import PdfFileReader

box = [2,0,4,13]
fc = 28.28
for i in range(0, len(box)):
    box[i] *= fc

for filename in (files):
  pdftemp=open(filename,'rb')
  pdfReader = PyPDF2.PdfFileReader(pdftemp)
  pagestmp=pdfReader.getNumPages()
  pages=[i+3 for i in range(pagestmp-2)] #leave out first 2 pages

  regions_raw = tb.read_pdf(filename, pages=pages,area=[box],output_format="json")
  regions = []
  for i in range(0,len(regions_raw)):
      regions.append(regions_raw[i]['data'][0][0]['text'])

  print(regions)

A: Oh, I´ve got it. Works, just some data starting one page later (on page 4).
An empty entry in "data" crashes, causing the error.


text:
Q: Jquery ui progress bar is not displayed in front of the other elements I'm using JQuery UI 1.8.20, asp.net 4.0, VS 2010 and
I have a problem displaying a progress bar in front of all other markup elements when loading data to populate some lists.
My html markup is basically this (splitDocumentProgressbar is the progress bar):

The javascript that populates one list and updates the progress bar (this code is in an external javascript file that I have written and this file is referenced in the aspx where the markup is defined):
var initializeUncategorizedPagesList = function (data) {
    var listItems = [];

    var progressBarSteps = data.DocumentPages.length;
    showProgressBar(true);

    $.each(data.DocumentPages, function (index, documentPage) {

        updateProgressBar(progressBarSteps, index);

        var headerClass = $.validator.format('
{0}
', documentPage.Title);
        var image = $.validator.format('', documentPage.DocumentId, documentPage.ThumbVariantId, documentPage.Title);
        var imageUrl = $.validator.format('Forstørr bilde', documentPage.DocumentId, documentPage.HoverVariantId, documentPage.Title);
        var listClass = $.validator.format('
{1} {2} {3}
', documentPage.DocumentId, headerClass, image, imageUrl);

        listItems.push(listClass);
    });

    pub.UncategorizedPagesList.append(listItems.join(''));
    showProgressBar(false);
};

var updateProgressBar = function (progressBarStep, index) {

    //If this is true, the progressbar property is not set
    if (pub.Progressbar === "Progressbar") {
        return;
    }

    if (progressBarStep === 0) {
        return;
    }

    var progressBarValue = (100 / progressBarStep) * (index + 1);

    pub.Progressbar.progressbar({
        value: progressBarValue
    });
};

// Show/hide the progress bar and will also reset the progress bar
var showProgressBar = function (show) {

    if (show === true) {
        updateProgressBar(1, -1);
        pub.Progressbar.show();
    }
    else {
        pub.Progressbar.hide();
    }
};

The progress bar works. I know this because when I debug my javascript code I can see the progress bar is displayed and the value is increased. But to me is seems that the progress bar is hidden behind the rest of the ui when i run the code without debugging.
Do you have any tips and tricks to share with me?

A: Try putting like this:

Your progressbar should appear above your code, if it doesn't you have the problem isolated in the progressbar.


text:
Q: $T(n)=T(\frac{n}{3})+T(\frac{2n}{3})+cn$ I'm trying to understand the following proof from 'Introduction to Algorithms' that the recurrence $T(n)=T(n/3)+T(2n/3)+cn$ has solution $O(n lg n)$.
I'm stuck on the fourth step when he replaces $-d(2n/3)lg(3/2)$ with just $(2n/3)lg(3/2)$ i.e. he replaces $-d$ with $1$.
Should this be an inequality rather than an equality. It would make sense if it was less than or equal to.

$d \ge c/(lg(3)-2/3)$

A: They just factored out $-d$, and the coefficient is not replaced by $1$. Thus the sign $=$ is correct.

A: Adding color, and changing some of the brackets from round to square, the fourth step is
$$
\begin{aligned}
&\left[ \color{red}{d(n/3)\lg n} - d(n/3)\lg 3\right] +
\left[\color{red}{d(2n/3)\lg n}-d(2n/3)\lg(3/2)\right] + cn\\
&=\color{red}{dn\lg n}-d\left[(n/3)\lg 3+(2n/3)\lg(3/2)\right]+cn
\end{aligned}
$$
Looks like they factored out $-d$; it wasn't replaced by $1$.


text:
Q: Why does this markdown preview differently? See this question. When published, the markdown does not render the same way it does in preview for edit mode. The numbered list does not continue when published, but appears to continue in preview. Moreover, the OP actually typed 2, but it still rendered as 1 which is puzzling.

Published

Editor Preview

A: When that post was created, our Markdown parser ignored the numbers and always started new lists at 1. That has since changed, but the post has never been re-rendered to reflect that change, so it is still showing a cached copy of how it was rendered at the time it was posted.
If you simply make some completely frivolous change so that the system caches a new rendered copy, it will update to display the same as the preview.


text:
Q: Get in a python function the name of the caller function file This code will print a message followed by m1.py, that's the file name obtained from calling os.path.basename. Instead, I need the log function to get the file name of the caller, in this case m2.py (that's the file that generates the log entry 'message'). How to achieve that?
m1.py
   def log(message):
       print(message + ' ' + os.path.basename(__file__))

m2.py
   from m1 import log

   def func():
       log('some message')

   func()

A: use inspect module :
import  inspect

def log(message):
    frm = inspect.stack()[1].filename
    print('[%s] %s' % (frm, message))


text:
Q: You should not use  outside a  in Piral I get this error when debugging my pilet inside the default Piral instance:
Uncaught Error: Invariant failed: You should not use <Link> outside a <Router>

The weird thing is the next log entry reports that the error is coming from inside a Router:
react_devtools_backend.js:2430 The above error occurred in the <Context.Consumer> component:
    in Link
    in Unknown
    in Suspense (created by ErrorBoundary)
    in ErrorBoundary
    in Unknown (created by Menu)
    in li (created by MenuItem)
    in MenuItem
    in Unknown (created by Menu)
    in ul (created by MenuContainer)
    in div (created by MenuContainer)
    in div (created by MenuContainer)
    in nav (created by MenuContainer)
    in header (created by MenuContainer)
    in MenuContainer
    in Unknown (created by Menu)
    in Menu (created by Layout)
    in div (created by Layout)
    in Layout
    in Unknown (created by PiralContent)
    in PiralContent (created by PiralView)
    in Router (created by BrowserRouter)
    in BrowserRouter
    in Unknown (created by PiralView)
    in PiralProvider (created by PiralView)
    in PiralView (created by Piral)
    in Piral

My pilet index.jsx:
import { Link } from 'react-router-dom'

const App = () => 'My pilet'

export function setup(app) {
  app.registerPage('/my-pilet', App)
  app.registerMenu(() => <Link to="/my-pilet">My Pilet</Link>)
}

My Piral instance uses the boilerplate provided by piral-cli and is completely unchanged. It even has a default menu item that works correctly without an error:

(the "Not Found" is the default menu item provided by Piral)
Why am I getting this error?

*

*Piral 0.12.4

*Piral CLI 0.12.4

*Piral CLI Webpack 0.12.4

A: Something must be wrong with your setup. If this error appears it means that your Link has a different routing context than the one from the app shell. My suspicion is that you do not share react-router-dom. Put this in the peerDependencies of the package.json of your pilet.

A: The error is self explanatory, you just need to enclose <Link .. /> with Router tags. Try this:
import { BrowserRouter as Router, Link } from 'react-router-dom'

const App = () => 'My pilet'

export function setup(app) {
  app.registerPage('/my-pilet', App)
  app.registerMenu(() => <Router> <Link to="/my-pilet">My Pilet</Link> <Router>)
}

Source: https://reactrouter.com/web/example/url-params


text:
Q: Interpretation of (simultaneous) confidence band against fitted values in multiple regression In a homework question, I am asked to interpret a figure of the confidence band and simultaneous confidence band of 95% confidence level plotted against predicted values. The confidence bands are produced from linear regression.

I did some searching, but the explanation by Wikipedia only covers the situation where we have only one predictor, which is hard to generalize to multiple regression.
Here is my own attempt: since the fitted value by a linear model is simply a linear combination of predictors and 1, confidence bands against fitted values can be thought of as confidence bands against different levels of predictors. On the one hand, at each level of predictors, the probability of a point falling in the point-wise confidence band is 95%; on the other hand, the probability for a line representing the real relationship between predictors and the response to fall into the simultaneous confidence band across all level of predictors is 95%.
However, I'm not satisfactory about the answer, because "levels of predictors" is too vague and sounds like word-playing. In addition, the coefficients used to calculate the predicted values are random variables and thus prone to statistical error, which means the whole X-axis is somewhat random.
How do I interpret it?

A: You have two options:
Option A) Try to figure out a confidence band for each observation in y, given its corresponding value of x (or x's, in case of multiple regressors).Keep on doing this independently for each observation, as if the other predictions did not exist, and you get your red-band.
Note, the band has some non-zero width since the predicted value of y is uncertain, and that's because the estimated regression betas are themselves uncertain (the estimates are function of what the sampled observations of (x,y) are - different samples would, of course, lead to different betas, hence the beta estimate is a random variable on its own, having some non-zero variance, leading to the aforementioned uncertainty).
Option B) Here, you want to find out a confidence band for the entire set of y-predictions. So, it's the confidence interval of the whole n*1 vector of y =(y_1, y_2,...y_n) which again, comes from the uncertainty of the beta estimates themselves. So, this gives you a n*1 upper bound and a n*1 lower bound , at one go, instead of computing similar bounds one by one, independently for each y value. This would be different from the case A because in A, the prediction of y_i and that of y_j, ignore the correlation induced by their common dependence on the beta estimate.


text:
Q: Code formatting I have a dataframe, df, for which I want to change the order of some columns. I have been struggling with using the multi index.
Running the command df.columns, I get the following output:
MultiIndex(levels=[['', 'Monday', 'Tuesday', 'Wednesday'], ['Margin $', 'Margin %', 'Sales -GST $', 'entity']],
           labels=[[1, 1, 2, 2, 3, 3], [1, 2, 1, 2, 1, 2]],
           names=['DayOfWeek', None])

The only columns that are visible in df are ['Margin %', 'Sales -GST $'], however I'd like them to be in the opposite order, ['Sales -GST $', 'Margin %'].
If someone could help me out that would be great.

A: You can swap the order of your multiindex by using the swaplevel index method.
df.index.swaplevel()

A: you can change the order by changing the order of indexes while creating multi index.
For example seeing your output you might have created multi indexes as shown below.
arrays = [np.array(['Monday', 'Tuesday', 'Wednesday']),
          np.array(['Margin $', 'Margin %', 'Sales -GST $', 'entity'])]
In the above you can change the order according to your needs.
Here is quick link for reference.
http://pandas.pydata.org/pandas-docs/stable/advanced.html


text:
Q: Unable to create a better database structure I want to create a basic project to search buses from one station to another
Let I have four stations A,B,C,D and I have four buses 1,2,3,4
Root of buses are
bus 1 : A->B->C->D
Bus 2 : A->C->D
Bus 3 : A->C->B
Bus 4 : A->B->D

How can I design a database for such system
I have tried
Method 1: I have created a table with two fields busno and busroute in bus route I want to store complete route of the bus number. but I think searching in this table will be very complex
or please suggest me a better Idea for such project

A: My hint is, 3 tables
Bus

*

*id

*name

Stops

*

*id

*name

Route

*

*BusId

*StopId

*position

A: How about this one
| Buses |
| id | name |

| Stations |
| id | name |

| Destinations |
| busId | stationId | priorityNo | // Where priorityNo determines where the bus should stop first.

The good part about this you can always add new buses and stations.

A: for stations you may create a table that has two fields, station name and station order and you link the bus number with rows from station table.
station table example:
A - 1
B - 2
B - 3

and you link bus 1 through keys with A-1 and B-2 and that means that A is the first station and B is the second for bus 1. Also you link bus 3 with B-3 which means B is the third station for bus 3...etc.


text:
Q: Is there any way to access http://:/logs.log.txt using Java code in windows I am trying to get file attributes present in a Unix server and when I type this url in my IE it displays the files in the file-folder-directory architecture.
I am planning to write a code for a tool such that I can automate the process of getting the file attributes like file modified date,size of file etc.
Are there any Methods/ways to do this?
Does this code work:
File file = New File("http://<someserver.com>:<portnumber>/logs/log.txt");
Date date = file.LastModifiedDate();
System.out.println("modifed date is"+date);

A: If the protocol your server supports is only HTTP, I'm afraid there's no easy way to do this. You will have to:

*

*parse the returned HTML, probably looking for <a href= tags (using some html parser, but not with regex)

*open those links with new URL(url).openConnection(), read their streams, and do the same thing recursively, until an actual file (and not directory) is found.

But this won't give you the file attributes - only the name and the file contents.
If you want to browse, you need a different protocol, like FTP or SCP.

A: The HTTP protocol won't help you here. HTTP does not publish any file attributes, except for the Content-length (file size) and the Last-Modified header value which doesn't necessarily mirror the actual file modification date. Also it might not be sent by the HTTP Server at all.
Your best bet would be using an FTP library for example the one from Apache Commons Net.
If you decide to use this library, you can use the properties of the FTPFile class, for example the file size, file date and permissions.


text:
Q: DataTables dom alignment off My DataTables alignment is off, can anyone tell me why? Have been trying to find a solution, but can't find one:
My dom is:
dom: "<'row'<'col-sm-5'B><'col-sm-7'f>>" +
     "<'row'<'col-sm-12'tr>>" +
     "<'row'<'col-sm-4'i><'col-sm-4'p><'col-sm-4'l>>"

And the reels is as the picture. I want the pagination to be centered, and the "Show X entries" to be right aligned.

A: Took awhile, but came up with the following:
dom: "<'row'<'col-sm-6'B><'col-sm-6'f>><'row'<'col-sm-12'tr>><'row'<'col-sm-6'l><'col-sm-6'p>><'row'<'col-sm-12 text-right'i>>"

All neat and nice now!


text:
Q: lag a field in a df by one day in corresponding date field There are references to lag() in r with a time series or zoo object. I just have a dataframe:
library(tidyverse)
library(lubridate)

df <- data.frame(
  date = seq(ymd('2021-01-01'), ymd('2021-01-31'), by = 1),
  x = 1:31
)

df %>% glimpse
Rows: 31
Columns: 2
$ date <date> 2021-01-01, 2021-01-02, 2021-01-03, 2021-01-04, 2021-01-05, 2021-01-06, 2021-01-07, 2021-01-08, 2021-01-09, …
$ x    <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30…

I would like a new column, y, which is the value of x on the preceding day. Example, for 2021-01-10 x=10, I would like y to be what x was on 2021-01-09 which here is 9.
How can I lag a data frame based on a date field?

A: If the 'date' are ordered, then we can just use lag
library(dplyr)
df %>%
    arrange(date) %>%
    mutate(y = lag(x))

A: In base R if the dataframe is ordered and assuming you don't want something like NA if a day is missing:
df$y <- c(NA, df$x[-nrow(df)])


text:
Q: Python DJANGO 3.0 issue with passing arguments to @register.simple_tag I have the following tree:

*

*apps

*templatetags

*

*pyos.py

*templates

*

*index.html

In pyos.py I have the following code:
import os
from django import template

register = template.Library()

@register.simple_tag
def listdir(path):
    d = os.listdir
    return d(path)

def test():
    pass

Then in index.html, inside templates I have the following already working:
{%extends 'principal.html'%}
<div>
    {%load pyos%}

    {%listdir 'C:/'%}

</div>

I need to pass some static path as argument, is there any way to do something like that?
<div>

    {%load pyos%}
    {%load static%}

    {%listdir {%static 'img/imagesFolder%}%}

</div>


text:
Q: How to find the intersection of union of two circle groups I have two groups of circles. S1 is the union of the first group and S2 is the union of the second group of circles. I know center and radius of all circles. I have to find the equation for the intersection of S1 and S2. Is there anyway to do it?

A: Intersection of unions is the union of intersections (intersection is distributive over union):
$$\left( \bigcup_{c\in  \mathcal S_1}c\right)\cap \left(\bigcup_{c\in  \mathcal S_2}c\right)=\bigcup_{c_1\in \mathcal S_1,c_2\in\mathcal S_2}(c_1\cap c_2)$$
So you can just intersect individual circles and take union of the intersections.


text:
Q: Include plain java projects as dependency at gradle project I have two projects
one plain java project and one gradle spring project created from jhipster
I would like to use the java project alongside with the gradle one.
After search on the net i have found how to do it link1 but this works only if all my projects are gradles.
Also when i try to add module dependency from Project Structure does not work.
Project tree
workspace
-project1
--build.gradle
-project2

What is the right way of doin this?
Also why i cannot make changes from IDE's project structure and automatically update build.gradle and settings.gradle with the new dependencies?

A: Change the plain java project into a gradle project, change the two projects into a gradle multi-project.
It's not hard to do, the plain java project probably just needs an almost empty build.gradle file and the settings.gradle file just needs to include it.
An IDE cannot help you much in these tasks, you will have to do most of it manually.


text:
Q: Using AJAX To complete autopredict - Not working Having a problem with an AJAX JS feature which will grab information from the PHP database and predict the search term before the user has finished.
/js/primary.js:
$(document).ready(function() {
                $('.autosuggest').keyup(function() {

                    var search_term = $(this).attr('value');
                    //alert(search_term); //takes what is typed in the input and alerts it
                    $.post('ajax/search.php', {search_term:search_term}, function (data) {
                        alert('Ajax Activated');
                        $('.result').html(data);
                                    $('.result li').click(function() {
                                            var result_value = $(this).text();
                                            var id_result = $(this).data("id");
                                            $('.autosuggest').attr('value', result_value);
                                            $('.id').attr('value', id_result);
                                            $('.result').html('');
                                    });
                    });
                });
            });

/ajax/search.php:
            require_once '../Configuration.php';
            if (isset($_POST['search_term']) == true && empty ($_POST['search_term']) == false) {

            $search_term = mysqli_real_escape_string($sql_connection, $_POST['search_term']);

            $query = mysqli_query($sql_connection,"SELECT `id`,`customer_name`,`postcode` FROM `Customers` WHERE `customer_name` LIKE '$search_term%' ");

            while(($row = mysqli_fetch_assoc($query)) !== false) {
                //loop
                  echo '
',$row['customer_name'],' ',$row['postcode'],'
';

                }
            }

            ?>

Selectcustomer.php:
                        $customer_id = (int) $_GET['id'];

                        $query = "SELECT * FROM Customers WHERE id = {$customer_id}";

                        $result = mysqli_query($sql_connection, $query) or die('
' . $query . '

' .
                                               mysqli_error($sql_connection) . '
');

                        $customer = mysqli_fetch_assoc($result);

            ?>

Quick find users

                            <form action="Customer.php" method="post">

                            <input type="text" class="autosuggest"> <input type="submit" value="Go Go Go!">

                                <input type="hidden" name="id" class="id" value="">
                            </form>

Problem:
Nothing is appearing in the field (This used to work).
I fixed all of the paths not working. But it still doesn't prompt a search.

A: I was directed to look in Search.php which contained an infinite loop:
        while(($row = mysqli_fetch_assoc($query)) !== false) {
            //loop
              echo '
',$row['customer_name'],' ',$row['postcode'],'
';

Changed it to:
        while($row = mysqli_fetch_assoc($query)) {
            //loop
              echo '
',$row['customer_name'],' ',$row['postcode'],'
';


text:
Q: C# - How do I order a list of colors in the order of a rainbow? From a list of images, I calculated the average color using a method similar to this. I now have a list of System.Drawing.Color, but I'm not sure how to sort them in a way that it looks like a rainbow.
Here is something simple I have tried (slightly changed for example purposes):
var colorList = new List<Color>
{
    Color.Red,
    Color.Purple,
    Color.Black,
    Color.Blue,
    Color.Green,
    Color.LightGreen,
    Color.LightSkyBlue,
    Color.Yellow
};

var orderedColorList =
    colorList.OrderBy(o => (o.R * 3 + o.G * 2 + o.B * 1));

This does not seem to create a rainbow but more of an effect from black to white.
How would I be able to sort them in a way that results in a rainbow?

A: If you order by the Hue first, and then RGB, you should get a rainbow ordering:
var orderedColorList = colorList
    .OrderBy(color => color.GetHue())
    .ThenBy(o => o.R * 3 + o.G * 2 + o.B * 1);

Using a mixed-up collection of rainbow colors, this appears to do the trick:
var colorList = new List<Color>
{
    Color.LightSkyBlue,
    Color.Red,
    Color.Yellow,
    Color.Purple,
    Color.Orange,
    Color.Blue,
    Color.Green
};

var orderedColorList = colorList
    .OrderBy(color => color.GetHue())
    .ThenBy(o => o.R * 3 + o.G * 2 + o.B * 1);

foreach (var color in orderedColorList)
{
    Console.WriteLine(color.Name);
}

Output


text:
Q: How to automate adding a framework to "Embedded Binaries" We're building a Unity game for a client that has provided us with an iOS framework. The framework is required to be added as an Embedded Binary. This is simple to do manually, however, we are using Jenkins to automatically make our builds.

Note: this is an example image I found on Google.
Is there a way to automate this through a script be it with XCode, Unity, or 3rd party tools?


text:
Q: Validar que el usuario este logueado al cambiar de vista - AngularJS Estoy desarrollando una aplicación web con AngularJS, y necesito realizar una validación en cada una de las vistas en que el usuario se haya logueado previamente. Ya tengo creado un servicio propio para la autenticación y en este existe un método que valida si ya se ha logueado, pero no sé cómo implementarlo con las vistas.
He realizado esto que he encontrado por allí pero no funciona, mi mayor preocupación es que se pueda acceder directamente desde la URL.
angular.module("myapp").run([
    "$rootScope",
    "$location",
    "$AuthService",
    function($rootScope, $location ,$AuthService){
        $rootScope.$on('$routeChangeStart', function (event, next) {
             if($AuthService.isAuth()){
                console.log("entra");
            }
            else{
                $location.path("/login");
            }
        });
    }
]);

A: yo lo haria de la siguiente manera usando ui.router para manejar las rutas:
.state('register-event', { //ok
        url: '/register-event/:eventId',
        templateUrl: 'views/register-event.html',
        controller: 'RegisterEventCtrl as vm',
        onEnter: function($AuthService,$location){
          if(!$AuthService.isAuth()){

              $location.path("/login");

          }

        }
    })

Tambien podrias usar la siguiente libreria, aunque hace un tiempo atras deje de usarla por un bug que tenia pero seguramente ya lo arreglaron https://github.com/Narzerus/angular-permission
Este se usaria de la siguiente manera dentro de run(),(este codigo puede haber cambiado ya que es el que yo usaba hace un tiempo):
PermRoleStore
      .defineRole('anonymous', function (stateParams) {

          if (!$AuthService.isAuth()) {
            return true; // Is anonymous
          }
          return false;
      });
      PermRoleStore
      .defineRole('isloggedin', function (stateParams) {
          if ($AuthService.isAuth()) {
            return true; // Is loggedin
          }
            return false;
      });

En tus rutas se debe añadir lo siguiente para verificar que el usuario este logeado, si no esta logeado se lo redireccionara al login:
.state('tabs.comercios', {
          url: "/comercios/:comercioID",
          data: {
           permissions: {
            except: ['anonymous'],
            redirectTo: 'login'
           }
          }

        })

En caso de que quieras redireccionar directamente al panel al usuario porque este ya esta logeado seria asi:
.state('login', {
        url: '/login',
        data: {
          permissions: {
            except: ['isloggedin'],
            redirectTo: 'tabs.categorias'
          }
        },
        templateUrl: 'templates/login.html',
        controller: 'LoginCtrl'
    })


text: Q: How to check Facebook logged or not in Android I want to open app not have to login Facebook, I want to push some information to another activity by Push Extra. I know AccessToken.getCurrentAccessToken(), but how to push extra with email, gender, name, phone number into another activity while AccessToken.getCurrentAccessToken() != null


text:
Q: Grant access to users on multiple tables on multiple Mysql server I have a set of 50 MariaDB servers that have the same table names in all the databases. Database names and table names are all the same. How can I grant access to the same users on all 50 database tables? I have an ssh key set up on all the servers and do not want to log on to individual servers to grant access.

A: You mention you have an SSH key already setup, so you can do this:
#!/bin/bash

servers="server1
server2
server3"

for server in $servers
do
    ssh user@"$server" <YOUR COMMAND HERE>
done

Replace "YOUR COMMAND HERE" with your MariaDB command(s).
If you have many other things to run on all those servers, Ansible is the way to go.


text:
Q: codeigniter bcc doesn't work Codeigniter "bcc" doesn't work, But the same code with "to" works just fine! Any suggestions why this happens and how to fix it?
Here's my code:
        $email = "myEmail@myWebsite.com";

        $subject = "my subject";
        $message = "my message";

        $this->email->set_mailtype("html"); // In my actual code this is needed

        $this->email->from('myWebsiteEmail@myWebsite.com', 'Info');
        // $this->email->to($email); // It works with this code
        $this->email->bcc($email); // It doesn't work with this code

        $this->email->subject($subject);
        $this->email->message($message);

        $this->email->send();

Any suggestions would be appreciated!

A: You have to have a to to be able to bcc
Try adding an email to the to as well as a bcc and it should work.

A: You may need to enable bcc_batch_mode in email config.
By default is value is FALSE.

A: It doesn't need a $this->email->to() all you need to do is set $config['bcc_batch_mode'] = TRUE; and then add the emails like $CI->email->bcc( $bccEmailArray );. The bcc method does not work like the cc method.


text:
Q: How to point Java to a symbolic link Let's say I have symbolic link called /home/team/Java , I want to point Java to that symbolic link
How can I do it Solaris?
Expectation :
When I type "which java" in my environment
It should give output "home/team/Java"

A: Use this command
ln -s /usr/bin/j2re1.4.2_17/bin/java home/team/Java

here /usr/bin/j2re1.4.2_17/bin/java is your actual java installation directory path


text:
Q: array being pushed data but empty when logging Hey all I currently have the forEach method below in an array
let distances = []

            markers.forEach((el) => {
              new google.maps.DirectionsService().route({
                origin: address,
                destination: el.address,
                travelMode: google.maps.TravelMode.DRIVING
              })
                .then((response) => {
                  distances.push(response)
                  // For each route, display summary information.
                })
                .catch((e) => console.log('Directions request failed due to ' + status))

              console.log(distances)
            })

does anyone know why I cant see the items after they are all pushed ?


text:
Q: Codec mismatch between asterisk server and my android app? I'm new to VOIP application development.  I successfully made an iphone voip app and an android voip app, and I can talk to my friends via this voip app.  I have my own asterisk server set up on a linux operating system.
In making the phone voip app, I used whichever codec was native to the sip library I integrated with (in this case, it was linphone sip library).  Now I'm interested in figuring out which codec is being used.  After some debugging, my android app says I'm using the PCMU codec.  This is very unusual because in my asterisk server sip.conf file, I only allow ulaw and gsm codecs.
So my question is, how come my voip app works perfectly when there's a mismatch in codecs between my phone app (using PCMU) and my asterisk server (allowing only ulaw and gsm)?  I'd expect my app to break because of this codec mis-match.

A: Please check answer in your other question. Note, pcmu=ulaw=g711u. it is just different names


text:
Q: ASIHTTPRequest login method and reuse creds I am using ASIHTTPRequest to login to my app and have created a bool method to login and thats working great:
-(BOOL)User:(NSString *)user password:(NSString *)password
{
    NSURL *url = [NSURL URLWithString:url];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setUseSessionPersistence:YES];
    [request setUseKeychainPersistence:NO];
    [request setUsername:user];
    [request setPassword:password];
    [request setDomain:domain];
    [request startSynchronous];

    NSError *loginError = [request error];
    if(loginError == nil){
        return true;
    }else{
        return false;
    }

}

but now I am trying to use these creds outside this method. I read the documentation and it appears I can use these creds via:
//Should reuse our username and password
request = [ASIHTTPRequest requestWithURL:url];

but that would throw an error because request would not be defined. How would I do this?

A: Effective range of the request variable only in the method. You should also define new variable in the outside of the method.
Like below:
//Should reuse our username and password
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

A: As the documentation says:

If useSessionPersistence is turned on (it is by default), ASIHTTPRequest stores credentials in memory and can re-use them for subsequent requests.

This means that your credentials will be stored in sessionCredentialsStore (and sessionProxyCredentialsStore if you're using a proxy). Unless you overwrite them, they will be automatically applied to all subsequent requests. Both of these variables are static global variables.
So, just make a request as normal, and the credentials will be applied to the next request as long as you don't modify the credentials store.

A: I am not very clear about what you are asking but as far as I understand your concern is about extracting user credentials after the request has been fired. Is that correct?
I think the ideal way to do this is to never let go of the request in the first place (OR simply cache using Keychain). So basically hold this request variable as an instance variable(ivar) of a particular object (potentially a singleton manager type class that handles login tasks). Example
// LoginManager.h

@import Foundation;

@interface LoginManager : NSObject

@property (nonatomic, readonly, strong) ASIHTTPRequest *request;

@end

// LoginManager.m

#import "LoginManager.h"

@interface LoginManager ()

@property (nonatomic, readwrite, strong) ASIHTTPRequest *request;

@end

@implementation LoginManager

+ (instancetype)sharedManager
{
    static LoginManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

-(BOOL)User:(NSString *)user password:(NSString *)password
{
    NSURL *url = [NSURL URLWithString:url];
    self.request = [ASIHTTPRequest requestWithURL:url];
    [self.request setUseSessionPersistence:YES];
    [self.request setUseKeychainPersistence:NO];
    [self.request setUsername:user];
    [self.request setPassword:password];
    [self.request setDomain:domain];
    [self.request startSynchronous];

    NSError *loginError = [request error];
    if(loginError == nil)
    {
        return true;
    }
    else
    {
        return false;
    }
}

@end

Access it via:
ASIHTTPRequest *request = [[LoginManager sharedManager] request]

NSLog(@"%@", request.username);
NSLog(@"%@", request.password);


text:
Q: Adding a new record that has a foreign key relationship using new_foo_path(@bar) I'm trying to add a new location to a restaurant using Ruby on Rails.
In the restaurants#show action I run:
<%= link_to 'Add Location', new_location_path(@restaurant) %>

And I get a URL: http://localhost:3000/locations/new.1, where 1 is the id of the restaurant. But the new location form doesn't appear.
What is the rails way to handle this simple case? Is using new_FOO_path even the right thing to be doing?
In this case, I shouldn't have a drop down to select the restaurant because I want the end user to only be able to add a location to their own restaurant. I would somehow need to have a hidden input with the restaurant ID in the add location form, and also validate the id on the backend.

A: I would create a nested resource in your routes.rb. Example:
resources :restaurants do
  resources :locations
end

Then your link target would be new_restaurant_location_path(@restaurant). In your controller, you can find the restaurant via Restaurant.find(params[:restaurant_id]).
Alternatively, set the restaurant id as a GET parameter with new_location_path(:restaurant_id => @restaurant.id).


text:
Q: WCF Add Service Reference - Collection type keeps trying to use System.Array I am having a problem adding a custom WCF service reference to my WPF application. I have been working on this service and application for nearly 6 months now and have never run into this issue until today. Whenever I try and add the WCF service via "Add Service Reference," all of my methods that return List are trying to return T[] instead. When I configure the service reference and change the collection type to "System.Collection.Generics.List", It shows in the status bar that it is updating the reference code, but the methods in the WPF application are throwing errors stating that it can't implicitly convert from List to Array. It seemed to have happened after I pushed an update to the server, but the only thing that was changed was the way one of my objects is initialized. I have tried the following so far;

*

*Cleaned the project

*Cleaned the solution

*Rebuild the solution

*Manually deleted the obj/bin/Service Reference folders

*Removed and re-published the wcf service

*Restarted the server

Im at a complete loss and have no idea what to do at this point. Any help is greatly appreciated!
Update
I created a separate console project, and it hooks into the WCF service correctly once configured to return lists. Looks to be specifically an issue with the WPF project.
Update 2
I noticed the following errors showing up briefly when I try to build. They disappear after a while, but I don't know if this has anything to do with the issue. They are both in the App.config file.

*

*The 'bindingConfiguration' attribute is invalid - The value 'BasicHttpBinding_ICustomService' is invalid according to its datatype 'serviceBindingConfigurationType' - The Enumeration constraint failed.

*The 'contract' attribute is invalid - The value 'CustomServerSvc.ICustomServer' is invalid according to its datatype 'clientContractType' - The Enumeration constraint failed.
Update 3
Interestingly, this only seems to happen on the client side randomly after a build.
Adding in my web.config per request.
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="UnifyServer.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <connectionStrings>
    <add name="DebugUnifyCS"
          connectionString="connectionString"
          providerName="System.Data.SqlClient" />
    <add name="UnifyCS"
          connectionString="connectionString"
          providerName="System.Data.SqlClient" />
  </connectionStrings>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <client />
    <bindings>
      <basicHttpBinding>
        <binding name="myBasicBinding" maxBufferPoolSize="524288" maxBufferSize="2147483647"
          maxReceivedMessageSize="2147483647" receiveTimeout="00:30:00" sendTimeout="00:30:00">
          <readerQuotas maxDepth="128" maxStringContentLength="2147483647"
            maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
        </binding>
      </basicHttpBinding>
    </bindings>
    <!--<bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IUnifyServer" >
          <security mode="None" />
        </binding>
      </basicHttpBinding>
    </bindings>-->
      <services>
        <service name="UnifyServer.UnifyServer">
          <endpoint address="UnifyServer" binding="basicHttpBinding" bindingConfiguration="myBasicBinding" contract="UnifyServer.IUnifyServer"></endpoint>
          <host>
            <baseAddresses>
              <add baseAddress="http://unifysrv2012:19081/"/>
            </baseAddresses>
          </host>
        </service>
        <service name="UnifyServer.ServiceEndpoint">
          <endpoint address="ServiceEndpoint" binding="basicHttpBinding" bindingConfiguration="myBasicBinding" contract="UnifyServer.IServiceEndpoint"></endpoint>
          <host>
            <baseAddresses>
              <add baseAddress="http://unifysrv2012:19081/"/>
            </baseAddresses>
          </host>
        </service>
      </services>
      <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

  <applicationSettings>
    <UnifyServer.Properties.Settings>
      <setting name="UnifyServer_some_service" serializeAs="String">
        <value>https://some.url.com/some_service.asmx</value>
      </setting>
    </UnifyServer.Properties.Settings>
  </applicationSettings>
</configuration>

A: I doubt any service reference is updated since you are getting error while updating service reference.
Try start by these steps, each step is independent to other & might be cause of issue:

*

*Make sure [ServiceContract] is declared for the interface of your services, because this produces the exact error.

*If you have re-factored code or changed any file/namespace. make sure its applied everywhere.

*Use fully qualified service name in web.config with Namespace;

*Make sure System.ServiceModel & System.Runtime.Serialization reference is not missing.

*Delete .SUO (solution Users Option file) file after closing VS. This will reset the cache for XMLEditor component in VS.

Update
For error The 'bindingConfiguration' attribute is invalid - The value 'BasicHttpBinding_ICustomService' is invalid according to its datatype 'serviceBindingConfigurationType' - The Enumeration constraint failed.
Make sure all service interface/contract have [ServiceContract] attribute, methods have [Operation Contract].
Also make sure all DataContract Attributes have [DataMember] Or enum have [EnumMember] attribute.

Update 2
One case I have faced was some attribute wasn't able to serialize. e.g. I was returning DataSet that can't be serialized to binary by default by wcf, that cause the error.
In worst case, you have to separate Data contracts & reuse them & have to generate proxy manually using SVCUtil. I know it sounds crazy. But sometimes when all things doesn't work it seems to be working.
Let me know it works or not.

A: This happens often so when you are adding the reference to the WCF service check this:

*

*In the "Add service reference" screen press the "Advanced..." button (at the bottom).

*In the middle part of the "Service reference settings" screen that you just opened you'll see 2 combos where you specify the collection type, select the right ones and click ok.


text:
Q: I want to get item from a foreign key inside a foreign key (if that makes any sense...) I'm using ASP.NET Core Identity. The user ID will be as FK in the Invite model and I'm trying to display all the users that are in the invite with the desired information.
I want to display the GameName within the GameID that is assigned to the user.
So it would be something like in invite show GameName (FK in user) GameTag (user) instead of GameID with a number.
Model classes:
public class Invite
{
    public int ID { get; set; }
    [ForeignKey("UserId")]    // ICollection<Invite> in User
    [Display(Name = "Users")]
    public virtual ApplicationUser User { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public string Description { get; set; }
    [ForeignKey("GameID")]
    public int? GameID { get; set; }
    public string GameTag { get; set; }
    public virtual ICollection<Invite> Invite { get; set; }
}

public class Game
{
    public int ID { get; set; }

    [Display(Name = "Game")]
    public string GameName { get; set; }
    public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }//Allow Users to get Games FKID (Foreign key ID)
}

Getting the list of invites in the invite controller index and putting them inside viewbag for invite razor index page. it only shows GameID which is the FK inside User and I don't know how to get the information inside the Game FK from Invite that is assigned to user as FK
// GET: Invites
public async Task<IActionResult> Index()
{
    ViewBag.InviteList = new List<String>();
    var invite = _context.Invites;
    var theuser = _context.ApplicationUser;

    foreach (Invite i in invite)
    {
         foreach (ApplicationUser tu in theuser)
         {
             if (i.User.Id == tu.Id)
             {
                 ViewBag.InviteList.Add(tu.GameID + " " +tu.GameTag);
             }
         }
    }

    return View(await _context.Invites.ToListAsync());
}

If anyone understands what I'm trying to say welcome to suggest a better title

A: Your code is not implemented correctly (besides the main requirement of showing GameName). Actually the info from Game is not referenced directly from ApplicationUser. Not sure why you don't include that in the class (together with GameID). Suppose you do that (including the property Game), the code can be simple like this:
var invites = await _context.Invites.AsNoTracking()
                            .Include(e => e.User.Game).ToListAsync();

//NOTE: this can contain duplicate strings added to `InviteList`, unless you
//include more data field in each item.
foreach (Invite i in invites)
{
     ViewBag.InviteList.Add(i.User.Game.GameName + " " + i.User.GameTag);
}

If you don't want to include the property Game in the ApplicationUser, you need to join the entities, like this:
var games = await (from invite in _context.Invites
                   join game in _context.Games on invite.User.GameID equals game.ID
                   select new { game.GameName, invite.User.GameTag }).AsNoTracking().ToListAsync();
//to avoid duplicate items (as noted in the previous code)
ViewBag.InviteList = games.GroupBy(e => e.GameName)
                          .Select(g => g.First())
                          .Select(e => $"{e.GameName} {e.GameTag}").ToList();


text:
Q: ZipEntry changes UpperCase filename to CamelCase I am trying to zip up 3 files in a windows environment just before SCP'ing them to a Linux server.
The 3 filenames are all uppercase.
When I add the ZipEntry to the ZipOutputStream, it changes the file name to camel case.  This will not work when sending them to Linux.
Is there any way to keep the uppercase names when I use ZipEntry.putNextEntry()?
byte[] buffer = new byte[1024];
String strOutFile = "MyZip.zip";
FileOutputStream fos = new FileOutputStream(strOutFile);
ZipOutputStream zos = new ZipOutputStream(fos);
String strInFile = "FILE1.TXT";
ZipEntry zipEntry = new ZipEntry(strInFile);
zos.putNextEntry(zipEntry);
FileInputStream fis = new FileInputStream(new File(strInFile));
int len;
while ((len = fis.read(buffer)) > 0) {
  zos.write(buffer, 0, len);
}


text:
Q: Two-sided document: reverse page margins for hardcopy Background
Wrote a manual in LyX. The PDF is two-sided. Using KOMA Script v2. The pages are 8.5" x 11".
Problem
The spacing on the margins is not printer-friendly, it is reversed:

Since this page is an even-numbered page (4), the print shop said that the extra space must be on the right-hand side. The extra space (for binding) is currently on the left-hand side (of even pages).
Question
How can the margins be swapped so that the larger space is on the right (for even page numbers) while maintaining the same total margin space?
Ideas

*

*Tried adding a blank page to the beginning of the manual.

*\KOMAoptions{BCOR=3cm}\recalctypearea
The latter results in the margins having been flipped around, but with different spacing.
Thank you!

A: I had the same problem. Even numbered pages would be inverted margin-wise and page numbers would appear on the 'inner' side of the page. For me though, the chapter title in the header was on the wrong side as well. E.g. on page 4 it read "Chapter 1.4 xxx" on the left (inner) side and since I put my pagenumbers in the footer those too appeared at the page's inner margin.
So in my case, everything including margins, page header and footer was simply inverted. However, neither my table of contents, nor list of tables and figures were inverted, so I concluded there was something immediately after \listoftables that was causing the inverted margins etc. What I then found was a \clearpage which I put there so that the next chapter doesn't start on the same page as the list of tables.
Look for a \clearpage in your twoside-enabled document and remove it or replace it with a \cleardoublepage if you absolutely need it because \clearpage will cause everything to invert.

A: The default layout is exactly right. The idea is that when you open the book flat on the table, the white space at the borders and in the middle (between the even and odd pages of the text) are the same width (for balance).
The memoir documentation (memman.pdf) and I believe the KOMA bundle documentation also explain all this in great length.

A: From main menu:
Document>Settings...>Page Layout

Then click on checkbox for "Two-sided document".
Regards

A: It is normal that the outside margins are larger than the inside margins. However, KOMA-script/typearea supports the specification of a binding correction. That is, specifying how much space will be lost on the inside of the pages due to binding. The effect is that it shifts the text to the outside by that amount.
You specify the binding correction by passing the BCOR option to the documentclass: \documentclass[BCOR=3cm]{scrbook}. Alternatively, you can also add \KOMAoptions{BCOR=3cm}\recalctypearea to your preamble.

Edit: One way to switch margins is to add the following to your preamble:
\let\tmp\oddsidemargin
\let\oddsidemargin\evensidemargin
\let\evensidemargin\tmp
\reversemarginpar

This will exchange the margin sizes and print marginpars on the inside. I don't know whether that switching has any other unintended side-effects.


text:
Q: How to fix the error of not taking value at 0 position in loop I'm trying to take input from User in program But unable to take input at index 0
void User::call()
{
    `cout<< "number of times :";
    cin>>a;
    for (int i=0 ;i < a;i++)
    {
    cout<<"ENTER NAME : ";
    getline(cin,b);
    cin.ignore();
    }
}
`
I have attached the pictures of code and output result . Kindly check.
MY CODE HERE
AND OUTPUT HERE.

A: Please see this answer. I think the issue is caused by a stay newline or carriage return character.
In your code, try changing:
cin >> a to the following:
cin >> a;
cin.ignore(); // ignore the stray newline after you input a number.


text:
Q: usb c thunderbolt to vga doesnt detect my extended laptop Im using lenovo ideapad gaming 3 and the ugreen 9 in 1 usb type c connector.
It supports the thunderbolt, thats why I bought the usb type c to vga. Ive also tested the ugreen 9 in 1 type c with my samsung note 10+ and its working, so Im having doubts that the problem is in my laptop, not in the ugreen

A: Seems like even though it is a usb type c thunderbolt, its doesnt support extended display
I got the answer here


text:
Q: how to target parent div on focus of child div using sass.? How can I make it so that on Focus on input to change the background color of text ..?
 What exactly am I doing wrong?
please let me know..
thanks

.parent_div {
  background: lightblue;
  .child_div {
    input {
      color: grey;
      background: blue;
      &:focused {
        color: purple;
        background: white;
      }
      &:focused~grand-child-of-parent {
        opacity: 0.7;
        background: red;
      }
    }
  }
}

    <input type="text" />

 is simply dummy text of the printing and typesetting industry.

A: Unfortunately, this is not possible, as there is no "grand-child-of-parent" selector.
You can change the background and text of the input itself, when it gets focudes, but you can't modify styles of parent elements without using JavaScript.
For this case, listen to the focus event by JavaScript and add / remove a modifier class to e.g. parent element.
HTML:

  <input class="field" type="text" />

Bla

CSS:
.child-class {
  background: red;
}
.focused .child-class {
  background: green;
}

JavaScript (jQuery):
$('.field').on('focus', function() {
  $(this).parent().addClass('focused');
})
$('.field').on('blur', function() {
  $(this).parent().removeClass('focused');
})

A: Actually this is now kinda possible, but not for any circumstances probably:
With the help of :focus-within (https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within).

.parent_div {
  background: lightblue;
}

.parent_div .first_child .input {
  color: grey;
  background: blue;
}

.parent_div .first_child .input:focus {
  color: purple;
  background: white;
}

.parent_div:focus-within {
  opacity: 0.7;
  background: red;
}

    <input class="input" type="text" />

 is simply dummy text of the printing and typesetting industry.