text:
Q: Get area of municipality I am using stSPARQL and the ref says:

xsd:float strdf:area(strdf:geometry A): Returns the area of the surface if it is a polygon or multi-polygon.

and so I am trying:
PREFIX geo: <http://geo.linkedopendata.gr/gag/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX strdf: <http://strdf.di.uoa.gr/ontology#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
...
?municipality geo:has_geometry ?geometry . // so far so good (checked)
FILTER(strdf:area(?geometry) = ?area) .

and I am getting nothing as a result. My overall goal is to get the total area of all municipalities, but I can not even get one! Any idea?
Note that's my first time I am using spatial metric functions, thus what I am trying to do is to collect and show the result of strdf:area(), but I am failing!
The 1st result of ?geometry is:

"MULTIPOLYGON(((476162.8125 3949684,476195.687499999 3949675,476216.000000001 3949675,476226.1875 3...   more

EDIT:
If I try with this: ?area = strdf:area(?geometry) ., I will get an error:

Encountered " "=" "= "" at line 15, column 9. Was expecting one of: "(" ... "!" ... "^" ... "a" ... ... ...

A: I think what you want to do with a function that has a return value is you should use it in your select clause somehow.
For example:
PREFIX geo: ...
PREFIX rdf: ...
PREFIX strdf: ...
PREFIX xsd: ...
...
SELECT (strdf:area(?geometry) AS ?myarea)
WHERE {
        ?municipality geo:has_geometry ?geometry .
}

Supposedly this gives you all the areas you need to add, just use the SUM(?myarea) function. This adds all the answers that the "area" function found. In the previous situation your select clause would be something like:
SELECT (SUM(strdf:area(?geometry)) AS ?myarea)

A: FILTER does not set variables.
From your comment about wanting to collect the result of strdf:area(),
either
BIND(strdf:area(?geometry) AS ?area)

or
SELECT ... (strdf:area(?geometry) AS ?area) ...


text:
Q: String Replace Problem I have a string replace problem. I have a result like:
"Animal.Active = 1 And Animal.Gender = 2"

I want to replace something in this text.
Animal.Active part is returned from a database and sometimes it is returned with the Animal.Gender part.
When Animal.Gender part comes from the database I have to remove this And Animal.Gender part.
Also if the string has Animal.Active = 1, I have to remove Animal.Active = 1 And part. Note the And.
How can I do this?

A: Granted this is a very specific solution that will undoubtedly become more complicated as you add more conditions, but here goes:
dbReturn =
    dbReturn.Replace("And Animal.Gender","").Replace("Animal.Active = 1","");

A: You will need to use a regular expression (regex) to replace this, then, since you want to match a number.
  string pattern = "And Animal\.Gender\s*=\s*[0-9]+";
  string replacement = "";
  Regex rgx = new Regex(pattern);
  string result = rgx.Replace(input, replacement);

Will work to replace "And Animal.Gender = #" with zero or more white spaces between the = sign.
You can do a similar replacement for the second request, with Animal.Active.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JQuery and WinJS - Promise WinJS Promises and JQuery Promises are the same thing?

A: Promises are a programming pattern for dealing with asynchronous operations. The pattern could be applied to other languages, but they are most commonly encountered in JS libraries (like jQuery and WinJS).
Kraig Brockschmidt has a really good blog post about how they work (in general) and in WinJS here:
http://blogs.msdn.com/b/windowsappdev/archive/2013/06/11/all-about-promises-for-windows-store-apps-written-in-javascript.aspx
I've written a blog post comparing jQuery promises and promises in WinJS. The short answer: they're interoperable.
http://blogs.windows.com/windows/b/appbuilder/archive/2013/07/10/jquery-and-winjs-working-together-in-windows-store-apps.aspx


text:
Q: How can I optimize this android code? I want to parse jsonarray which has uncertain length,

*

*if this array's length is 0,then children are null;

*if this array's length is 1,then children0 has some value,and others
are null;

*if this array's length is 2,then children0 and children2 have some
values, and children3 is null;

*if this array's length >= 3,then children0 and children1 and
children2 have values.

How can I optimize this code?
That's all...
It's my first time to ask question on stack overflow.
I'm so sorry for my poor English...
String children0 = null;
String children1 = null;
String children2 = null;

if (chArray.length() > 2) {
    children0 = value0;
    children1 = value1;
    children2 = value2;
} else if (chArray.length() == 2) {
    children0 = value0;
    children1 = value1;
} else if (chArray.length() == 1) {
    children0 = value0;
}

A: you can use an array
String[] childrens = new String[3];

for(int i=0; i<chArray.length() && i<3; i++)
    childrens[i] = value[i];

A: I like the switch for this
switch(chArray.length){
    default: // > 2 because every lower cases are defined after!
        children2 = value2;
    case 2:
        children1 = value1;
    case 1:
        children0 = value0;
    case 0: //error check if the array is empty before (this is ugly like this ;) )
}

Without breaks, it will place itself in the right position depending on the length of the array received then execute the following line.


text:
Q: Javascript get Text from an External Webpage I have looked for a long time but I haven't been able to find a simple solution. On my webpage I want to input an address which will be looked up by a website which returns a webpage where in the text the username I need is located.
https://id.ripple.com/v1/user/  +   the username inputed. It would open the page like https://id.ripple.com/v1/user/rUkUchFYfvjucGtGDtSV2avQCzmJrktkVw where there will be a username parameter containing sashadkiselev. I want to be able to make a function which takes the address opens that webpage retrieves the username and shows it in a pop up box.

A: As redundant as your request seems, if you are using jQuery, you can have the following code to do what you want:
$(function () {
    function getUsername(username, callback) {
        $.getJSON('https://id.ripple.com/v1/user/' + username, function (data) {
            callback.call(data, data.username);
        });
    }

    getUsername('sashadkiselev', function (username) {
        alert('Username is: ' + username);
        // the rest of the data is also available as "this"
    });
});

Note that the ability to pass a function as the callback parameter to getUsername() allows you to easily customise what you do with the username.


text:
Q: Typing: How to specify shape of array How can I specify the "typing shape" of an array?
I have a function that returns a numpy array of shape (2, 2):
import numpy as np
def some_function() -> np.ndarray:
    return np.array([[1, 2], [3, 4]])

I would like to specify the shape in the returning type.


text:
Q: Email Field from Slack to AWS Lambda {
  "messageVersion": "1.0",
  "invocationSource": "DialogCodeHook",
  "userId": "xxx",
  "sessionAttributes": {
    "currentReservation": ""
  },
  "requestAttributes": {

  },
  "bot": {
    "name": "BookTrip",
    "alias": "shoping",
    "version": "7"
  },
  "outputDialogMode": "Text",
  "currentIntent": {
    "name": "Shoping",
    "slots": {
      "offer": "Yes",
      "email_address": null
    },
    "slotDetails": {
      "offer": {
        "resolutions": [{
          "value": "Yes"
        }],
        "originalValue": "Yes"
      },
      "email_address": {
        "resolutions": [],
        "originalValue": null
      }
    },
    "confirmationStatus": "None"
  },
  "inputTranscript": "<mailto:xxx.20@gmail.com|xxx.20@gmail.com>"
}

When bot asks for email address. User entered xxx.20@gmail.com for the email_address slot.
But when the request comes from the slack, it is not coming in the slot.

A: Lex is not able to recognize the input as an email because Slack is wrapping the actual input with <mailto:...|...>. You can see the input that Lex is provided in the inputTranscipt value of the event.
I'm assuming you have Lex connected directly to Slack, and that you are using a Lambda Function.
In Lambda, you will have to parse the inputTranscript and fill the slot yourself. You can try something like this (Node.js):
var userInput = event["inputTranscript"];

var email = userInput .split("|");
email = email[1].replace(">","");

console.log(email);
event["currentIntent"]["slots"]["email_address"] = email;

You should only do the above after user inputs their email. It will take the whole input from Slack, including the mailto: wrapper tag and split that in half as an array. Then it takes the second half and removes the ">" at the end. You should then be left with the pure email, as the user had originally input it. Then set that in the slot. As you pass the slots back to lex in the response, Lex will then recognize the email_address slot as filled.
You may have to process the inputTranscript often like this. I have found that keeping track of the last elicited slot in a sessionAttribute helps me determine where in the conversation I need to parse the input in specific ways.


text:
Q: Mark bad blocks as unusable on NTFS using linux one of my laptops are using windows and after a certain impact it doesn't boots up anymore, I figured the disk might've been damaged. So I've launced live Kali linux and scanned it with badblocks (like in this article) and found ten thousand of them (bad blocks). Now, how can I mark those blocks as unusable, because it seems that fsck doesn't work on NTFS.
badblocks /dev/sda > ~/bad_blocks

A: I'm afraid that won't help you get it to boot anyway. Most likely there are critical system files in those damaged blocks, and you cannot access those.
Your HD cannot be used anymore. The best you can do is to use ddrescue or similar tool to make a complete copy of the hard disk or what can be accessed from it to a file on another hard disk, and then use data recovery software on that hard disk image file.

A: I'm not aware of any publicly available Linux tool that supports this. It's in the plans for ntfsck from ntfsprogs, the most advanced publicly available package for NTFS (see ntfsprogs\ntfsck.c in its source), but that's about it. (You might be able to contract the developers to implement this for you. This isn't so hard technically, just time and effort.)
So, your best bet for now is to boot from a Windows live media (MS DaRT is the official one for repair tasks) and run chkdsk /r.
I also succeeded in booting from a Linux Live CD, sharing the block device with Samba, then mounting and checking it over the network from a Windows machine with ImDisk.
Alternatively, How to unmark an NTFS cluster as bad? outlines how to do this by hand. Basically, it's editing NTFS metadata in a hex editor.

A: All the bad blocks must be in one place as a scrach on the hard drive.
So, try to recover everything you can and make 2 partitions around the faulty area.


text: Q: Find the coordinates of the closest point between two lines in 3d space. I have not worked with 3d coordinate systems for a while and this is giving me a bit of a struggle. I have the coordinates of four points in XYZ. Two points I use to generate the line AB and the other two I use to generate line CD. I would like to find the closest XYZ coordinate on AB to line CD and the closest XYZ coordinate on CD to line AB. My idea was to find the equation for the perpendicular line between AB and CD and then find the intersection of this new line with AB and CD. However, I do not really know where to begin. If anyone could help that would be very much appreciated


text:
Q: Saving my LZ77 tags in the decompressed file for n java I implemented LZ77 algorithm in java and actually it works and outputs the tags correctly in the form <pos, len, next>. But I don't know how to save those tags in a file such that the total size of the file get lesser than the original one.
I tried to convert the tags to binary and save them to the file, but actually the file size got bigger.
Can anyone explain an algorithm to save the tags into the file?

A: The LZ77 specification doesn't indicate the encoding of the triples.  If you look at the Wikipedia page https://en.wikipedia.org/wiki/LZ77_and_LZ78, the "implementation" section shows how various implementations have output the triplets.
You are free to use one of these or implement your own.


text:
Q: A function like is_page() but returns true if on any sub page of given page In my header I use this code:
if(is_page("stores")) {
    // Do something
}

I run some code if on the page stores but what I want to do is run that code if the page is stores or any page that is a sub page of stores. Not only that, but is recursive so if we are on a sub sub sub page of stores the code still runs.

A: Testing for sub-Pages section of Conditional Tags article in Codex has fitting code example that uses get_post_ancestors() to retrieve parent tree and loops through it with check.

A: When using pretty permalinks, I simply check against the request;
if ( preg_match( '#^stores(/.+)?$#', $wp->request ) ) {
    // away we go!
}

No extra DB queries, little computation, and works right down the tree!

A: Handy little function
 function is_child_of($parent) {
    global $post;
    if ( $post->post_parent == $parent){
        return true
    }else{
        $curent_parent = $post->post_parent;
        $dec = false;
        while ($curent_parent > 0){
            $p = get_post($curent_parent);
            $curent_parent = $p->post_parent;
            if ($curent_parent > 0){
                if ($curent_parent == $parent){
                    return true;
                }
            }
        }
    return false;
}

Usage:
check if current is a child of a page with the ID of 22
if (is_child_of(22)){
  //its a child of 22
}


text:
Q: How do I access Ruby type names from within BasicObject How do I access Ruby type names from within BasicObject?  I understand that "... common classes will not be found without using a full class path", but I don't know the syntax for specifying the full class path.
The code below fails because Hash isn't imported into BasicObject.
class Basic < BasicObject
  def flexible(data)
    if (data.is_a?(Hash))
      puts "It's a hash!"
    end
  end
end

foo = Basic.new
foo.flexible({})

A: To answer your immediate question, you can access Hash like so:
if (data.is_a?(::Hash))
  puts "It's a hash!"
end

This will still fail for a different reason, which is because BasicObject doesn't include Kernel, so puts is not available:

undefined method `puts' for #<Basic:0x000055c405afbc88>

If you do this as well:
class Basic < BasicObject
  include ::Kernel

or this instead:
::Kernel.puts "It's a hash!"

Then it should work as expected.


text:
Q: Referencing an object array in C# PInvoke I'm building a spectrometry application which uses a C# GUI and a native C++ logical dll. I'm trying to make the dll fill an array of simple C++ structs passed by reference from the C# side. However, when I try to print the [supposed to be filled] array elements, I'm getting System.NullReferenceExceptions and the array elements are marked as null in memory.
Here is the C++ struct definition and method implementation:
typedef struct intensitytype {
    unsigned short usEchelleOrder;      // echelle order
    unsigned short usPixel;             // horizontal camera pixel index (unbinned !!)
    double dIntensity;                  // intensity
    double dWaveLen;                    // wave length [nm]
} intensitytype;

void CameraControl::getResults(intensitytype* graphData)
{
    graphData = _spectroData; // _spectroData is a pointer to a dynamic intensitytype array.
}

Here are the C# class definition and signature
[StructLayout(LayoutKind.Sequential)]
    public class intensitytype
{
    public ushort usEchelleOrder = 0;      // echelle order
    public ushort usPixel = 0;             // horizontal camera pixel index (unbinned !!)
    public double dIntensity = 0;                  // intensity
    public double dWaveLen = 0;                    // wave length [nm]
}

 [DllImport(@"Elemission.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void getResults(bool freeData, out intensitytype[] graphData);

I'm not sure what type of C# reference identifier is needed in this instance, or even if manual pointer marshalling is required. If one of you guys can point me in the right direction, I'd be forever grateful.

A: I finally found the solution to my problems, and am posting this for anyone who would need some clarification:
First, as David pointed out, simply treating the referenced argument as a pointer and assigning it the array's address does not work. You have to copy the entire array contents into the referenced array. Easily fixed.
The second mistake was in the C# method signature; the descripton that was needed here was "[Out]", with the brackets, compared to simply "out" (Once again, thanks David).
So, the end result:
The structs do not change, but the function signature in C# does:
[DllImport(@"Elemission.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void getResults([Out] intensityType[] graphData);

and here is a snippet of the function call:
int arraySize;
DllMethods.executeAcquisition(out arraySize); // arraySize is the Struct array length
intensityType[] resultData = new intensityType[arraySize];
DllMethods.getResults(resultData);

Meanwhile in C++, the C# call is received by the wrapper and passed to the member function...
__declspec(dllexport) void getResults(intensitytype* graphData)
{
    MainControl::getInstance()->getCamera()->getResults(graphData);
}

...and lo and behold, the struct array is filled.
void CameraControl::getResults(intensitytype* graphData)
{
    for (int i = 0; i < _spectroDataLength; i++)
        graphData[i] = _spectroData[i];
}


text:
Q: How line break content become one line paragraph? *strong text*what i want to do is from my breakline content to one line paragraph
example my var_dump result:
string(212) "(73857,"2012-02-02 03:18:44","TXT",60143836234);"
string(122) "(73858,"2012-02-02 03:20:08","WAP",60143836234);"
string(211) "(73859,"2012-02-02 08:21:47","TXT",60163348563,);"
What i want to become:
string(555) "(73857,"2012-02-02 03:18:44","TXT",60143836234);(73858,"2012-02-02 03:20:08","WAP",60143836234);(73859,"2012-02-02 08:21:47","TXT",60163348563,);"
update (here is my code, $i is the line break records, if I able to make the breakline to one line, i will put in a new file )
foreach($get_line_feed_content as $i) {
$add_special_char = "(".$i.");";

var_dump($add_special_char);

    if(!empty($i)){

        $stringData = $final_content;
        fwrite($save, $stringData);
        fclose($save);
    }
}

any idea?
Thank and highly appreciated your answer

A: Did you just want to glue the strings together? I don't see any line breaks from your dumps.
If that's the case, just do:
$finalString = $string1 . $string2 . $string3;
var_dump($finalString); //Strings should be glued as one.

If, however, each line is represented as an element in an array:
$stringsArray = array('string1', 'string2', 'string3');
$finalString = implode("", $stringsArray);
var_dump($finalString);

With your most recent update, this is what I would do:
$newString = '';

foreach($get_line_feed_content as $i) {
  $newString  .= "(".$i.");"; //concatenate

  var_dump($newString); //You will get a lot of dumps and with each dump, a new string should be appended to it.

    if(!empty($i)){
        fwrite($save, $newString);
        fclose($save);
    }
}

A: if you want to glue strings you can do like this:
$data = $string1.$string2.$string3;

If you have array of strings do like this:
$strings = array('text1','text2','text3');
$data = implode('', $strings);


text:
Q: Unexpected Character > when appending html - regex escape necessary? I wonder if someone can help me understand. I was getting an AJAX response of HTML and adding it to the DOM with jQuery's .appendTo(), and getting the error:
"Unexpected character >".
After plenty of Googling and elimination debugging, I discovered it was a JavaScript function:
function htmlEscape(str) {
  return String(str)
      .replace(/&/g, '&')
      .replace(/"/g, '"')
      .replace(/'/g, ''')
      .replace(/</g, '<')
      .replace(/>/g, '>');
}

Note the final replace. If I escape that right chevron, I'm good. I ran my code through a syntax checker early on (http://esprima.org/demo/validate.html) and it said everything was valid. So I wonder if anyone can explain why this issue arose?
Thanks!


text:
Q: GET http://localhost:3000/server/server.js net::ERR_ABORTED 404 (Not Found) I ma new to loopback .I am using mysql for backend . I am trying to display the list of Account into webpage but the problem when I run the applications , I am getting following errors in console windows ..
GET http://localhost:3000/server.js net::ERR_ABORTED 404 (Not Found)
vue.js:634 [Vue warn]: Do not mount Vue to  or  - mount to normal elements instead.
Here is code for server.js
// Copyright IBM Corp. 2016. All Rights Reserved.
// Node module: loopback-workspace
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

'use strict';

var loopback = require('loopback');
var boot = require('loopback-boot');

var app = module.exports = loopback();

app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    var baseUrl = app.get('url').replace(/\/$/, '');
    console.log('Web server listening at: %s', baseUrl);
    if (app.get('loopback-component-explorer')) {
      var explorerPath = app.get('loopback-component-explorer').mountPath;
      console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
    }
  });
};

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module)
    app.start();
});

Here is my html code ..
<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width">

Account List

          Id
          Email Address
          Created Date
          Updated Date

          {{account.id}}
          {{account.email}}
          {{account.createdAt}}
          {{account.lastModifiedAt}}

          Delete

    <form @submit.prevent="storeAccount">

        Email
        <input type="text" id="email" v-model="account.email">

        Created At
        <input type="text" id="createdAt" v-model="account.createdAt">

        Last Modified At
        <input type="text" id="lastModifiedAt" v-model="account.lastModifiedAt">

      <input type="reset" value="Clear" @click="reset">
      <input type="submit" value="Save User ">
    </form>

Hers is the screen shot when I run the applications .

A: Do you think that accessing /server.js is necessary?
Try creating separate controllers for your models.
Or try creating Models according to your need.
For reference: https://loopback.io/doc/en/lb3/Defining-models.html


text:
Q: HttpClient spike in memory usage with large response I'm working on a console app that take a list of endpoints to video data, makes an HTTP request, and saves the result to a file.  These are relatively small videos.  Because of an issue outside of my control, one of the videos is very large (145 minutes instead of a few seconds).
The problem I'm seeing is that my memory usage spikes to ~1 GB after that request is called, and I eventually get a "Task was cancelled" error (presumably because the client timed out).  This is fine, I don't want this video, but what is concerning is that my allocated memory stays high no matter what I do.  I want to be able to release the memory.  It seems concerning that Task Manager shows ~14 MB memory usage until this call, then trickles up continuously afterwards.  In the VS debugger I just see a spike.
I tried throwing everything in a using statement, re-initializing the HttpClient on exception, manually invoking GC.Collect() with no luck.  The code I'm working with looks something like this:
consumer.Received += async (model, ea) =>
{
    InitializeHttpClient(source);
    ...
    foreach(var item in queue)
    {
        await SaveFileFromEndpoint(url, fileName);
        ...
    }
}

and the methods:
public void InitializeHttpClient(string source)
{
    ...
    _client = new HttpClient();
    ...
}

public async Task SaveFileFromEndpoint(string endpoint, string fileName)
{
    try
    {
        using (HttpResponseMessage response = await _client.GetAsync(endpoint))
        {
            if (response.IsSuccessStatusCode)
            {
                using(var content = await response.Content.ReadAsStreamAsync())
                using (var fileStream = File.Create($"{fileName}"))
                {
                    await response.Content.CopyToAsync(fileStream);
                }
            }
        }
    }
    catch (Exception ex)
    {

    }
}

Here is a look at my debugger output:

I guess I have a few questions about what I'm seeing:

*

*Is the memory usage I'm seeing actually an issue?

*Is there any way I can release the memory being allocated by a large HTTP request?

*Is there any way I can see the content length of the request before the call is made and memory is allocated?  So far I haven't been able to find a way to find out before the actual memory is allocated.

Thanks in advance for your help!

A: If you use HttpClient.SendAsync(HttpRequestMessage, HttpCompletionOption) instead of GetAsync, you can supply HttpCompletionOption.ResponseHeadersRead, (as opposed to the default ResponseContentRead). This means that the response stream will be handed back to you before the response body has downloaded (rather than after it), and will require significantly less buffer to operate.

A: In addition to @spender's answers (which is on point), you need to also make sure that you dispose the response when you are done with it. You can find more information about this on "Efficiently Streaming Large HTTP Responses With HttpClient" article.
Here is a code sample:
using (HttpClient client = new HttpClient())
{
    const string url = "https://github.com/tugberkugurlu/ASPNETWebAPISamples/archive/master.zip";
    using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
    using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
    {
        string fileToWriteTo = Path.GetTempFileName();
        using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create))
        {
            await streamToReadFrom.CopyToAsync(streamToWriteTo);
        }
    }
}

You also need to take into account that you should not be creating an HttpClient instance per operation. HttpClientFactory is a very organised way to make sure that you flow the HttpClient within your app safely in a most performant way.


text:
Q: Converting a string with html entities to an array in the same order I have a string in this form :
dsds sdqsd test

and i want to put it in an associative array :
array('strong' => 'dsds' , 'em' => 'sdqsd' , 'underline' => 'test');

in a way that the order of elements int this array have to be the same as their order in the string .
which means if i have for example :
testdsds sdqsd

i get :
 array( 'underline' => 'test', 'strong' => 'dsds' , 'em' => 'sdqsd');

I tried doing it by using strpos in a loop but that's a lot of iterations specialy if i have a big string, so is there a simpler way using regex ?
Thanks.

A: 1, You can use tag names as array indexes only in case you have only one tage of each type per parsed HTML statement.
2, Maybe this library will help: http://simplehtmldom.sourceforge.net/
3, Or create custom parser using regular expression. That's solution that I really wont suggest because of big CPU performance requirements.


text:
Q: Change axis in polar plots in matlab to radians So matlab rightfully uses radians for trigonometric functions and in the actual plotting of polar plots. However annoyingly it puts the angular axis in degrees, is there any way to change this?

A: The text objects representing angular values are created by the polar function in the following section of its code (Matlab R2010b):
% annotate spokes in degrees
rt = 1.1 * rmax;
for i = 1 : length(th)
    text(rt * cst(i), rt * snt(i), int2str(i * 30),...
        'HorizontalAlignment', 'center', ...
        'HandleVisibility', 'off', 'Parent', cax);
    if i == length(th)
        loc = int2str(0);
    else
        loc = int2str(180 + i * 30);
    end
    text(-rt * cst(i), -rt * snt(i), loc, 'HorizontalAlignment', 'center', ...
        'HandleVisibility', 'off', 'Parent', cax);
end

Since 'HandleVisibility' is set to 'off' by the code, those text objects are not visible from outside the function, and thus you can't modify their 'String' property.
You can create a modified version of polar (save it with a different name, in a user folder) in which the above section is replaced by this:
% annotate spokes in degrees
rt = 1.13 * rmax;
text_strings = {'\pi/6'  '\pi/3'  '\pi/2'  '2\pi/3' '5\pi/6'  '\pi' ...
                '7\pi/6' '4\pi/3' '3\pi/2' '5\pi/3' '11\pi/6' '0'};
for i = 1 : length(th)
    text(rt * cst(i), rt * snt(i), text_strings{i}, ...
        'HorizontalAlignment', 'center', ...
        'HandleVisibility', 'off', 'Parent', cax);
    text(-rt * cst(i), -rt * snt(i), text_strings{i+6}, ...
        'HorizontalAlignment', 'center', ...
        'HandleVisibility', 'off', 'Parent', cax);
end

Comments on this code:

*

*Maybe you prefer to define text_strings without simplifying the fractions (i.e. '2\pi/6' instead of '\pi/3' etc).

*The 1.13 in the first line (originally 1.1) is fine-tuned to match the length of the strings. You may need to change that value is you use different strings

Here's an example result (I've called the modified function polar_rad.m):
theta = 0:.01:2*pi;
rho = sin(theta).^2;
polar_rad(theta, rho)


text:
Q: Android - SQL syntax error Here is my code, with unrelated stuff removed:
public class DataManager extends SQLiteOpenHelper
{
    private final static String DB_TABLE = "Nums";
    private ContentValues initialValues;
    private static SQLiteDatabase myDB;

    public DataManager()
    {
        initialValues = new ContentValues();
        if(null != myDB)
        {myDB.close();}
        myDB = getWritableDatabase();   // This causes NullPointerException which is next on my TODO list
    }

    public void addValues(String num, String val)
    {
        initialValues.clear();
        initialValues.put(num,val);
        myDB.insert(DB_TABLE, null, initialValues); // THIS LINE CAUSES ERROR
    }
}

I can CREATE the database but I can't INSERT without getting this error:
android.database.sqlite.SQLiteException: near "1": syntax error: , while compiling: INSERT INTO Nums(1) VALUES(?);
The database table Nums looks like this:
Num | Val
=========
1   |   23
2   |   34
3   |   6
4   |   3
5   |   5
6   |   56
7   |   34
8   |   45
9   |   32
10  |   23

As you can see, I'm trying to create a database with a list of numbers from 1 -> n where each number has a value beside it. All values in the database are String. There was a reason I didnt choose INT but cant remember now.... :(
Can anyone see where my syntax is wrong?
My phone is rooted so I can use an SQLite Browse app to view the database, and the table is created, its just empty!
Thanks.

A: The syntax for put is ContentValues.put(columnName, value). Try the following code.
public void addValues(String num, String val)
{
    initialValues.clear();
    initialValues.put("Num",num);
    initialValues.put("Val",val);
    myDB.insert(DB_TABLE, null, initialValues);
}

Just as some helpful suggestions, you don't need to save a reference to myDb. You can just always call getWritableDatabase() inside of your SqlLiteOpenHelper.


text:
Q: Screencapture of Unity AR view from native iOS I am trying to take a screenshot of my Unity view from the native iOS. My native iOS has been written in Xamarin.iOS
When a button click event fires on unity view, my native app fires a notification and callig a method in native side. Inside this native method I am trying to capture the screenshot of my current view(Unity AR view). This is my xamarin code to take the screenshot.
            UnityFramework _ufw;
            _view = _ufw.AppController().RootView;
            var mainLayer = _view.Window.Layer;

            mainLayer.RenderInContext(UIGraphics.GetCurrentContext());
            var img = UIGraphics.GetImageFromCurrentImageContext();
            img.SaveToPhotosAlbum((iRef, status) =>
            {
                if (status != null)
                {
                    new UIAlertView("Problem", status.ToString(), null, "OK", null).Show();
                }
                else
                {
                    new UIAlertView("Saved", "Saved", null, "OK", null).Show();
                }
            });
        }
        finally
        {
            UIGraphics.EndImageContext();
        }

My problem is it doesn't capture my AR view. Instead, it just capture a white view. I want to capture my Unity view which has some overlayed items on a camera view. How could I do this? Thank you!

A: This post helped me. So I replaced my below lnes
var mainLayer = _view.Window.Layer;
mainLayer.RenderInContext(UIGraphics.GetCurrentContext());

With
UIGraphics.BeginImageContextWithOptions(_view.Frame.Size, false, 0f);
_view.DrawViewHierarchy(_view.Frame, true);

Works like a charm


text:
Q: If $\frac{d}{c} > \frac{b}{a} +1$, is $a \ln(b+1)+c \ln(d-1)-a\ln(b)-c\ln(d)>0$? If $\dfrac{d}{c}>\dfrac{b}{a} +1$, is it true that
$$a \ln(b+1)+c \ln(d-1)-a\ln(b)-c\ln(d)>0?$$
where $a, b, c, d$ are integers, and $a, c \geq 1$, and $b, d \geq 2$.
It seems to be that it might be true (I've not been successful at finding a counterexample so far), but I've tried proving using the product and quotient rules, though to no avail.

A: Hint
$$a \ln(b+1)+c \ln(d-1)-a\ln(b)-c\ln(d)=\ln \left(\left(1+\frac{1}{b} \right)^a \left(1-\frac{1}{d} \right)^{c} \right)$$
Then use the given inequality
$\frac{c}{d}<\frac{a}{a+b}<\frac{a}{b}$
I think you can take it from here


text:
Q: Algebraic Object in Topology Common algebraic categories are group, ring, module and algebra. Some of them have the corresponding object in topology, like topological group and topological linear space. We define them by making operations continuous or smooth. So there are two questions left:

(1) Is it reasonable to generalize topological linear space to topological module? And instead of $\mathbb R$ or $\mathbb C$ as coefficient in functional analysis, can we use a ring $R$?
(2) How about topological ring and topological algebra? Are there any reference about them?

A: As for Topological Ring and Topological algebra are concerned they are important topics to study, for examples see this http://en.wikipedia.org/wiki/Topological_ring and http://en.wikipedia.org/wiki/Topological_algebra... infact there is a very nice book written on Rings of Continuous Functions by Gillman and Jerrison. The fact that study of topological groups find more applications is because they can be used to study symmetries and they first arose while studying groups of continuous transformations, both of which find immense utility in physics also.

A: These are all reasonably well-developed theories.  Bourbaki's General Topology has chapters on general topological rings and modules.  Warner has two monographs, Topological Rings and Topological Fields that go into more detail.


text:
Q: using node-inspector with meteor on windows I am trying to use node-inspector to help debug my meteor app on windows. As indicated here: https://docs.meteor.com/commandline.html#meteordebug
running meteor debug should start the node-inspector portal at http://localhost:8080/debug?port=5858 by default.
I can navigate to the url, but do not see any files under "Sources" (or anywhere for that matter)
I've tried setting the port manually, and tried installing node-inspector via npm as well in case it was needed, and tried running "meteor NODE_OPTIONS='--debug' ...but those don't seem to help (and the NODE_OPTIONS parameter doesn't even work...)
what am I missing/why don't the files show up? how can I debug this debuggng issue...?
PS - i do see Notifications permission has been blocked as the user has dismissed the permission prompt several times. See https://www.chromestatus.com/features/6443143280984064 for more information.
in the dev console on the debugger tab. Could this cause any issues? Not really sure what notification permissions I supposedly blocked.
UPDATE:
Also getting these 3 errors popping up in the console:

Runtime.js:358 Assertion failed: Unknown experiment canvasInspection
Runtime._assert @ Runtime.js:358
21:53:06.599 Runtime.js:367 TypeError: Cannot read property 'createSetting' of undefined
    at WebInspector.FilterBar.setName (:8080/ui/FilterBar.js:62)
    at WebInspector.NetworkPanel (:8080/network/NetworkPanel.js:47)
    at Function.WebInspector.NetworkPanel._instance (:8080/network/NetworkPanel.js:408)
    at eval (:8080/node/network/NetworkPanel.js:13)
    at eval (<anonymous>)
    at evaluateScript (Runtime.js:153)
    at scriptSourceLoaded (Runtime.js:136)
    at <anonymous>
Runtime._reportError @ Runtime.js:367
21:53:06.772 Runtime.js:367 TypeError: Cannot read property 'sources' of undefined
    at WebInspector.SourcesOverrides._hideChromeSpecifics (:8080/node/sources/SourcesOverrides.js:12)
    at WebInspector.SourcesOverrides (:8080/node/sources/SourcesOverrides.js:5)
    at eval (:8080/node/sources/SourcesOverrides.js:63)
    at eval (<anonymous>)
    at evaluateScript (Runtime.js:153)
    at scriptSourceLoaded (Runtime.js:136)
    at <anonymous>

many thanks for any help.


text:
Q: Highstock - custom x axis labels or force x axis labels for specific format Here's a simple highstock chart on JSFiddle.
http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/stock/xaxis/range/
You can see that the highstock chart, somehow figured out to display x-axis labels as
22nd Nov, 20 Dec, 17 Jan, 14 Feb....

How do I force this x-axis labels to display the 1st of each month? So for example, I would like it to display
1 Nov, 1 Dec, 1 Jan, 1 Feb...

Plus, if my x-axis range was set to the following
range: 1 * 30 * 24 * 3600 * 1000 // one month

I want to force-change the x-axis labels so that, instead of 1st of each month, I want to display
1 Jan, 7 Jan, 14 Jan, 21 Jan, 28 Jan

Basically, I'm looking for a way to change the x-axis labels to display the way I want.

A: First of all, do you need ordinal axis by Highstock? If not, then simply disable it and then set tickInterval, just like this: http://jsfiddle.net/vrzjp468/
    xAxis: {
        ordinal: false,
        range: 6 * 30 * 24 * 3600 * 1000, // six months
        tickInterval: 30 * 24 * 3600 * 1000
    },

And of course, when you need different case, like every two weeks, then set tickInterval: 14 * 24 * 3600 * 1000.
In case you need to use ordinal axis, then try to use tickPositioner.


text:
Q: Yii2 Facebook oauth - Integrity constraint violation: 1048 - Column'email' cannot be null I'm using Yii2 framework.
To log into my website, users can do it with the traditional way and with the Facebook login.
However, when user is already created using the traditional way, if they try to log in again but this time with the facebook button, the "integrity constraint violation window" shows up.
The message displays:
SQLSTATE[23000]: Integrity violation:1048 Column 'email' cannot be null. The SQL being executed was: INSERT INTO 'user'('username','email','oauth_client','oauth_user_id','password_hash','status'.........
CONTROLLER
class SignInController extends \yii\web\Controller

{

public function actions()
{
    return [
        'oauth' => [
            'class' => 'yii\authclient\AuthAction',
            'successCallback' => [$this, 'successOAuthCallback']
        ]
    ];
}

public function successOAuthCallback($client)
{
    $attributes = $client->getUserAttributes();
    $user = User::find()->where([
        'oauth_client' => $client->getName(),
        'oauth_client_user_id' => ArrayHelper::getValue($attributes, 'id')
    ])->one();
    if (!$user) {
        $user = new User();
        $user->scenario = 'oauth_create';
        /*echo '<pre>';   var_dump($attributes);exit;*/
        if ($client->getName() === 'facebook') {
            $user->username = ArrayHelper::getValue($attributes, 'id');
            $user->email = ArrayHelper::getValue($attributes, 'email');
        }
        if ($client->getName() === 'google') {
            $user->username = ArrayHelper::getValue($attributes, 'id');
            $user->email = ArrayHelper::getValue($attributes, 'emails.0.value');
        }
        $user->oauth_client = $client->getName();
        $user->oauth_client_user_id = ArrayHelper::getValue($attributes, 'id');
        $password = Yii::$app->security->generateRandomString(8);
        $user->setPassword($password);
        if ($user->save()) {
            $profileData = [];
            if ($client->getName() === 'facebook') {
                $profileData['firstname'] = ArrayHelper::getValue($attributes, 'first_name');
                $profileData['lastname'] = ArrayHelper::getValue($attributes, 'last_name');
            }
            if ($client->getName() === 'google') {
                $profileData['firstname'] = ArrayHelper::getValue($attributes, 'name.givenName');
                $profileData['lastname'] = ArrayHelper::getValue($attributes, 'name.familyName');
            }

            $user->afterSignup($profileData);
            $sentSuccess = Yii::$app->commandBus->handle(new SendEmailCommand([
                'view' => 'oauth_welcome',
                'params' => ['user'=>$user, 'password'=>$password],
                'subject' => Yii::t('frontend', '{app-name} | Tu nuevo usuario', ['app-name'=>Yii::$app->name]),
                'to' => $user->email
            ]));
            if ($sentSuccess) {
                Yii::$app->session->setFlash(
                    'alert',
                    [
                        'options'=>['class'=>'alert-success'],
                        'body'=>Yii::t('frontend', 'Welcome to {app-name}. Email with your login information was sent to your email.', [
                            'app-name'=>Yii::$app->name
                        ])
                    ]
                );
            }

        } else {
            // We already have a user with this email. Do what you want in such case
            if ($user->email && User::find()->where(['email'=>$user->email])->count()) {
                Yii::$app->session->setFlash(
                    'alert',
                    [
                        'options'=>['class'=>'alert-danger'],
                        'body'=>Yii::t('frontend', 'We already have a user with email {email}', [
                            'email'=>$user->email
                        ])
                    ]
                );
            } else {
                Yii::$app->session->setFlash(
                    'alert',
                    [
                        'options'=>['class'=>'alert-danger'],
                        'body'=>Yii::t('frontend', 'Error while oauth process.')
                    ]
                );
            }

        };
    }
    if (Yii::$app->user->login($user, 3600 * 24 * 30)) {
        return true;
    } else {
        throw new Exception('OAuth error');
    }
}

}
VIEW:
       <div>
               <?= yii\authclient\widgets\AuthChoice::widget([
                       'baseAuthUrl' => ['sign-in/oauth']
                ])?>
       </div>


text:
Q: Collisions between the player and enemy do not work anymore, Unity2D So I am working on a space shooter game, and I was changing the size of the box collider. And when I turned the game on there weren't any collisions happening between the player and the enemy. Collisions between the enemy and laser still worked though. I can't put images in here, but Stack Overflow provided me with some links to the images. If I didn't provide you with enough of the code or anything else, please say so. I don't know what is going wrong and it's killing me. So can you see what is wrong?
ps: I'm very new to Unity
Player code:
void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Enemy")
        {
                Damage();
        }
    }

Enemy code
void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Laser")
    {
    Destroy(other.gameObject);
    Destroy(this.gameObject);
    }

    if (other.tag == "Player")
    {
        Destroy(this.gameObject);
    }
}

Player Inspector
Enemy Inspector
Laser Inspector

A: [by "there weren't any collisions happening" do you mean

*

*the method "OnTriggerEnter" is not called or

*the methods in your if statements are not called?

For 1. Check if the player has a 2Dcollider attached.
For 2.: you use the "tag", did you tag the Player?
to fix some mistakes it is helpful to use:
Debug.Log("Enter message");
so you get a message in the console and can see if your Trigger even works or your if statement is the problem.]

edit: i looked up the inspectors and the player collider has the "IsTrigger" unchecked. not sure if that's the problem.

A: Your collider is unchecked in your player, also you need to check trigger in that collider.


text:
Q: Google Maps Polygon resize event I have an editable Polygon, just like here.
I want to "catch" the event when a user is moving the dot around the map (to resize the polygon). I need this functionality to implement snap to point.
Is it possible?
Edit
this.polygon = new google.maps.Polygon({
    map: map,
    strokeWeight: 2,
    editable: true,
    path: this._path
});

var dragging = false;
google.maps.event.addListener(this.polygon, 'mousedown', function (event) {
    if (event.vertex) {
        dragging = true;
    }
});
google.maps.event.addListener(this.polygon, 'mousemove', function (event) {
    if (dragging) {
        // dragging
    }
});
google.maps.event.addListener(this.polygon, 'mouseup', function (event) {
    dragging = false;
});

The code is working, events are catched. However, i can't access the current dragged point to change it's position.
I also tryied inside mousemove event to change the latLng object, but with no effect
Temporary Solution
You can't access the Polygon ghost while is resizing, so the only solution to implement the snapping is to do it after the polygon has been resized.
this.polygon = new google.maps.Polygon({
    map: map,
    strokeWeight: 2,
    editable: true,
    path: this._path
});

var path = this.polygon.getPath();
google.maps.event.addListener(path, 'set_at', function (event) {
    // Here do the snapping, after the polygon has been resized
});

google.maps.event.addListener(path, 'insert_at', function (event) {
    // Here do the snapping, after the polygon has been resized
});

A: Yes it's possible but not straight forward.
You would need to use a combination of events on the polygon object.
A PolygonMouseEvent object has three properties, edge, path and vertex. If the event occured over a vertex you will get the index of it otherwise it is undefined.
So if you try the following you may be able to build the functionality you want:

*

*Listen for the mousedown event.  If vertex is defined, then dragging = true.

*Listen for the mouseup event. Set dragging = false

*Listen for the mousemove event.  If dragging = true then get the mouse position. e.latLng and do your logic to snap it.

I haven't tried this, but with some tinkering you should get it working using this method.
If mousemove doesn't work try using mouseover.
If you give it a go and can't get it working, post your code so we can help.

A: Actually, the arguments passed to the set_at event handler are (index, object).  The index will correspond to the vertex modified.

A: Expanding on the answer from @SeainMalkin with code:
var draggingPolygonVertex = false;

google.maps.event.addListener(polygon, 'mousedown', function(mdEvent) {
    if(mdEvent.vertex || (mdEvent.vertex == 0)){
        draggingPolygonVertex = true;
    }
});

google.maps.event.addListener(polygon, 'mouseup', function(muEvent) {
        draggingPolygonVertex = false;
});

google.maps.event.addListener(polygon, 'mousemove', function(mmEvent) {
    if(draggingPolygonVertex){
        // you're now dragging a vertex of the polygon
        // insert snap to grid code
    }
});

A: I've solved a similar problem putting together the solution Seain Malkin suggested and the solution suggested here (thanks to both).
Instead of registering a "google event listener" for mousemove  to  polygon I've registered a DOM event listener to the maps div (useCapture parameter set to true, especially to work with Firefox):
map.getDiv().addEventListener('mousemove', function (e) {
    if (drawing) {
        var latLng = getLatLngByOffset( map, e.clientX, e.clientY );
        // dragging
    }
}, true);

A: I think the right answer is this:
path.addListener('bounds_changed', function (event) {
    // Here do the snapping, after the polygon has been resized
});

A complete example is here: Google Doc example


text:
Q: bell was ringing OR rang Replace the bold part with correct one:

*

*The bell was ringing and ringing but no one picked up the phone.

(a) rang and rang                      (b) rang repeatedly (answer sheet)
(c) was ringing repeatedly (my answer) (d) No improvement
Why option C is incorrect here? B could also be a possible answer, but i don't see why C is wrong here.

A: This question is not really about what is correct or incorrect. It's about what is most appropriate or idiomatic. And while I would opt for (b) as the most likely answer, it's not the only correct answer. Much depends on the context.
(a) >The bell was ringing and ringing but no one picked up the phone.
This past continuous tense, which emphasises the continuous ringing of the bell by repetition, might well be used by someone telling a story. The speaker tries to keep the action alive by using a tense close to the historic present. It implies that the event is not yet over.
(b) >The bell rang and rang but no one picked up the phone.
The use of the past tense implies that the event is over. This a perfectly acceptable and correct sentence if not quite as neat as (b).
(c)>The bell was ringing repeatedly but no one picked up the phone.
Like (a) this sentence keeps the action alive if a speaker is giving a dramatic account of an event. It is also correct but most likely to be used in a specific context.
For example, it's the tense that a speaker might use to describe a fire, as in:

The fire was burning fiercely but there was no sign of the fire brigade.

A: rang repeatedly is the most correct answer in this situation. It seems the multiple choice answers you were provided were done in a way so that every sentence sounds correct to the English speaking ear, however (b) would be considered most correct because it achieves its purpose in the sentence in the least redundant/most concise manner possible.
I've spoken English all my life and was ringing repeatedly sounds correct, but rang repeated is the best way to say it, and is likely the most common way/sophisticated way to say that something was ringing and ringing


text:
Q: Cohomology of pushforwards of vector bundles over the projectivization of a vector bundle Let $p:\mathcal E\to X$ be a vector bundle over a smooth projective variety $X$ and $p':\mathbb P\mathcal E\to X$ its projectivization.
We consider, then,  two vector bundles: $\mathcal B$ over the total space of $\mathcal E$, and $\mathcal B'$ over the total space of the projectivization $\mathbb P \mathcal E$.
EDIT: $\mathcal B'$ is the bundle obtained by $\mathcal B$ projectivizing the fibers of $\mathcal E$.
Is it possible to deduce the cohomology of $p_*\mathcal B$ by the cohomology of $p'_*\mathcal B'$ or vice versa?


text:
Q: UISearchBar in UITableView I'm trying to add a search function to my tableview. I've started by creating the UITableView, which works perfect. The problem is when I start writing in the search bar I get this error:
Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[<__NSCFString 0x8c44c00> valueForUndefinedKey:]:
this class is not key value coding-compliant for the key name.'

Then i've added the searchbar and searchdisplay to the viewcontroller.
searchdisplaycontroller outlets:

viewcontroller outlets:

in viewdidload
self.filteredArray = [NSMutableArray arrayWithCapacity:[finalArray count]];

numberOfRows method:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        NSLog(@"lol");
        return [filteredArray count];
    } else {
        return [rows count];
    }

}

rest of the methods:
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
    // Update the filtered array based on the search text and scope.
    // Remove all objects from the filtered search array
    [self.filteredArray removeAllObjects];
    // Filter the array using NSPredicate
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];
    filteredArray = [NSMutableArray arrayWithArray:[finalArray     filteredArrayUsingPredicate:predicate]];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    // Tells the table data source to reload when text changes
    [self filterContentForSearchText:searchString scope:
     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller     shouldReloadTableForSearchScope:(NSInteger)searchOption {
    // Tells the table data source to reload when scope bar selection changes
    [self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:
     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

A: The problem is with your predicate. If you see in the error message, it says this class is not key value coding-compliant for the key name.'
In your predicate,
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];

you're searching for the text on a property that doesn't exist (name). Without seeing more of your code or knowing more of what you're trying to accomplish, changing the predicate to say @"SELF contains..." instead of @"SELF.name contains..." should do the trick.
You can see the Apple docs on predicates or this article for more information.


text:
Q: Embedded python interpreter won't use virtual conda environment I am trying to build a C++ program that embeds the python interpreter using pybind11. I am using Visual Studio 2019 on Windows with a C++ project (not CMake).
I want to use the packages that are inside a virtual conda environment (Anaconda3/envs/pytorchenv) rather than the root environment. The problem that I can't seem to get past is that the program uses the python installation in the Anaconda root environment no matter what I do.
Even if I "conda activate" the virtual environment in an Anaconda prompt before launching the program - it still uses the root environment. (I'm not sure if "conda activate" is supposed to modify PATH, but when I check my system environment variables, it doesn't change them).
I'm guessing there is something I can set in my Visual Studio project settings to indicate that I want pybind11 to use the virtual environment instead of the conda base path. Any help would be greatly appreciated. Thanks!


text:
Q: POST request to IBM Watson Relationship extraction returns error In Bluemix, I am trying to call the IBM Watson relationship extraction API from Python. First off I create an application on Bluemix and bing the relationship extractor api to it. Then from the drop-down menu on the API I get the user name and password from the instantiating credentials. Which in the coe below I have replaced with bluemux-username and bluemix-password. The Python code I wrote for this is as follows:
import requests
import json

url="https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
username="bluemix_username"
password="bluemix_passowrd"
with open ("data.txt", "r") as myfile:
    text=myfile.read().replace('\n', '')

raw_data = {
    'contentItems' : [{
        'contenttype' : 'text/plain',
        'content': text
    }]
}

input_data = json.dumps(raw_data)

response = requests.post(url, auth=(username, password), headers =   {'content-type': 'application/json'}, data=input_data)
try:
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print("And you get an HTTPError: %s"% e.message)

However, when I run this I get the following error:
And you get an HTTPError: 400 Client Error: Bad Request

*Note: I used the same method for the personality insights API and that worked.
Any ideas?
Thanks

A: Here's an updated copy of your code that should work:
import requests
import json

url="https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
username="bluemix_username"
password="bluemix_passowrd"
with open ("data.txt", "r") as myfile:
    text=myfile.read().replace('\n', '')

input_data = {
    'sid' : 'ie-en-news',
    'txt' : text
}

response = requests.post(url, auth=(username, password), data=input_data)
try:
    response.raise_for_status()
    print response.text
except requests.exceptions.HTTPError as e:
    print("And you get an HTTPError: %s"% e.message)

Basically I changed the payload you were posting to add some missing values.
Hope this helps!

A: If you don't want to use data.txt and use the standard input in your terminal,  you can do:
## -*- coding: utf-8 -*-

import os
import requests
import fileinput

class RelationshipExtractionService:
    url = None

    def __init__(self):
        self.url = "https://gateway.watsonplatform.net/relationship-extraction-beta/api/v1/sire/0"
        self.user = "<username>"
        self.password = "<password>"

    def extract(self, text):
        data = {
            'txt': text,
            'sid': 'ie-en-news',  # English News, for Spanish use: ie-es-news
            'rt': 'xml',
        }

        r = requests.post(self.url,
                          auth=(self.user, self.password),
                          headers = {
                              'content-type': 'application/x-www-form-urlencoded'},
                          data=data
                          )
        print("Request sent. Status code: %d, content-type: %s" %
              (r.status_code, r.headers['content-type']))
        if r.status_code != 200:
            print("Result %s" % r.text)
            raise Exception("Error calling the service.")
        return r.text

if __name__ == '__main__':
    service = RelationshipExtractionService()
    for line in fileinput.input():
        print service.extract(line)

Usage
Simple text analysis:
echo "New York is awesome" | python main.py
You can also pipe a file:
cat article.txt | python main.py
From .txt to .xml:
cat article.txt | python main.py > article.xml


text:
Q: How to make a random object in this code? I found this script on the internet, and decided to put the standard asterisks, font ones. The font itself was connected via CSS. In the JS file I indicated what snowflakes are needed to fall. But if I put them, they fall in groups of three snowflakes in a line, but not randomly and not one by one:

var snowmax=25;
var snowcolor=new Array("#AAAACC","#DDDDFF","#CCCCDD","#F3F3F3","#F0FFFF","#FFFFFF","#EFF5FF")
var snowtype=("Arial");
var snowletter=new Array("\u2744 \u2743 \u2742",);
var sinkspeed=0.5;
var snowmaxsize=30;
var snowminsize=8;
var snowingzone=1;

var snow=new Array();
var marginbottom;
var marginright;
var timer;
var i_snow=0;
var x_mv=new Array();
var crds=new Array();
var lftrght=new Array();
var browserinfos=navigator.userAgent;
var ie5=document.all&&document.getElementById&&!browserinfos.match(/Opera/);
var ns6=document.getElementById&&!document.all;
var opera=browserinfos.match(/Opera/);
var browserok=ie5||ns6||opera;
function randommaker(range) {
    rand=Math.floor(range*Math.random());
    return rand;
}
function initsnow() {
    if (ie5 || opera) {
        marginbottom=document.body.clientHeight;
        marginright=document.body.clientWidth;
    }
    else if (ns6) {
        marginbottom=window.innerHeight;
        marginright=window.innerWidth;
    }
    var snowsizerange=snowmaxsize-snowminsize;
    for (i=0;i<=snowmax;i++) {
        crds[i]=0;
        lftrght[i]=Math.random()*15;
        x_mv[i]=0.03+Math.random()/10;
        snow[i]=document.getElementById("s"+i);
        snow[i].style.fontFamily=snowtype[randommaker(snowtype/length)];
        snow[i].size=randommaker(snowsizerange)+snowminsize;
        snow[i].style.fontSize=snow[i].size+"px";
        snow[i].style.color=snowcolor[randommaker(snowcolor.length)];
        snow[i].sink=sinkspeed*snow[i].size/5;
        if (snowingzone==1) {snow[i].posx=randommaker(marginright-snow[i].size)}
        if (snowingzone==2) {snow[i].posx=randommaker(marginright/2-snow[i].size)}
        if (snowingzone==3) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/4}
        if (snowingzone==4) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/2}
        snow[i].posy=randommaker(2*marginbottom-marginbottom-2*snow[i].size);
        snow[i].style.left=snow[i].posx+"px";
        snow[i].style.top=snow[i].posy+"px";
    }
    movesnow();
}
function movesnow() {
    for(i=0;i<=snowmax;i++) {
        crds[i]+=x_mv[i];
        snow[i].posy+=snow[i].sink;
        snow[i].style.left=snow[i].posx+lftrght[i]*Math.sin(crds[i])+"px";
        snow[i].style.top=snow[i].posy+"px";
        if (snow[i].posy>=marginbottom-2*snow[i].size || parseInt(snow[i].style.left)>(marginright-3*lftrght[i])) {
            if (snowingzone==1) {snow[i].posx=randommaker(marginright-snow[i].size)}
            if (snowingzone==2) {snow[i].posx=randommaker(marginright/2-snow[i].size)}
            if (snowingzone==3) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/4}
            if (snowingzone==4) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/2}
            snow[i].posy=0;
        }
    }
    var timer=setTimeout("movesnow()",50);
}
for (i=0;i<=snowmax;i++) {
    document.write(""+snowletter+"");
}
if (browserok) {
    window.onload=initsnow;
}

I'm not strong in JavaScript, and therefore my question: How to make it fall randomly, and one at a time? I am not able to find the solution myself.

A: If you're just looking for one snowflake instead of the trio falling then isn't it just the snowletter declaration at the top that's giving you the the trio... change it to just one \u character and you get one...
var snowletter=new Array("\u2744 \u2743 \u2742",);

change to
var snowletter=new Array("\u2744");

see https://jsfiddle.net/Abeeee/m0aq57ng/

A: Change your snowletter to array of snows: new Array("\u2744", "\u2743", "\u2742") and change how you pick snow randomly: snowletter[Math.floor(Math.random()*snowletter.length)]
Example code:

var snowmax=25;
var snowcolor=new Array("#AAAACC","#DDDDFF","#CCCCDD","#F3F3F3","#F0FFFF","#FFFFFF","#EFF5FF")
var snowtype=("Arial");
var snowmax=25;
var snowcolor=new Array("#AAAACC","#DDDDFF","#CCCCDD","#F3F3F3","#F0FFFF","#FFFFFF","#EFF5FF")
var snowtype=("Arial");
var snowletter=new Array("\u2744", "\u2743", "\u2742");
var sinkspeed=0.5;
var snowmaxsize=30;
var snowminsize=8;
var snowingzone=1;

var snow=new Array();
var marginbottom;
var marginright;
var timer;
var i_snow=0;
var x_mv=new Array();
var crds=new Array();
var lftrght=new Array();
var browserinfos=navigator.userAgent;
var ie5=document.all&&document.getElementById&&!browserinfos.match(/Opera/);
var ns6=document.getElementById&&!document.all;
var opera=browserinfos.match(/Opera/);
var browserok=ie5||ns6||opera;

function randommaker(range) {
    rand=Math.floor(range*Math.random());
    return rand;
}

function initsnow() {
    if (ie5 || opera) {
        marginbottom=document.body.clientHeight;
        marginright=document.body.clientWidth;
    }
    else if (ns6) {
        marginbottom=window.innerHeight;
        marginright=window.innerWidth;
    }
    var snowsizerange=snowmaxsize-snowminsize;
    for (i=0;i<=snowmax;i++) {
        crds[i]=0;
        lftrght[i]=Math.random()*15;
        x_mv[i]=0.03+Math.random()/10;
        snow[i]=document.getElementById("s"+i);
        snow[i].style.fontFamily=snowtype[randommaker(snowtype/length)];
        snow[i].size=randommaker(snowsizerange)+snowminsize;
        snow[i].style.fontSize=snow[i].size+"px";
        snow[i].style.color=snowcolor[randommaker(snowcolor.length)];
        snow[i].sink=sinkspeed*snow[i].size/5;
        if (snowingzone==1) {snow[i].posx=randommaker(marginright-snow[i].size)}
        if (snowingzone==2) {snow[i].posx=randommaker(marginright/2-snow[i].size)}
        if (snowingzone==3) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/4}
        if (snowingzone==4) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/2}
        snow[i].posy=randommaker(2*marginbottom-marginbottom-2*snow[i].size);
        snow[i].style.left=snow[i].posx+"px";
        snow[i].style.top=snow[i].posy+"px";
    }
    movesnow();
}

function movesnow() {
    for(i=0;i<=snowmax;i++) {
        crds[i]+=x_mv[i];
        snow[i].posy+=snow[i].sink;
        snow[i].style.left=snow[i].posx+lftrght[i]*Math.sin(crds[i])+"px";
        snow[i].style.top=snow[i].posy+"px";
        if (snow[i].posy>=marginbottom-2*snow[i].size || parseInt(snow[i].style.left)>(marginright-3*lftrght[i])) {
            if (snowingzone==1) {snow[i].posx=randommaker(marginright-snow[i].size)}
            if (snowingzone==2) {snow[i].posx=randommaker(marginright/2-snow[i].size)}
            if (snowingzone==3) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/4}
            if (snowingzone==4) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/2}
            snow[i].posy=0;
        }
    }
    var timer=setTimeout("movesnow()",50);
}

for (i=0;i<=snowmax;i++) {
    document.write(""+snowletter[Math.floor(Math.random()*snowletter.length)]+"");
}

if (browserok) {
    window.onload=initsnow;
}

A: The line which groups three snowfakes together is here:
var snowletter=new Array("\u2744 \u2743 \u2742",);

To just use one of those three by random, change this line to:
var snowletter="\u2744\u2743\u2742";

And also change the following line:
document.write(""+snowletter+"");

To:
document.write(""
               + snowletter[Math.floor(Math.random()*snowletter.length)]
               +"");

Here you see the result:

var snowmax=25;
var snowcolor=new Array("#AAAACC","#DDDDFF","#CCCCDD","#F3F3F3","#F0FFFF","#FFFFFF","#EFF5FF")
var snowtype=("Arial");
var snowletter="\u2744\u2743\u2742";
var sinkspeed=0.5;
var snowmaxsize=30;
var snowminsize=8;
var snowingzone=1;

var snow=new Array();
var marginbottom;
var marginright;
var timer;
var i_snow=0;
var x_mv=new Array();
var crds=new Array();
var lftrght=new Array();
var browserinfos=navigator.userAgent;
var ie5=document.all&&document.getElementById&&!browserinfos.match(/Opera/);
var ns6=document.getElementById&&!document.all;
var opera=browserinfos.match(/Opera/);
var browserok=ie5||ns6||opera;
function randommaker(range) {
    rand=Math.floor(range*Math.random());
    return rand;
}
function initsnow() {
    if (ie5 || opera) {
        marginbottom=document.body.clientHeight;
        marginright=document.body.clientWidth;
    }
    else if (ns6) {
        marginbottom=window.innerHeight;
        marginright=window.innerWidth;
    }
    var snowsizerange=snowmaxsize-snowminsize;
    for (i=0;i<=snowmax;i++) {
        crds[i]=0;
        lftrght[i]=Math.random()*15;
        x_mv[i]=0.03+Math.random()/10;
        snow[i]=document.getElementById("s"+i);
        snow[i].style.fontFamily=snowtype[randommaker(snowtype/length)];
        snow[i].size=randommaker(snowsizerange)+snowminsize;
        snow[i].style.fontSize=snow[i].size+"px";
        snow[i].style.color=snowcolor[randommaker(snowcolor.length)];
        snow[i].sink=sinkspeed*snow[i].size/5;
        if (snowingzone==1) {snow[i].posx=randommaker(marginright-snow[i].size)}
        if (snowingzone==2) {snow[i].posx=randommaker(marginright/2-snow[i].size)}
        if (snowingzone==3) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/4}
        if (snowingzone==4) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/2}
        snow[i].posy=randommaker(2*marginbottom-marginbottom-2*snow[i].size);
        snow[i].style.left=snow[i].posx+"px";
        snow[i].style.top=snow[i].posy+"px";
    }
    movesnow();
}
function movesnow() {
    for(i=0;i<=snowmax;i++) {
        crds[i]+=x_mv[i];
        snow[i].posy+=snow[i].sink;
        snow[i].style.left=snow[i].posx+lftrght[i]*Math.sin(crds[i])+"px";
        snow[i].style.top=snow[i].posy+"px";
        if (snow[i].posy>=marginbottom-2*snow[i].size || parseInt(snow[i].style.left)>(marginright-3*lftrght[i])) {
            if (snowingzone==1) {snow[i].posx=randommaker(marginright-snow[i].size)}
            if (snowingzone==2) {snow[i].posx=randommaker(marginright/2-snow[i].size)}
            if (snowingzone==3) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/4}
            if (snowingzone==4) {snow[i].posx=randommaker(marginright/2-snow[i].size)+marginright/2}
            snow[i].posy=0;
        }
    }
    var timer=setTimeout("movesnow()",50);
}
for (i=0;i<=snowmax;i++) {
   document.write(""
                  + snowletter[Math.floor(Math.random()*snowletter.length)]
                  +"");

}
if (browserok) {
    window.onload=initsnow;
}


text:
Q: Clear all the cookies even download a new browser but again show "ERR_TOO_MANY_REDIRECTS" error When i visit : here  then it shows "ERR_TOO_MANY_REDIRECTS" error. Honestly say that I Clear all the cookies even download a new browser but again show "ERR_TOO_MANY_REDIRECTS" error. How can i fix this issue?

A: It seems it is not a browser/cookie issue. There could be many reasons for this issue. Most common will be:

*

*The web server(Apache, Nginx, etc) is not properly configured.

*A bug in Backend(PHP etc) script redirection.

Please post some more details about server, scripts etc so, you can get a better help.


text:
Q: When calculating averages, why can we treat exploding die as if they're independent? I'm certain that I'm forgetting something basic, but here goes. The exploding dice is a (house) rule for some games that says when you roll the maximum result on a given die (e.g. 6 on a six-sided die) you roll that die again and add the result. If you roll the maximum value again, you roll again and add that. This will carry on until you stop rolling the maximum value.
From here, a natural question arises: "what's the average of an exploding die?". With the example of a six-sided die, the following answer comes naturally:
$3.5*+3.5*\frac{1}{6}+3.5*\frac{1}{6^2}\dots=4.2$
This does indeed seem to be correct, and holds to any empirical test that I can think of, but why does this work? I want to use some excuse to the effect of "expected value is linear and we've got identical distributions", but I find that unsatisfactory. In particular, I don't understand why we can use the average values of 3.5 when every term to the right of that 3.5 assumes that we've beat the average. I have no doubt that this is why we need the $6^{-n}$ terms, but my intuition insists that this is insufficient.
Note: What I really want here is to see the rigor. An ideal answer will attack this from the ground up, possibly even axiomatically. I'd hope that we don't have to go as deep as using probability measures on sets, but at the very least I want some answer that focuses on what property of averages allows us to factor the dice like this.

A: The series you have there represents

The expected value of the first die throw, plus the probability that you get a second throw times the expected value of the second die, plus the probability that you get a third throw times the expected value of the third throw, plus ...

It is basically what you get if you write down what the expectation is straight from the definition, and tidy up a little:
$$
\frac16\cdot1+\cdots+\frac16\cdot 5+\frac16\cdot \left(6+ \frac16\cdot1+\cdots+\frac16\cdot 5+\frac16\cdot \left(6+ \cdots \right) \right)
$$

A: Another way to look at it:
Let $E$ denote the answer.  Suppose you toss the die once.  One of two things happens..either you get a value below $6$ or you get a $6$ and start over (from which point, of course, you expect to get an additional $E$).  Thus we have $$E=\frac 16\times (1+2+3+4+5)+\frac 16\times (6+E)\implies E=\frac {21}5$$
as desired.

A: This does indeed come from linearity of expectation - but you have to be really careful about what exactly you're applying this theorem to. In particular, let's examine some random variables. In a given trial (i.e. you roll the dice until you get something other than $6$), let us define some quantities. First, let $X$ be the total achieved. Let $X_1$ be the portion of this due to the first roll and $X_2$ be the portion due to the second roll (which is $0$ if there was no second roll) and so on.
We then have that $X=X_1+X_2+X_3+\ldots$ noting that, almost certainly, there are only finitely many non-zero terms in the sum and also - in case we should later worry about issues of convergence - that these are all non-negative quantities, so we are justified in applying linearity of expectations to this to get
$$\mathbb E[X]=\mathbb E[X_1]+\mathbb E[X_2]+\ldots$$
Then, we just compute $\mathbb E[X_n]$. This is straightforwards: There is a $\frac{1}{6^{n-1}}$ chance that we will roll for an $n^{th}$ time and, given that we do roll, the expected roll is $3.5$ as it is just a typical die roll. So, $\mathbb E[X_n]=\frac{1}{6^{n-1}}\cdot 3.5$ as given in the solution which gives
$$\mathbb E[X]=(1+1/6+1/6^2+1/6^3+\ldots)\cdot 3.5$$
Note that, via this approach, we never consider whether a die actually was $6$ except in determining whether we reach the $n^{th}$ roll - that's because, to compute expectation, we are splitting into the cases of "I roll this die" and "I don't roll this die" which do not bias the roll of the die at all. Basically, we are allowed to imagine, while computing each expectation, that this is the last roll, regardless of whether we get a $6$ because no further information is relevant to the value of $X_n$.


text:
Q: OpenAL ALUT sound error After looking on the internet, I could not find an answer to my issue.
I am creating a game for a university assignment and for extra marks and I have decided to implement sound into my game.
I am using the OpenAL with ALUT .dll's. Here are the errors that I get.

Above the error list is me declaring the sound and things I need for sound.

A: It looks like you've forgot to link against some libraries.
Those error don't seem to have anything to do with OpenAL though.
Try and find out where the definition of tle::New3DEngine is and add this library to your additional dependencies (Project -> Linker -> Input).
You should also add %(AdditionalDependencies) which will hopefully get rid of the GetSystemMetrics linking error.


text:
Q: ExcelDNA Memory Space I am writing an application that has multiple potential user interfaces and I am using MEF to inject the appropriate implementation during startup. One implementaiton of IDisplay uses ExcelDNA (Excel is the interface). The code launches Excel as a process through
var processInfo = new ProcessStartInfo
{
    FileName  = PATH_TO_EXCEL,
    Arguments = PATH_TO_EXCELDNA_ADDIN
};

Process.Start(processInfo);

This works fine except that Excel is now in a seperate memory space so UI callbacks (i.e. Ribbon button clicks) cannot get access to any injected or assigned properties.
One possible solution is to launch Excel first then have ExcelDNA's AutoOpen() hook (which gets called once the add in has loaded in Excel) call the bootstrapper class to configure MEF however I'm wondering if it is possible to share memory between the C# and Excel processes? Would starting Excel via Excel.Application app = new Excel.Application { Visible = true; } resolve? I would try this but have not been able to find out how to specify the path of the ExcelDNA addin for it to load (like above).

A: Excel will always run as a separate process. So you can't share memory between the Excel process and another process. However, C# code can run inside the Excel process - this is exactly how an Excel-DNA add-in works.
You can also communicate between the Excel process and some other process. One option for this is to use the COM Automation interop - this is what you're doing when you call new Excel.Application from your own executable. You are starting a separate Excel process (or connecting to an existing running process), and then getting back an inter-process communication proxy (the Application object).
If you then want to tell that Excel process to load an Excel-DNA add-in, you can call Application.RegisterXLL(path_to_add_in) to have it load the .xll. How you hook up the Excel-DNA add-in and the rest of your code is still to be figured out.
You might still need some kind of cross-process communication, like .NET Remoting, WCF with named pipes or something like that.


text:
Q: How can I migrate MariaDB to Aurora I have running MariaDB Database and I want to migrate it to Amazon Aurora, how can I migrate It to Amazon Aurora

A: This migration is doable in multiple ways. Few questions to begin with :

*

*Which version of Maria DB are you currently on and which version of Aurora Mysql are you planning to move to?

*Are you already on RDS MariaDB? If yes, the migration might be a bit simple with snapshot restore.
If you are not currently on RDS MariaDB:

*

*MariaDB 10.0 to Aurora 5.6 and MariaDB 10.1, 10.2, 10.3 to Aurora 5.7 should be doable without much complications. This is based on the compatibility shown here: https://mariadb.com/kb/en/mariadb-vs-mysql-compatibility/ . You would most likely export your data using mysqldump and then import them via SQL apis or LOAD from S3 that Aurora supports.

*For any other migrations, you might need to do additional steps since you'd be crossing the compatibility boundaries.
Doc: https://docs.aws.amazon.com/dms/latest/sbs/CHAP_MySQL2Aurora.html
If you are already on RDS Maria DB:

*

*Try snapshot restore. A direct snapshot restore might not get you where you need to get, but thats the starting point for you.

Doc: https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Migrating.RDSMySQL.Import.html


text:
Q: React Hook UseEffect cannot be called at the top level I am getting this same error whether I use useEffect inside of my function component or out of it:
React Hook "useEffect" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
 import React, { useEffect } from "react";

const GetVerse = async () => {
  useEffect(async () => {
    const fetchVerse = await fetch(
      "https://bhagavad-gita3.p.rapidapi.com/v2/chapters/1/verses/null/"
    );
    const verseBody = await fetchVerse.json();
    console.log(verseBody);
  });
  return

;
};

export default GetVerse;

A: You component can't be async. But if you want to have an async useEffect, you have to do like this :
const GetVerse = () => { // component can't be async

  useEffect(() => { // useEffect callback can't be async either
    const fn = async () => { // declare an async function here
      const fetchVerse = await fetch(url)
      const verseBody = await fetchVerse.json()
      console.log(verseBody);
    }

    fn() // call the async function
  }, []) // don't forget to add dependency array here

  return

}

A: React Components and the useEfffect callback shouldn't be async. Here is a way to use await in the callback. The idea is to create a async function and then call it.
Also consider adding an empty array [] as the second parameter to useEffect as not putting this will cause infinite API calls.
import React, { useEffect } from "react";

const GetVerse = () => {
  useEffect(() => {
    async function getData() {
      const fetchVerse = await fetch(
        "https://bhagavad-gita3.p.rapidapi.com/v2/chapters/1/verses/null/"
      );
      const verseBody = await fetchVerse.json();
      console.log(verseBody);
    }
    getData();
  }, []);
  return

;
};

export default GetVerse;


text:
Q: Underfitting, Overfitting, Good_Generalization So as a part of my assignment I'm applying linear and lasso regressions, and here's Question 7.

Based on the scores from question 6, what gamma value corresponds to a
  model that is underfitting (and has the worst test set accuracy)? What
  gamma value corresponds to a model that is overfitting (and has the
  worst test set accuracy)? What choice of gamma would be the best
  choice for a model with good generalization performance on this
  dataset (high accuracy on both training and test set)?
Hint: Try plotting the scores from question 6 to visualize the
  relationship between gamma and accuracy. Remember to comment out the
  import matplotlib line before submission.

This function should return one tuple with the degree values in this order: (Underfitting, Overfitting, Good_Generalization) Please note there is only one correct solution.
I really need help, I can't really think of any way to solve this last question. What code should I use to determine (Underfitting, Overfitting, Good_Generalization) and why???
Thanks,
Data set: http://archive.ics.uci.edu/ml/datasets/Mushroom?ref=datanews.io
Here's my code from question 6:
from sklearn.svm import SVC
from sklearn.model_selection import validation_curve

def answer_six():
    # SVC requires kernel='rbf', C=1, random_state=0 as instructed
    # C: Penalty parameter C of the error term
    # random_state: The seed of the pseudo random number generator
    # used when shuffling the data for probability estimates
    # e radial basis function kernel, or RBF kernel, is a popular
    # kernel function used in various kernelized learning algorithms,
    # In particular, it is commonly used in support vector machine
    # classification

    model = SVC(kernel='rbf', C=1, random_state=0)

    # Return numpy array numbers spaced evenly on a log scale (start,
    # stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)

    gamma = np.logspace(-4,1,6)

    # Create a Validation Curve for model and subsets.
    # Create parameter name and range regarding gamma. Test Scoring
    # requires accuracy.
    # Validation curve requires X and y.

    train_scores, test_scores = validation_curve(model, X_subset, y_subset, param_name='gamma', param_range=gamma, scoring ='accuracy')

    # Determine mean for scores and tests along columns (axis=1)
    sc = (train_scores.mean(axis=1), test_scores.mean(axis=1))

    return sc

answer_six()

A: Well, make yourself familiar with overfitting. You are supposed to produce something like this: Article on this topic

On the left you have underfitting, on the right overfitting... Where both errors are low you have good generalisation.
And these things are a function of gamma (the regularizor)

A: Overfitting = your model false
if model false
scatter it
change linear to poly or suport vector with working kernel...
Underfitting = your dataset false
add new data ideal correleated ...
check by nubers
score / accuracy of test and train if test and train high and no big difference you are doiing good ...
if test low or train low then you facing overfitting / underfitting
hope explained you ...


text:
Q: Logout from JASIG server from browser I am trying to logout from JASIG CAS server running on tomcat.
I access my data from a nodeJS proxy and i have no idea how to logout.
I tried removing the cookie and it didnt help.
What is the right way to log out.

A: I have solved this issue at - https://github.com/fangli/kibana-authentication-proxy/issues/36


text:
Q: angularjs data not showing in view after retrieving from request Everyone.
I am facing a problem while loading data in the view.
my controller is
app.controller('AccountController', function(dataFactory,$scope,$http){
getResultsPage(1);
function getResultsPage(pageNumber) {

  if(! $.isEmptyObject($scope.libraryTemp)){
      if($.isEmptyObject($scope.searchText)){
        $scope.searchText = '';
        }
        if($.isEmptyObject($scope.account_type)){
        $scope.account_type = '';
        }
      dataFactory.httpRequest('/angular_project/public/accounts?search='+$scope.searchText+'&account_type='+$scope.account_type+'&page='+pageNumber).then(function(data) {
        $scope.data = data.account.data;
        $scope.accountType = data.account_type;
        $scope.totalItems = data.account.total;
        $scpoe.perpage = data.perpage;
      });
  }else{
    dataFactory.httpRequest('/angular_project/public/accounts?page='+pageNumber).then(function(data) {
      $scope.data = data.account.data;
      $scope.accountType = data.account_type;
      $scope.totalItems = data.account.total;
      $scope.perpage = data.perpage;
      console.log(data);
    });
  }
}
$scope.accounts_detail = function(id){
  dataFactory.httpRequest('accounts_detail/'+id).then(function(data) {console.log(data);
      $scope.sales_items_detail = data.sales_items_detail;
      $scope.mall_roakker_detail = data.mall_roakker_detail;
      $scope.transection_detail = data.transection_detail;
      console.log($scope.sales_items_detail);
      $scope.ddd = 'asdfasdf';
      //getResultsPage(1);
  });
}
});

my first view is:

                        {{ $index + 1 }}
                        {{ value.name }}
                        {{ value.address }}
                        {{ value.title }}
                        {{ value.check_from }}
                        {{ value.check_to }}

                        <button data-toggle="modal" ng-click="edit(value.id)" data-target="#edit-data" class="btn btn-primary">Edit</button>
                        Account Detail

problem is that while I click on Account Detail link data loaded from the database through but not showing in the related view that is.

Account Detail

                        Name
                        Item Name
                        Rate
                        Weight

                        {{ x.name }}
                        {{ x.title }}
                        {{ x.rate }}
                        {{ x.weight }}

in this view, data is not showing but console shows this data.

anybody can help me.
Thanks in advance

A: I think in your js file your $scope.accounts_detail = function (id){} not calling from anywhere.
call this function like
$scope.accounts_detail(id);


text:
Q: Could not import module ├── project
│   ├── app
│   │   ├── __init__.py
│   │   ├── models.py
│   │   ├── forms.py
│   │   ├── script.py

In models.py I have some classes, let's say Class1, Class2, Class3...
I can easily import these classes from models.py to forms.py using from app.models import Class1, Class2, ....
When script.py runs I can't import these classes to script.py this way. Have ModuleNotFoundError: No module named 'app' (in script.py) When I use from models import Class1, Class2, ... have the same error, but in models.py. If it's important models.py is genereted by Django, forms.py is created by me. This is strange for me because models.py and forms.py can recognize app module and script.py can't, but all these files are placed in one directory. Copy-pasted imports, this is not misprint.
What could be wrong?

A: If you're executing python script.py, move it to outside the app module.

A: In this setup I'd usually do something like this:
script.py being the main script would be in the project directory, next to app.
init.py would contain:
from app import models, forms

script.py would have
import app

If models.py needs anything in forms.py:
try:
    import forms # uses this when ran in models.py
except:
    from app import forms # uses this when ran from script.py

If forms.py needs anything in models.py:
try:
    import models # uses this when ran in forms.py
except:
    from app import models # uses this when ran from script.py


text:
Q: Find domain of the inequality $$
\frac{x}{x-1} \geq \frac{1}{e}
$$
I can see at $x=1$, it is undefined. But when I rearrange the inequality, like below.
$$
ex \geq x-1
$$
Now $x=1$ is not undefined. I am confused and do not know how it is possible and what is going on. Please explain. Thank you.

A: Hint. For $$x>1$$ we get $$x\geq \frac{x-1}{e}$$ and for $$x<1$$ we obtain $$x\le \frac{x-1}{e}$$


text:
Q: Android Studio Composite Build we have an android app and an android library. Now I want to rework some stuff in the lib and want the app to be also reworked (e.g. rename method etc.)
I found gradle composite builds. I was not able to use the little + button (link gradle project) in the gradle toolbar, as it is in IntelliJ. But I could make it work by using the
includeBuild ../android-lib

directive in settings.gradle
I also tried to add the dependency in the root build.gradle as follows:
tasks.register('run') {
    dependsOn gradle.includedBuild('../android-lib').task(':app:run')
}

The Lib is added in my projects/android tree and is also visible in gradle toolbar.
BUT it is not found in "show usages". Also, changes in the libary do not cause any compile errors in the root app.
I know this feature from eclipse ("workspace resultution"). Can't really believe that it is so hard to achieve in android studio?
Edit: found this old question, but at that time, the conposite build was just added and android studio was still eclipse-based: Android Studio nested composite build - plugin com.android.library not found
Edit2: Also tried to define the depencendy replacement:
//settings.gradle
includeBuild('../android-library') {
    dependencySubstitution {
        substitute module('de.example.android-lib:android-lib') with project(':android-lib')
    }
}

Edit3:
File -> New -> Import Module ... does also not work. This copies the files from the library's git into the app's repom which I definitely don't want.


text:
Q: Replace Symbol With Number In Text Within frac(), Using Mathematical Annotation in R Within my graph, I have included a label of the formula used to find the displayed data:
text(0,2,expression(paste(EMA[i], " = (", P[i], " x ",alpha,") + ",
EMA[i-1], " x (1-",alpha,") where ",alpha," = ", frac(2,1+N))),adj=0)

The first question - The above is part of a function I am creating, which N is an adjustable argument.  I would like the N above, within the frac brackets, to display whatever value N equals when the function is run.  Is this possible?
Second question, how can I replace each "x" with the actual multiplication symbol.  I was unable to find this, the search is a nightmare.
Thank you!

A: You can get this using bquote instead of expression and wrapping the N in .().  Also,  you can get the times sign by just using the appropriate Unicode character.
N = 3
plot(NULL, xlim=c(-1,4), ylim=c(-3,3))
text(0,2,bquote(paste(EMA[i], " = (", P[i], " × ",alpha,") + ",
EMA[i-1], " × (1-",alpha,") where ",alpha," = ", frac(2,1+.(N)))),adj=0)


text:
Q: Why is Geordi the only guy with a visor? There is one thing about Star Trek: The Next Generation that has always bothered me. Why is it that Geordi is the only one that has a visor?
There was literally no one else ever on the show that had one of those things. Is he really the only person in the Federation that was born blind? Even if he was, you would think that they would have them available for sighted people just so they can pick up all the cool wavelengths Geordi can see. How many times has he saved the day because he saw some interfero-whatsit-tachyon particle?

A: Geordi may have been the only crew-member with a VISOR but he wasn't the only blind character in Star Trek to use a sensing device.
In the original series, Miranda Jones uses an advanced Sensor Web to view her surroundings. The capabilities of this piece of kit seem very similar to Geordi's VISOR. Note that neither Kirk, nor Spock show bafflement at the technology itself, just the cleverness with which it's been hidden.

MCCOY: I'm sorry, Miranda, but you must be realistic. You are blind, and there are some things you simply cannot do.
(Spock touches the decorated over-dress she always wears.)
SPOCK: Evidently a highly sophisticated sensor web. My compliments to you, and to your dressmaker.
KIRK: Yes, of course. It's the only reasonable explanation. You can't see and Kollos can't hurt you.
SPOCK: An elegant solution. but I fail to understand why you apparently try to conceal your blindness, Doctor Jones.
KIRK: I think I understand. You said it. Pity is the worst of all.
MIRANDA: Pity, which I hate. Do you think you can gather more information with your eyes than I can with my sensors? I could play
  tennis with you, Captain Kirk. I might even beat you. I am standing
  exactly one metre, four centimetres from the door. Can you judge
  distance that accurately? I can even tell you how fast your heart is
  beating.

It's fairly obvious that in the future, blindness is relatively rare. When added to the quasi-military nature of Starfleet, that would certainly explain the relatively small number of blind characters that we see.

A: In the (much newer) series Star Trek: Lower Decks, other VISOR wearing people appear, for instance in the first episode of the first season 'Second Contact' (image from TrekCore)

A: He was the only one on the Enterprise. Nothing was ever said about him being unique in either Starfleet or the Federation. One could assume that his visor (excluding customizations to attempt to transmit what he was seeing) was by no means unique technology within the Federation; potentially there were other similarly sight-assisted personnel serving on other vessels. On the other hand, both Worf and Data were explictly (and repeatedly) described as unique in Starfleet.
From a real-world perspective: Geordi is blind (but has to be able to function somehow) because Roddenberry wanted to depict a future of inclusivity. It's part of the rationale behind Worf's character as well. Although Data's primary dramatic function is to be an outside observer of humanity, he's another example of an inclusive Starfleet.

A: The visor actually gives Geordi chronic headaches, not something that people would want to deal with at all times. Additionally he was told during one episode that technology had evolved to the point where he could get prosthetics. He would however lose the ability to view the additional wavelengths, and he didn't want to give up that ability.
Given the choice, most people I feel would choose to utilize a prosthetic approach, and look more "normal", especially with them not necessarily deriving a benefit from viewing the various spectrums that Geordi does being an engineer.
Another way to think of it is to ask yourself, why doesn't everyone now walk around with infrared goggles on? Because you'd look very silly. (Don't get me started with the "Nerd" glasses trend going on in the NBA.) Geordi himself eventually (as in the latter TNG-cast movies) exchanged his visor for a less conspicuous look(though this might also have been because on quite a few occasions the fact that he had the visor almost got him and others killed/tortured/captured).
Edit: I was going to try to look up the specific episodes I mentioned to provide sources, but it seems an arduous task for something so innocuous.


text:
Q: how different is the notion of an "indeterminate" from that of "algebraically independent" in relation to dimension theory? The following is a well-known theorem in commutative algebra, see e.g. Matsumura, Commutative Ring Theory, p. 117:
Let $A$ be a Noetherian ring and $X_1,\cdots,X_n$ indeterminates over $A$. Then $\dim A[X_1,\cdots,X_n] = \dim A + n$.
Question: I am trying to understand what exactly is meant by "indeterminates". Certainly, if the $X_i$ are indeterminate, then they are algebraically independent over $A$. Is the converse true? i.e. if $a_1,\cdots,a_n$ are elements in some ring extension of $A$ such that they are algebraically independent over $A$, then can we view them as indeterminates over $A$? If $A$ is a field, then certainly $\dim A[a_1,\cdots,a_n]=tr.deg_A A[a_1,\cdots,a_n] = n = \dim A + n$ and so the statement of the theorem holds. What if $A$ is not a field?

A: Yes, these are the same thing. One difficulty in seeing that this is so is that one might not have a tangible definition of "indeterminate". To remedy this, define the free commutative $A$-algebra on $n$ generators to be a commutative $A$-algebra $B$ with elements $X_1,\ldots,X_n$ such that, given another commutative $A$-algebra $C$ and choice of elements $c_1,\ldots,c_n$ in $C$, there is a unique $A$-algebra hom $B\to C$ such that $X_i\to c_i$. Then it's not hard to prove that "algebraically independent" and "indeterminate" are the same thing.