text:
Q: ID tokens vs Access tokens in implicit grant flow I would like some clarification on how to use ID tokens and access tokens in an implicit grant flow.
I have an Angular SPA using MSAL.js for Angular package and a Web API. The API does NOT call any external services, like MSFT Graph. The back end uses role claims from JWT to establish RBAC authorization to our API functionality only.
This doc says:
https://learn.microsoft.com/en-us/azure/active-directory/develop/id-tokens

id_tokens are sent to the client application as part of an OpenID Connect flow. They can be sent along side or instead of an access token, and are used by the client to authenticate the user.
ID Tokens should be used to validate that a user is who they claim to be and get additional useful information about them - it shouldn't be used for authorization in place of an access token.

This doc shows an authentication flow where a web API is called with an ID token instead of an access token:
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow
This sample code sends ID token too (calling own Web API sample):
https://github.com/Azure-Samples/active-directory-javascript-singlepageapp-dotnet-webapi-v2
The sample back end validates ID token audience against Client ID of the app that issued it.
Given our API is the only consumer of tokens, should we use ID tokens or access tokens?

A: Generally speaking, when securing your API with the Microsoft Identity platform, clients should be using the access token when making API requests, not the ID token.

A: check this part

It first calls acquireTokenSlient, which gets a token from the cache if available if not
it calls acquireTokenPopUp which will get an acces token for the specific scope, I am not sure if it would open up a popup window or will get a token in the background with hidden iframe. But it would fetch an access token for sure. API can never be accessed with ID token.
check https://learn.microsoft.com/bs-latn-ba/azure/active-directory/develop/scenario-spa-acquire-token for more clarification


text:
Q: ENOTFOUND: getaddrinfo ENOTFOUND api.heroku.com api.heroku.com:443 Error for heroku create My steps are below:

*

*Download the heroku-osx.pkg, and installed it.

*$ heroku login with my account and password

*cloned the ruby-getting-started: $ git clone https://github.com/heroku/ruby-getting-started.git

*But when I run $ heroku create in my Terminal.

Reports the error:

Creating app... !
   ▸    ENOTFOUND: getaddrinfo ENOTFOUND api.heroku.com api.heroku.com:443

I have find the related question in SO:

*

*I got error while using "git push heroku master"

*Hibernate unable to create schema automatically on Heroku postgres
But they are not when execute $ heroku create comes out the error.

A: It means that the connection between api.heroku.com with a port of 443 and to your PC failed and results to shutdown. Thus retrying the command will succeeds.

A: You may not be connected to the internet. Make sure to check your connection as it is required to complete this command.

A: The same was happening to me on Mac OS X 10.12.6 in iTerm2 3.1.5
Restarting iTerm solved the issue for me.

A: Carelessly, I don't know why, I tried several times of :
$ heroku create

It create succeed, with the logs:
Creating app... done, ⬢ still-harbor-32209
https://still-harbor-32209.herokuapp.com/ |
https://git.heroku.com/still-harbor-32209.git

So, I think try several times will solve it.

A: I experienced the same issue recently.
To debug this:
1) I tried restarting my terminal entirely CMD+Q, but still hit the timeout issue
2) I ran a whois on my-heroku-app.com and that command also timed out, even though I could connect to it through my browser
3) I disconnected my VPN and ran a whois command. This fixed the issue
After reconnecting my VPN, everything worked smoothly. Not sure what caused the hiccup, but I hope these steps help for anyone trying to debug this.

A: This happened to me when the internet temporarily cut out for a few seconds while I was trying to run a heroku command.
The Heroku CLI returned Error: getaddrinfo ENOTFOUND api.heroku.com
As soon as the internet connection was restored, everything was back to normal

A: I had a similar issue. my OS is windows, I solve this problem by restarting my command line and running the command all over and everything worked fine

A: The problem for me was network connection, by checking and re-establishing connection, it worked perfectly fine

A: I was getting the same , Because I was connected to VPN  and I think network was blocking the same . So disconnect VPN and try once.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Group by month based on DateTime Field I have a model for hotel reservations:
class PaymentRequest(SoftDeleteModel):
     class Meta:
        verbose_name_plural = "PaymentRequests"

    user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False, null=False, default=None)
    customer_first_name = models.TextField(blank=False, null=False)
    customer_last_name = models.TextField(blank=False, null=False)
    arrival_date = models.DateTimeField(blank=True, null=True)

What I'd like to do is make a queryset to group my reservations by month and get a count of it.
i.e {'jan' : 10, 'feb' : 11, etc..}
I've seen some answers like this but does not work quite right, maybe since it was answered 10 years ago.

A: I tried something on my already existing model and got a result but instead of 'jan', 'feb' I was able to get the month digit, see if this works for you or not
from django.db.models.functions import Extract

PaymentRequest.objects.annotate(month=Extract('arrival_date','month')).
                       values('month').annotate(dcount=Count('*')).
                       values('month','dcount')

Result would be something like this
<QuerySet [{'month': 2, 'dcount': 2}, {'month': 12, 'dcount': 1}]>


text:
Q: Difference between Typeset Superscript vs. Unicode Symbol for Superscript For a Unicode font, is there any difference in height, placement, etc. between rendered text of ^{superscript}, when compared to the Unicode character for superscript itself?
For instance: will the TeX output of ^2 be identical to ² (\u00B2) in e.g. XeLaTeX -- or a WYSIWYG document, for that matter?

A: You are talking about a math environment I guess (because you mention $^$).
I think the answer depends on the packages being loaded. In the example I think the package unicode-math actually makes $²$ to expand to and $^2$ (or something similar). Once this substitution is made the result (in math mode) is independent of the font selected.
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Cambria}
\usepackage{unicode-math} %try commenting this
\setmathfont{Cambria Math} %and this
\begin{document}
x² $x^2$ $x²$
\end{document}

When you comment the marked lines you will see that then the result is not similar (in font and positioning).

So it isn't a categorical answer but it covers a common case.


text:
Q: Retain summands in an expression that match a given rule Suppose we have the following expression
A[j_] := Subscript[A, j]
EXPR=A[1]^2*A[2] + A[1]^4*A[3] + A[2]^2

As stated in the title, I am struggling to retain some summands in EXPR, in particular the ones for which the sum of the product of the subscript and the power in each term is equal to some integer c. For instance, how to get all those terms that satisfy this rule with $c=4$? The correct answer is
A[1]^2*A[2] + A[2]^2

as in the first term we have $1\cdot 2+2\cdot 1=4$, whereas in the second one $2\cdot 2=4$

A: Pick[EXPR, EXPR /. {Plus -> List, Times -> Plus, Subscript -> (#2 &), Power -> Times}, 4]

% // TeXForm

$ A_2 A_1^2+A_2^2$

or
Select[EXPR, 4 == # /. { Times -> Plus, Subscript -> (#2 &), Power -> Times} &] // TeXForm

$A_2 A_1^2+A_2^2$


text:
Q: Content Assist Error in Spring STS I get the below error when I hit ctrl+space for Spring annotations autocompletion.

As soon as I hit ok button, I get the suggestions as expected.
I have tried other suggestions for disabling disabling subwords completion processsor and Java Proposals(Code Recommenders).
Disabling the subwords, works for me, but what if I don't want to disable this
 feature?
Disbaling the Java Proposals did stop the error dialogue from appearing, but I no more get the appropriate suggestions.
For example, while looking for "@Res..." I would normally want to see Spring's RestController listed in the suggestion, but its not there.
Any help in this regard is appreciated.


text:
Q: Count tags in an XML doc using Python I have a pretty complicated XML document, that I want to parse.
My first step is to count the number of < H > tags in my XML document.
Here is a simplified version of my XML:
<file>
    xmlns="http://www.namespace.co.il"
    <H Id="1012532" W="2198.05">
        ///more tags
    </H>
    <H Id="623478" W="3215.05">
        ///more tags
    </H>
   etc.
</file>

Now what I want to do is to count the H elements, so here is what I tried:
import xml.etree.ElementTree as ET
tree = ET.parse(xml_file)

ns = {'nmsp': 'http://www.namespace.co.il'}
count =1
for HH in tree.iterfind(str(ns['nmsp']+':H')):
   print count
   count=count+1

When I run this code, nothing is printed to the console.
Any idea why?

A: I think your question has already been answered.
The answer by zeekay is:
import lxml.etree
doc = lxml.etree.parse(xml)
count = doc.xpath('count(//author)')

(where, in your version, 'author' should be changed to 'H', I guess)
EDIT:
As to your own code (it took me some time to find it out):
Your loop should be
for HH in root.iterfind('nmsp:H', ns):

As is pointed out here, you need to give information about the namespace dictionary and not just the value under 'nmsp'.

A: Is this what you looking for?
tree.iterfind('{http://www.namespace.co.il}H')


text:
Q: How to fix 'EACCES (Permission denied)' error in android? I am trying to delete a file on an external SD storage in android by using the following code:
filename = "/storage/extSdCard/AAA/testtitle.mp3"
File file = new File(filename)
file.delete()

I am also using the two permissions
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

in the Manifest (outside the application declaration), and I am using the code suggested here. The device does not seem to be a Marshmellow device (first answer), and the suggested solution in the third answer also does not help. I still get the same error:
remove failed: EACCES (Permission denied) : /storage/extSdCard/AAA/testtitle.mp3

What else can I try?


text:
Q: how to extract specific elements from a file I have a file with the following snap
Name    age  class
John    12   3
Mark    10   1
Philip  15   6

delimiter between the columns are multiple spaces.
I want to print the highest number in class category
Please help and tell me how can I get the desired output.

A: awk 'NR > 1 && (max == "" || $NF > max) { max = $NF } END { print max }' file

This reads your file, and whenever the last field of any line, except the first line (which is a header line), is a numeric value greater than any one seen before, that value is remembered in the variable max.  The value is also remembered if no value has been remembered before.
At the end, the value of the variable max, which is the greatest value seen in the last field of any line (except the first), is printed.
This assumes that the class column is always at the end of each line.
The special variables NF and NR are the number of fields in the current record, and the number of records read so far, respectively. The value $NF is the value of the last field in the current record.
To get the whole line that has the largest number in the last column, only a couple of small modifications have to be made to the above code to also remember and print the relevant data:
awk 'NR > 1 && (max == "" || $NF > max) { max = $NF; line = $0 } END { print line }' file

A: sort has this function by defining the key position. You may try this:
sort --key=3 file


text:
Q: How do i change the formatting Aptana Studio does when using the format command? There are times where I will use the Aptana shortcut key for auto formatting my code.

Shift + cmd + f

It's the same as clicking

Source >> Format

My problem is that I don't always like some of the formatting it does for me. For example, when performing the auto format command. It will format my lists in HTML like this:

  Home

but I want it to format it like this:

Home

How can I make it format it like the second example?
I have tried

Preferences >> Aptana Studio >> Formatter

But it is very confusing on what and how to change. Are there any better ways of doing this?

A: *

*In Aptana, or Titanium Studio, open Window>Preferences... find Formatter (under Studio in Titanium Studio, I don't know the exact location in Aptana).

*Active profile: I created a new profile and saved it in (Win 7) %AppData/Local/Titanium Studio/, but you may be able to edit the Default Profile.

*Preview: Select HTML and click edit (pencil icon). You will see a list of exclusions of HTML elements on the left of the dialog.

*Click the Add button and type li in the dialog box. Click OK, OK, OK.
You may need to refresh your open file, but you do not need to restart the app.


text:
Q: Localization of the standard MS Data Connection Dialog The data connection dialog is a database tool component released with Visual Studio. It allows users to build connection strings and to connect to specific data sources. Its source code has been released on Code Gallery.

It's very useful, but the only problem is that its UI is always in English, regardless of the fact that it's run under a localized version of Windows.
Maybe I missed some tricks?
I tried to use it in a WPF app:
DataConnectionDialog dcd = new DataConnectionDialog();
DataConnectionConfiguration dcs = new DataConnectionConfiguration(null);
dcs.LoadConfiguration(dcd);

dcd.SelectedDataSource = DataSource.SqlDataSource;
dcd.SelectedDataProvider = DataProvider.SqlDataProvider;
...
if (DataConnectionDialog.Show(dcd) == System.Windows.Forms.DialogResult.OK)
{
  ...
}

A: Bad news: It's not localized by default
Good news: The project is easy localizable by adding the resources for the language that you need.


text:
Q: How to mark has_one/has_many association as dirty? I've been looking for this kind of functionality in AR, but don't seem able to find it. The Dirty implementation of AR states that an already persisted instance is deemed only dirty if one of its direct attributes has changed. So, let's say:
class Picture < ActiveRecord::Base
  belongs_to :gallery
  has_one :frame
end

in this case, I can do something like:
p = Picture.new(:gallery => Gallery.new, :frame => Frame.new)
p.save #=> it will save the three instances
p.gallery = Gallery.new
p.save #=> will not save the new gallery
p.gallery_id_will_change!
p.gallery = Gallery.new
p.save #=> this will save the new Gallery

but now I can't do something similar for the has_one association, since the Picture implementation doesn't own an attribute referring to it. So, it seems such dirty markups are impossible. Or aren't they?

A: Best thing I can figure out to do is:
class Picture < ActiveRecord::Base
  belongs_to :gallery
  has_one :frame

  after_save :force_save_frame

  def force_save_frame
    frame.save! if frame.changed?
  end
end

A: Like weexpectedTHIS said Dirty flags are set for attributes on the model itself, not for related objects. It only works for the belongs_to because there is a foreign key on the model.
But you can make a trick like that
module FrameDirtyStateTracking
  def frame=(frame)
    attribute_will_change!('frame')
    super
  end
end

class Picture < ActiveRecord::Base
  prepend FrameDirtyStateTracking

  belongs_to :gallery
  has_one :frame
end

picture = Picture.new
picture.frame = Frame.new
picture.changed? # => true
picture.changed # => ['frame']


text:
Q: How to prevent DB re-invoking when using SpEL in spring data projection? I have a spring projection with the method getItems() where @Value is SpEL to db call
  public interface CartInfoProjection {

  String getUser();

  ...

  @Value("#{@shipDetailsRepository.getItemsById(target.chcasn)}")
  List<ItemProjection> getItems();
  }

And repository class
public interface ShipDetailsRepository extends JpaRepository<AbstractEntity, Long> {

  @Query(
      nativeQuery = true,
      value =
          """
      select user,
        ...
      from PKQDVECFW6.chcart00,
           PKQDVECFW6.phpick00
      where chcasn = :chcasn
        and chpctl = phpctl
        and chstat < 25
  """)
  Optional<CartInfoProjection> getCartInfoById(@Param("chcasn") String chcasn);

  @Query(
      nativeQuery = true,
      value =
          """
      select ...
      from PKQDVECFW6.pdpick00,
           PKQDVECFW6.cdcart00
      where cdcasn = :chcasn
        and cdpkln = pdpkln
        and pdpctl = cdpctl
        and cdpaku > 0
   """)
  List<ItemProjection> getItemsById(@Param("chcasn") String chcasn);

Each time when I execute getItems() method it calls to db to retrieve items. How can I cache items?


text:
Q: Generate an URL? How to build an URL from vector variables? I pull account data from a database which returns a user_ID and a tag_ID.
  user_ID
> [1] "userId=111111"
  tag_ID
> [1] "tagId=222222"

With these two parameters, it allows me to check how many times the account has been viewed. I get there with a .json link like this:
check_url <- ("URL/account_views.json?userID=111111&tag_ID=222222")

 read_html(check_url)
> [1] {"numVisitsStr":"00203"}

My problem is that I want to build each link url with the proper User_ID and Tag_ID.
When using:
url2 <- paste("URL/account_views.json?", "user_ID", "tag_ID", sep = "")

this only provides:
> url2
[1] "URL/account_views.json?user_ID&tag_ID"

The real values do not get parsed. But I need the numbers; not the vector variables
How can I do this?
Thanks for all input!

A: Try :
user_ID <- "userId=111111"
tag_ID <- "tagId=222222"
paste0("URL/account_views.json?", user_ID, "&", tag_ID)
#[1] "URL/account_views.json?userId=111111tagId=222222"

Or you can use also use glue which is very convenient for such operations
glue::glue("URL/account_views.json?{user_ID}&{tag_ID}")
#URL/account_views.json?userId=111111&tagId=222222

where strings inside {} are treated as R code.


text:
Q: Meaning of "the Washington journalist I.F. Stone" What does "the Washington journalist I.F. Stone" imply in the following sentence?

The refugees who surround Palestine in their hundreds of thousands were described recently by the Washington journalist I.F. Stone as "the moral millstone around the neck of world Jewry."

1) I. F. Stone works in Washington.
2) I. F. Stone lives in Washington.
3) Something else.

A: The relevant implication is that I.F. Stone works (actually worked) in Washington.
When he worked for The Nation he was its Washington editor. If his home had been in Boston at the time, that is of no consequence to the sentence, which is about refugees and journalism.
By saying

the Washington journalist I.F. Stone

the sentence is identifying who I.F. Stone is (was).


text:
Q: analyze a file's fragmentation in Windows 7 Is there a way that I can determine the fragmentation of a single file via programmatic means?  For example, is there some type of file system API that I can tap into to retrieve this type of information?

A: I'm just copy and pasting Raymond's reply from the comments, so I've marked it as a community wiki answer.
For C/C++, use FSCTL_GET_RETRIEVAL_POINTERS. For C#, use these wrapper classes.

A: Here is a good C# wrapper for the FSCTL_GET_RETRIEVAL_POINTERS: http://blogs.msdn.com/b/jeffrey_wall/archive/2004/09/13/229137.aspx
This wrapper calls the control code to return back a list of an object that defines where each file is on disk.
You probably want the GetFileMap method to retrieve this information.


text:
Q: Configuring proxy.cgi in Windows using Apache and GeoServer? I want to dispaly my layers on a server. I'am using geoserver 2.3.2 and apache 2.4
Till now i Create a proxy file in referring in this link : http://trac.osgeo.org/openlayers/browser/trunk/openlayers/examples/proxy.cgi  and i Put it in cgi-bin folder.  I Installed python and in the starting line of proxy.cgi i put the location of python.  #!C:/Python27/python.exe -u
I found in some tutorials that i should configure the file httpd.conf  and i have no idea how to configure it and where should i add this code :
" ProxyRequests Off
ProxyPreserveHost On

Order deny,allow
Allow from all

ProxyPass /geoserver //localhost:8080/geoserver
ProxyPassReverse /geoserver //localhost:8080/geoserver "

A: Those settings look like they belong to an Apache 2.2 server. For your Apache 2.4 server you could instead try:
ProxyRequests Off
ProxyPreserveHost On

<Proxy /geoserver>
Require all granted
</Proxy>

ProxyPass /geoserver http://127.0.0.1:8080/geoserver
ProxyPassReverse /geoserver http://127.0.0.1:8080/geoserver

Which are part of the configuration settings for Apache and added to the httpd.conf file.
You could try also using the server IP or localhost instead of 127.0.0.1 in the ProxyPass and ProxyPassReverse sections, i.e.
ProxyPass /geoserver http://localhost:8080/geoserver
ProxyPassReverse /geoserver http://localhost:8080/geoserver

or
ProxyPass /geoserver http://<your server ip>:8080/geoserver
ProxyPassReverse /geoserver http://<your server ip>:8080/geoserver

To test whether the proxying of GeoServer via Apache is working you should browse to:
http://localhost/geoserver/web/

If this page opens then the Apache web server is correctly proxying the the GeoServer server.
To help you debug any issues with the Apache configuration open a command window and try:
httpd.exe -t

If you get an error "is not recognized as an internal or external command" then the Apache httpd.exe is not in your path, you will need to change to the directory that holds the httpd.exe file before running the command. The typical location for the httpd.exe file would be in the bin sub folder such as:
* C:\Apache24\bin\

Check too that at the top of the httpd.conf file that you have uncommented (remove the #) the modules that handle proxying like:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Answering other questions raised in the comments:
The call to the proxy.cgi file (like below) needs to go into your JavaScript code called by the HTML page in which you create your map.
OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=..."

The proxy.cgi file itself doesn't need to be placed in the cgi-bin folder of the Apache server; it can go anywhere but you need to enable this by editing the following directive in the Apache httpd.conf file like below (where "C:/Apache24/htdocs" is taken to be the document root).
<Directory "C:/Apache24/htdocs">
    # The Options directive is both complicated and important.
    # Please see http://httpd.apache.org/docs/2.4/mod/core.html#options
    #Options +FollowSymLinks +Includes

    # Adding +ExecCGI allows CGI scripts to run outside of cgi-bin (and similar) script folders
    Options +FollowSymLinks +Includes +ExecCGI

    AllowOverride None
    Require all granted
</Directory>

To enable the proxy.cgi file to be recognized as executable you need to uncomment the appropriate AddHandler section (within the <IfModule mime_module> section), like:
<IfModule mime_module>
    ...
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    # Enabling the below to allow python processing
    AddHandler cgi-script .cgi .py
    ...
</IfModule>

You need to restart Apache for the configuration changes to be enabled.
You can test that the proxy.cgi is working by browsing to it like (below), without any parameters.
http://localhost/cgi-bin/proxy.cgi

The page should redirect you to the OpenLayers home page, or whatever url you have set in the proxy.cgi section:
else:
    fs = cgi.FieldStorage()
    url = fs.getvalue('url', "http://www.openlayers.org")

For a working example of a Web page with OpenLayers using a proxy.cgi script see:
GeoRSS Example


text:
Q: Limit of 2 variable function I'm trying to determine the limit of this function:
$$\lim_{(x,y)\to (1,2)} \frac{xy^2-4xy-y^2+4x+4y-4}{x^2+y^2-2x-4y+5}$$
I tried to approach in many different ways, such as
$$\lim_{t\to 1} f(t,2t) \quad, \quad\lim_{t\to 1} f(t,2) \quad, \quad \lim_{t\to 2} f(1,t) $$
But i got that the limit is 0 for all of them, tried with polar coordinates but it seems hopeless to get the limit!
How should I think there? Thanks in advance!

A: Let $f(x,y)=xy^2-4xy-y^2+4x+4y-4$ and $g(x,y)=x^2+y^2-2x-4y+5$. Then, for each $(x,y)\in\Bbb R^2$,\begin{align}f(x,y)&=f\bigl((x-1)+1,(y-2)+2\bigr)\\&=(x-1)(y-2)^2\end{align}and\begin{align}g(x,y)&=g\bigl((x-1)+1,(y-2)+2\bigr)\\&=(x-1)^2+(y-2)^2.\end{align}Therefore\begin{align}\lim_{(x,y)\to(1,2)}\frac{xy^2-4xy-y^2+4x+4y-4}{x^2+y^2-2x-4y+5}&=\lim_{(x,y)\to(1,2)}\frac{f(x,y)}{g(x,y)}\\&=\lim_{(x,y)\to(1,2)}\frac{(x-1)(y-2)^2}{(x-1)^2+(y-2)^2}\\&=\lim_{(x,y)\to(1,2)}(x-1)\overbrace{\frac{(y-2)^2}{(x-1)^2+(y-2)^2}}^{\phantom{[0,1]}\in[0,1]}\\&=0.\end{align}


text:
Q: How to avoid running code on head node of the cluster I am using a cluster to run my code. I use a runm file to run my code on the cluster. runm script is as below:
#!/bin/sh
#SBATCH --job-name="....."
#SBATCH -n 4
#SBATCH --output=bachoutput
#SBATCH --nodes=1-1
#SBATCH -p all
#SBATCH --time=1-01:00:00
matlab <znoDisplay.m>o1

today, when my code was running I received an email from cluster boss which says please don't run your code on the head node and use other nodes. I did a lot of searches but I couldn't find that how can I have changed the node from the main node to other nodes. Could anyone help me? Is there any script which could be used in runm to change it?
Could anyone help me to avoid running my code on head node?

A: If the Matlab process was running on the head node, it means you did not submit your script but you most probably simply ran it.
Make sure to submit it with
sbatch runm

Then you can see it waiting in the queue (or running) with
squeue -u $USER

and check that it is not running on the frontend with
top

Also note @atru's comment about the Matlab options -nodisplay and -nosplash for Matlab to work properly in batch mode.


text:
Q: Item level permission not working for list with unique permission I have a list with unique permissions. As a new item is created, with a flow, I delete all permissions (stop sharing) and assign new ones to some group using http call with roles assignment.
I realized I the edit permissions I am giving - despite correctly displayed - are not working. Even providing owner permissions works!
In this case LHDBOT01 has owner permissions (provided with the flow)

But when LHDBOT01 tries to modify this item...

He's getting this error message

Of course, I don't want to give this user edit access on list level...
Some suggestions?

A: Finally I realized waht's the problem: I set up in the list settings/advanced settings/item level permissions "Create items and edit item that were..." rather than "Create and edit all items":

Once changed, all works as expected!


text:
Q: 54M InnoDB keeps shutting down unexpectedly I have a mariadb server running several databases with very small load. From time to time, when I have 20+ users browsing one of the wordpress websites i have, the daemon just shuts down with the following log:
150203 12:33:07 mysqld_safe Number of processes running now: 0
150203 12:33:07 mysqld_safe mysqld restarted
150203 12:33:08 InnoDB: The InnoDB memory heap is disabled
150203 12:33:08 InnoDB: Mutexes and rw_locks use GCC atomic builtins
150203 12:33:08 InnoDB: Compressed tables use zlib 1.2.7
150203 12:33:08 InnoDB: Using Linux native AIO
150203 12:33:08 InnoDB: Initializing buffer pool, size = 512.0M
InnoDB: mmap(551026688 bytes) failed; errno 12
150203 12:33:08 InnoDB: Completed initialization of buffer pool
150203 12:33:08 InnoDB: Fatal error: cannot allocate memory for the buffer pool
150203 12:33:08 [ERROR] Plugin 'InnoDB' init function returned error.
150203 12:33:08 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
150203 12:33:08 [Note] Plugin 'FEEDBACK' is disabled.
150203 12:33:08 [ERROR] Unknown/unsupported storage engine: InnoDB
150203 12:33:08 [ERROR] Aborting

150203 12:33:08 [Note] /usr/libexec/mysqld: Shutdown complete

150203 12:33:08 mysqld_safe mysqld from pid file /var/run/mariadb/mariadb.pid ended
150203 12:37:45 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
150203 12:37:45 InnoDB: The InnoDB memory heap is disabled
150203 12:37:45 InnoDB: Mutexes and rw_locks use GCC atomic builtins
150203 12:37:45 InnoDB: Compressed tables use zlib 1.2.7
150203 12:37:45 InnoDB: Using Linux native AIO
150203 12:37:45 InnoDB: Initializing buffer pool, size = 512.0M
150203 12:37:45 InnoDB: Completed initialization of buffer pool
150203 12:37:45 InnoDB: highest supported file format is Barracuda.
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!
150203 12:37:45  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
150203 12:37:45  InnoDB: Waiting for the background threads to start
150203 12:37:46 Percona XtraDB (http://www.percona.com) 5.5.37-MariaDB-34.0 started; log sequence number 4997214447
150203 12:37:46 [Note] Plugin 'FEEDBACK' is disabled.
150203 12:37:46 [Note] Server socket created on IP: '0.0.0.0'.
150203 12:37:46 [Note] Event Scheduler: Loaded 0 events
150203 12:37:46 [Note] /usr/libexec/mysqld: ready for connections.
Version: '5.5.37-MariaDB'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MariaDB Server

The problem is my database size is very small (54MB) and im setting the pool size to 512MB which is more than enough, i have no idea why im getting cannot allocate memory for the buffer pool, this is the mysqltuner output as well
-------- General Statistics --------------------------------------------------
[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.5.37-MariaDB
[OK] Operating on 64-bit architecture

-------- Storage Engine Statistics -------------------------------------------
[--] Status: +Archive -BDB +Federated +InnoDB -ISAM -NDBCluster
[--] Data in MyISAM tables: 8M (Tables: 200)
[--] Data in InnoDB tables: 54M (Tables: 1100)
[--] Data in PERFORMANCE_SCHEMA tables: 0B (Tables: 17)
[--] Data in MEMORY tables: 0B (Tables: 50)
[!!] Total fragmented tables: 1106

-------- Security Recommendations  -------------------------------------------
[OK] All database users have passwords assigned

-------- Performance Metrics -------------------------------------------------
[--] Up for: 12s (664 q [55.333 qps], 16 conn, TX: 1M, RX: 254K)
[--] Reads / Writes: 91% / 9%
[--] Total buffers: 680.0M global + 2.8M per thread (151 max threads)
[OK] Maximum possible memory usage: 1.1G (59% of installed RAM)
[OK] Slow queries: 0% (0/664)
[OK] Highest usage of available connections: 2% (4/151)
[OK] Key buffer size / total MyISAM indexes: 128.0M/1.8M
[!!] Query cache efficiency: 12.7% (85 cached / 667 selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 26 sorts)
[!!] Temporary tables created on disk: 38% (10 on disk / 26 total)
[!!] Thread cache is disabled
[OK] Table cache hit rate: 300% (39 open / 13 opened)
[OK] Open file limit used: 2% (21/1K)
[OK] Table locks acquired immediately: 100% (590 immediate / 590 locks)
[!!] Connections aborted: 12%
[OK] InnoDB data size / buffer pool: 54.6M/512.0M

-------- Recommendations -----------------------------------------------------
General recommendations:
    Run OPTIMIZE TABLE to defragment tables for better performance
    MySQL started within last 24 hours - recommendations may be inaccurate
    Enable the slow query log to troubleshoot bad queries
    When making adjustments, make tmp_table_size/max_heap_table_size equal
    Reduce your SELECT DISTINCT queries without LIMIT clauses
    Set thread_cache_size to 4 as a starting value
    Your applications are not closing MySQL connections properly
Variables to adjust:
    query_cache_limit (> 2M, or use smaller result sets)
    tmp_table_size (> 16M)
    max_heap_table_size (> 16M)
    thread_cache_size (start at 4)


text:
Q: How to print out Apify requestQueue.getInfo() at run time? The docs on requestQueue.getInfo().
Code
function printRequestQueue(requestQueue){
    let { totalRequestCount, handledRequestCount, pendingRequestCount } =
    requestQueue.getInfo()
        .then(()=> {
            console.log('\nRequest Queue:\n   total:', this);
            console.log('\nRequest Queue:\n   total:', totalRequestCount);
            console.log('   handled:', handledRequestCount, '\n   pending:', pendingRequestCount);
          })
        .catch( (error) => console.log(error));
}

When run in the runtime environment Apify.main(async () => { ... }, it returns undefined:
Request Queue:
   total: undefined
   handled: undefined
   pending: undefined

A: You don't seem to be returning the contents of the response back from the operation promise and so the variables are indeed uninitialized at the time of logging them. Operation itself should be returning this result and you can confirm so by logging the result of the promise - e.g. .then(response) => {console.log(response)}:
https://sdk.apify.com/docs/typedefs/request-queue-info

A: Thanks to Vasek. I post below 2 solutions:
Solution 1
async function printRequestQueue (requestQueue){
  var { totalRequestCount, handledRequestCount, pendingRequestCount } = await
  requestQueue.getInfo();
  console.log(`Request Queue info:` );
  console.log(' - handled :', handledRequestCount);
  console.log(' - pending :', pendingRequestCount);
  console.log(' - total:'  , totalRequestCount);
}

Solution 2
function printRequestQueue (requestQueue){
  requestQueue.getInfo().then((response)=> {
    console.log('total:', response.totalRequestCount);
    console.log('handled:', response.handledRequestCount, '\n   pending:',
     response.pendingRequestCount);
    console.log('\nFull response:\n', response); })
 .catch( (error) => console.log(error));
}

One may read full explanation in here.


text:
Q: Why does Proguard remove method's "bridge" modifier? I've noticed that Proguard removes method's bridge modifier even if the class excluded from obfuscation with a -keep property. How can I avoid this behaviour? It breaks integration with third-party libraries.
So I have a Scala function object that has method apply. Before obfuscation:
scala> classOf[TestFunction].getMethods.filter(m => m.getName == "apply" && !m.isBridge)
res0: Array[java.lang.reflect.Method] = Array(public final double TestFunction.apply(java.lang.Object))

After obfuscation:
scala> classOf[TestFunction].getMethods.filter(m => m.getName == "apply" && !m.isBridge)
res0: Array[java.lang.reflect.Method] = Array(public final double TestFunction.apply(java.lang.Object), public final java.lang.Object TestFunction.apply(java.lang.Object))

I need those 2 cases be similar.
Proguard version is 5.3
UPD I also keeping the following attributes:
-keepattributes Signature,*Annotation*
-keepattributes InnerClasses,EnclosingMethod
-keepattributes SourceFile,MethodParameters,Synthetic,Code,LineNumberTable


text:
Q: Android http connection - multiple devices cannot connect the same server I really need help here...
I have a simple Android application that connects to my sever to fetch data over HTTPS.
Everything is working fine up until i connected to the same server from another device (iOS or Android). I am starting to get timeouts or connection refused or other errors depending on the library that I use (sometimes SSL handshake)

*

*I tried 2 android app on the same router - fails

*I tried Volley, Retrofit, plain http library - fails

*if one device is connected via cellular network and one on wifi, it is working fine. However, i have seen cases that it fails even using 2 devices connected to cellular network and not wifi.

*It is easy to reproduce. one app is working fine. as soon as i do an operation on the other device. the first app will not be able to connect.

*iOS app using the same api/server is working fine. no failures

*I ran wireshark on the android app during failure and received the following:
70  47.073286   10.0.0.1    10.0.0.138  ICMP    120 Destination unreachable (Port unreachable)
Seems like port issues. I am not sure anymore if this is a server issue or a client issue.. iOS app works fine. no issues. Only Android.
I tried:
System.setProperty("http.keepAlive", "false");

I tried setting an http header "connection :close" nothing works...
Any idea would be appreciated...

A: Same problem here . When my ios device connect to allstar heroes or fun run application the android device cant connect anymore . I cant find s fix for that . My router is tp link dir 615 . Maybe the problem is frpm router .

A: At the end of the day, it was server side issue. the IT guy gave me the following info: "incorrect flag on the tcp kernel settings" "Reuse connection" that is all I have for you. hope it can help someone else

A: I had the same problem. The issue seemed to be when the app tried to access ports in TIME_CLOSE here is a great explanation how this happen, changing the tcp kernel to Reuse connection, might solve the problem since the server will try to re-use those connection in TIME_CLOSE again.  but it must be a solution from the client side to avoid the connection to get stuck. in my case I was trying to create connection from multiples activities and i guess they, somehow, competed for opening and closing the connections, i solved the issue using a single activity to make the connection to the server.
hope this is useful to someone.

A: Had exact the same issue and spent a lot of time investigating, nothing helped including "Reuse connection" flag, tried also to disable tcp_timestamp, tcp_tw_reuse, tcp_tw_recycle and enable vm safe mode for the app as suggested here:

*

*https://github.com/square/okhttp/issues/903

*https://github.com/square/okhttp/issues/1037

*https://github.com/square/okhttp/issues/1518
but all in vein.
Further more, the very strange thing was that I had two different instances/servers which I made exactly the same in order to track down the issue and one server didn't have any issues.
So in the end:

Instance reboot solved problem with connections.
  (or just need to restart networking service)

(c) My server/instance admin


text:
Q: arraylist not updating outside the onNext method ArrayList updated in onNext but outside it ArrayList is not updated.
    mListItems.clear(); //size = 0

    compositeDisposable.add(Observable.create(handler)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(category -> {
                mListItems.add(category); //size = 3
                notifyDataSetChanged();
            })
            .subscribe());

    mListItems.forEach(this::expandAllParent); //size = 0

A: This is because that block of RxJava code runs asynchronously because you are subscribing to it on IO thread which means a thread other than android's main thread, so it is not guarantied that code inside doOnNext gets executed before code after your RxJava chain. I mean the execution order is like this:
mListItems.clear(); // -> first this line gets executed

// Here and observable gets created and passed to another thread to get execute by that thread
compositeDisposable.add(Observable.create(handler)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .doOnNext(category -> {
        mListItems.add(category);
        notifyDataSetChanged(); // and at last this block of code gets executed
    })
    subscribe());

mListItems.forEach(this::expandAllParent); // -> secondly this line gets executed

if you want to execute expandAllParent correctly for all added items then its better to move that line of code inside doOnNext method, like this:
    mListItems.clear();
compositeDisposable.add(Observable.create(handler)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .doOnNext(category -> {
        mListItems.add(category);
        notifyDataSetChanged();
        mListItems.forEach(this::expandAllParent); // -> move this here
    })
    subscribe());


text:
Q: How to handle HDInsight Hbase Major compactions? Hbase is not reachable when the major compaction take place We have HDInsight Hbase cluster installed and we observe that while there is major compactions going on, the Hbase becomes not reachable to the client applications.
Please suggest what is the best practices to handle this scenario.

A: Regarding HDInsight HBase, I would like to share some ideas here.
1) Time based compaction is disabled by deafult, see hbase.hregion.majorcompaction=0
2) Regarding size based compaction, the default compaction policy is ExploringCompactionPolicy while hbase.hstore.compaction.max.size is set to 10GB, so no compactions will happen larger than 10GB.
hbase.hregion.max.filesize is set to 3GB, thus once a region's HFiles have grown to execeed this value, the region will get split.
   The reason for such settings is that the max blob HBase could create in Azure Storage is up to 12GB, thus if compacting more than 12GB data, compaction will finally fail. You can definately increase the max blob size (up to 200GB per Azure Storage documented, but that will increase read/write latency and compaction time as well).
More context here,
Although Azure blob storage has 200GB limit for a single blob, (4MB*50k blocks), but in order to get best performance, in hadoop core-site.xml we limit fs.azure.read.request.size and fs.azure.write.request.size to 256kb, thus the max blob in HBase cluster will be 256KB*50k around 12GB. if you set to 4MB, it will be 200GB though. But 4MB will increase latency of each read/write, and you will allow HBase to compact up to 200GB data which will last for hours.
3) Major compaction is costly especially for cloud based HBase. Because the latency is higher than local disk/SSD. For read performance, you can set up bucket cache mounted on local VM SSD, which should have been turned on by default on the latest HDInsight HBase cluster.
There are definitely more tuning can be done like VM size, cluster size, Memstore size, etc.

A: It depends of your use case.
By default, major compaction are lunched each 24 hours.
If you know when your cluster is not used you can disable major compaction and run at that time (typically the night). A script called by cron that launch major compaction with hbase shell can do the job.
Since HBase 0.98.11 and HBase 1.1.0 you can limit compaction throughput, more information on Limit compaction speed JIRA.
It is important to launch major compaction because it improves HBase disk access by merging StoreFile (removing deleted data on disk, sort data by rowkey, ...)
hbase-site.xml  :
<!-- Disable major compaction -->
<property>
  <name>hbase.hregion.majorcompaction</name>
  <value>0</value>
</property>

Run major compaction manually :
# Launch major compaction on all regions of table t1
$ echo "major_compact 't1'" | hbase shell
# Launch major compaction on region r1
$ major_compact 'r1'


text:
Q: How to execute SonarQube Runner from Bamboo? I have setup SonarQube in Azure Virtual Machine.
sonarqube-5.4
MSBuild.SonarQube.Runner-2.0
SonarQube website at 9000 port is up and running.
(http://something.regionname.cloudapp.azure.com:9000/)
Now, how to execute sonarrunner from a local bamboo build server ?
What are the configuration settings and other changes ?
Earlier, I did setup sonarqube with bamboo locally successfully, because all are local paths.
But now, I want to install sonarqube and bamboo on different servers. How to connect these two ?
Please provide comments / settings in detail.
Thanks
Bhanu.

A: There's a Bamboo plugin for that: https://marketplace.atlassian.com/plugins/com.marvelution.bamboo.plugins.sonar.tasks/server/overview
I haven't used it, and I don't know whether it supports SonarQube Scanner for MSBuild (I'm skeptical on that count.)
Perhaps your best bet is to treat Bamboo like a fancy CLI, and use follow the instructions for analyzing from the command line. I.E.

*

*install an configure SonarQube Scanner for MSBuild on the Bamboo server

*via Bamboo run commands:

*

*MSBuild.SonarQube.Runner.exe begin /k:"sonarqube_project_key" /n:"sonarqube_project_name" /v:"sonarqube_project_version"

*build the project

*MSBuild.SonarQube.Runner.exe end

A: Mibex Software's excellent free Sonar for Bamboo has evolved to be the canonical (and supported) SonarQube integration for Bamboo - it provides a Bamboo tasks to analyze projects with Sonar for Maven, Gradle & SonarRunner and also supports auto-branching for Sonar-based code reviews-

A: The bamboo server has Sonar Runner task that can be used to execute the code.
You need to have sonar-project.properties file in your root folder.
The settings that need to be done are:
sonar.projectKey=<projectkey>
sonar.projectName=<projectname>
sonar.projectVersion=1.0.0
sonar.sourceEncoding=UTF-8
# Enable the Visual Studio bootstrapper
sonar.visualstudio.enable=true
# Code Coverage
#placeholder-for-modular-coverage-reporting
# Unit Test Results
#placeholder-for-modular-unit-test-reporting
# Required only when using SonarQube < 4.2
sonar.language=cs
# FXCop
# This property is set because it is required by the SonarQube Runner.
# But it is not taken into account because the location of the source
# code is retrieved from the .sln and .csproj files.
sonar.sources=.
# If you have multiple solution files then use the current one by setting up the below property
sonar.visualstudio.outputPaths=
# Test projects can be imported as unit test code (which is not analyzed by coding rules) using the regular expression property
#sonar.visualstudio.testProjectPattern=
#sonar.visualstudio.solution=YourSolution.sln
sonar.visualstudio.skipIfNotBuilt=true

This Msbuild Sonar may be helpful for you.


text:
Q: TypeORM: Sort String field as Number I have a GraphQL REST service returning a number field as a String. Is it possible to convince .addOrderBy to sort a string field as a number?
I can't modify the schema.


text:
Q: Camera capture activity MediaStore.ACTION_IMAGE_CAPTURE doesn't write to Uri This is weird. The following code was working a few weeks ago, and now it is not:
private void onClick()
{
   Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
   mOriginalUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"original" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
   Log.d("path", mOriginalUri.getPath());
   intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mOriginalUri);
   intent.putExtra("return-data", true);
   startActivityForResult(intent, CAMERA_REQUEST);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
   switch( requestCode )
   {
   case CAMERA_REQUEST:
       if(resultCode == MainActivity.RESULT_OK)
          Log.d("path", mOriginalUri.getPath());
       break;
   }
}

Somehow the camera capture activity is losing track of my Uri and setting it to null. I get a NPE when printing the path in the onActivityResult. How can I resolve this? I'm using Android 4.1.2 API 16 on a Galaxy Nexus.

A: I had a similar issue of the camera sometimes returning the image and sometimes returning null. I had the same setup of writing the image to a file.
I kicked off the camera intent from onCreate(), not an onClick() method.
When I locked the screen orientation of the intent (to portrait, but that does not matter), the problem went away. May want to try that and report back if that made a difference.
This may also be relevant:
Camera activity causing uri to go to null when screen orientation changes


text:
Q: Calculate PI using Random Numbers Having trouble with the following question:
In geometry the ratio of the circumference of a circle to its diameter is known as π. The value of π can be estimated from an infinite series of the form:
π / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
There is another novel approach to calculate π. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just π square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is π / 4.
To simuluate the throwing of darts we will use a random number generator. The Random module has several random number generating functions that can be used. For example, the function uniform(a, b) returns a floating point random number in the range a (inclusive) and b (exclusive).
Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.
A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. The way we achieve that is:
xPos = random.uniform (-1.0, 1.0)
yPos = random.uniform (-1.0, 1.0)

To determine if a point is inside the circle its distance from the center of the circle must be strictly less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is math.hypot (xPos, yPos). The radius of the circle is 1 unit.
The program that you will be writing will be called CalculatePI. It will have the following structure:
import math
import random

def computePI ( numThrows ):
  ...

def main ():
  ...

main()

Your function main() will call the function computePI() for a given number of throws. The function computePI() will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will determine if that randomly generated point is inside the circle or not. You will do this as many times as specified by the number of throws. You will keep a count of the number of times a dart lands within the circle. That count divided by the total number of throws is the ratio π/4. The function computePI() will then return the computed value of PI.
In your function main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by math.pi. The quantity Difference in the output is your calculated value of PI minus math.pi. Use the following number of throws to run your experiment - 100, 1000, 10,000, 100,000, 1,000,000, and 10,000,000. You will call the function computePI() with these numbers as input parameters. Your output will be similar to the following, i.e. the actual values of your Calculated PI and Difference will be different but close to the ones shown:
Computation of PI using Random Numbers

num = 100        Calculated PI = 3.320000   Difference = +0.178407
num = 1000       Calculated PI = 3.080000   Difference = -0.061593
num = 10000      Calculated PI = 3.120400   Difference = -0.021193
num = 100000     Calculated PI = 3.144720   Difference = +0.003127
num = 1000000    Calculated PI = 3.142588   Difference = +0.000995
num = 10000000   Calculated PI = 3.141796   Difference = +0.000204

Difference = Calculated PI - math.pi

Your output must be in the above format. The number of throws must be left justified. The calculated value of π and the difference must be expressed correct to six places of decimal. There should be plus or minus sign on the difference. Read the relevant sections in the book on formatting.
Till now I have done:
import math
import random

def computePI (numThrows):

  xPos = random.uniform (-1.0, 1.0)
  yPos = random.uniform (-1.0, 1.0)

  in_circle = 0
  throws = 0

  while (throws < numThrows):
    if math.hypot (xPos, yPos) <= 1:
      in_circle += 1
    throws += 1
  pi = (4 * in_circle) / numThrows
  return pi

def main ():

  throws = (100, 1000, 10000, 100000, 1000000, 10000000)
  for numThrows in throws[0:7]:

main ()

I am having trouble calling the ComputePI function in the Main function. Also how do I print num with left indentation and ensure that all numbers have the required decimal space? Thank you!

A: Your program has three main issues:

*

*Generating random numbers in the wrong place
xPos = random.uniform (-1.0, 1.0)
yPos = random.uniform (-1.0, 1.0)

These lines are executed only once when you enter the computePI() function. You then proceed to calculate the exact same value of hypot for hundreds or even thousands of iterations. Put these lines inside the while loop.

*Integer arithmetic
pi = (4 * in_circle) / numThrows

Since in_circle and numThrows are both integers, this calculation will be performed using integer arithmetic (in Python 2, at least). Changing the constant from 4 to 4.0 will change this to a floating point calculation:
pi = (4.0 * in_circle) / numThrows

*Incomplete main() function:
There's no need to use a subset of your throws tuple, and you haven't added a body to your for loop. Try this:
for numThrows in (100, 1000, 10000, 100000, 1000000, 10000000):
    randpi = computePI(numThrows)
    diff = randpi - math.pi
    print "num = %-8d   Calculated PI = %8.6f   Difference = %+9.6f" % \
          (numThrows, randpi, diff)

A: This is how I find it easy.
import random
import math
def approximate_pi():
    total_points = 0
    within_circle = 0
    for i in range (10000):
        x = random.random()
        y = random.random()
        total_points += 1
        distance = math.sqrt(x**2+y**2)
        if distance < 1:
            within_circle += 1
        if total_points % 1000 == 0:
            pi_estimate = 4 * within_circle / total_points
            yield pi_estimate

set total point generated and points withing the circle to zero
total_points = 0
within_circle = 0

generate the random values of x and y for multiple times. Calculate the distance of the point from the center of the circle or (0,0). Then if the distance is less than one it means that it's within the circle so it is incremented.
distance = math.sqrt(x**2+y**2)
        if distance < 1:
            within_circle += 1

Now if you have generated let's say multiple of 1000(1000 because we have taken the range for 10,000 so 1000 to get 10 values of pi), calculate the estimated value of pi using this formula which you know already.and the tied the estimate value(pi_estmate)
if total_points % 1000 == 0:
            pi_estimate = 4 * within_circle / total_points
            yield pi_estimate

pi_estimates = list(es for es in approximate_pi())
errors = list(estimate-math.pi for estimate in approximate_pi())
print(pi_estimates)
print(errors)

OUTPUT:
Estimates
[3.096, 3.142, 3.1253333333333333, 3.121, 3.1384, 3.136, 3.1314285714285712, 3.133, 3.1342222222222222]

Errors
[0.04240734641020705, 0.02240734641020703, 0.03307401307687341, 0.020407346410206806, 0.02320734641020694, 0.0017406797435404187, -0.009021225018364554, -0.011592653589793223, -0.016703764700904067]

Hope you understood, I hope my explanation was easy to understand, I am a beginner and learning stuff if there is anything wrong please feel free to notify.
Thank you

A: Essentially what the statement you've written above says:

import math

def find_pi(iterations):
  return sum(
    1 for _ in range(iterations) if math.hypot(
                          random.random(), random.random()) <= 1) * 4.0/iterations


text:
Q: print the string in between 2 conditions of text file in Python I am new to python.I am struggling to print the string in between conditions of text file.My text file contains information below
03:37:59 CONFIRM 03.37.59 IS-0008 SS-XYZ  SSU-BSS  AB-008966 CTL-I001234
03:37:59 123HTSA TVP5
08:12:19 SNAP 290D 08.12.20 CX-A TU-BSS ZRE-BSS IS-3
08:12:19 PSW-07151000 813264 00000000 2967561E
08:12:19 PGM-BA13 CODE-U00BA1302 TERM-000000A

/*After this a few lines of data display*/

08:12:19 GOOD BYE TAKE CARE

Third Line has "SNAP" and "IS-"
 Line 5 has "PGM-XXXX" where XXXX = program name and "CODE-XXXXXXXXX" XXXXXXXXX = type of Snap dump as coded.
        This will be followed by a few lines of data display. The number of lines is variable and can change.
        The last line will be "GOOD BYE TAKE CARE"
My output should be
08:12:19 SNAP 290D 08.12.20 CX-A TU-BSS ZRE-BSS IS-3
08:12:19 PSW-07151000 813264 00000000 2967561E
08:12:19 PGM-BA13 CODE-U00BA1302 TERM-000000A

/*After this a few lines of data display*/

08:12:19 GOOD BYE TAKE CARE

I have tried but i want to print upto 08:12:19 GOOD BYE TAKE CARE
with open("TEXT.txt", "r") as file:
output = ""
for line in file.readlines():
    if "CTL" in line:
        output += line
        print(output)

A: If I understand you correctly that you just need to print lines staring with the line containing SNAP and IS-, then how about this?
import re
with open("TEXT.txt", "r") as file:
    output = ""
    ok = False
    for line in file:
        if re.search('SNAP.*IS-', line):
            ok = True
        if ok:
            output += line
    print(output)

A: printing = False
with open('text.txt') as file:
    for line in file.readlines():
        if line[9:13] == 'SNAP':
            printing = True
        if printing:
            print (line.strip())
        if line == '08:12:19 GOOD BYE TAKE CARE':
            break

Initially the Boolean variable printing is set to False so that printing is disabled. Lines are read in a loop. When a line is read with 'SNAP' in the special location printing is set toTrue` to enable printing. In this condition lines are printed as soon as they are read. When a line is read containind 'GOOD BYE [etc]' the loop is broken and the script comes to an end.
EDIT: If you want to end printing prior to 'GOOD BYE [etc]' then the script could be the following.
printing = False
with open('text.txt') as file:
    for line in file.readlines():
        if line[9:13] == 'SNAP':
            printing = True
        if line.strip() == '08:12:19 GOOD BYE TAKE CARE':
            break
        if printing:
            print (line.strip())

Notice especially that line must be stripped of end-of-line characters to test for equality.


text:
Q: ERROR: column reference "customer" is ambiguous GOAL
Estou realizando um contador na coluna nome do host para todo cliente igual ao BRASILFOODS, única coisa que eu queria, era que ao lado da contagem aparecesse o nome BRASILFOODS
QUERY
SELECT COUNT(*) hostname, customer
FROM tb_get_gap
LEFT JOIN tb_get_customers
ON tb_get_gap.customer = tb_get_customers.cust_cmdb WHERE tb_get_customers.customer = 'BRASILFOODS' and tb_get_gap.exception = 'NO';

OUTPUT
>[Error] Script lines: 1-4 --------------------------
 ERROR: column reference "customer" is ambiguous
 Line: 1

A: Existe uma coluna chamada customernas duas tabelas envolvidas: tb_get_gap e tb_get_customers, então ele não sabe qual das duas deve pegar, você deve dar o nome completamente qualificado da coluna, por exemplo tb_get_gap.customer, da mesma forma que usou no WHERE.
Parece existir um outro problema porque não está agrupando os dados.


text:
Q: How to open user profile Linkedin with app in android I'm trying to open Linkedin profile with an app in Android, with a URL or member id.
I try this:
Intent linkedinIntent = new Intent(Intent.ACTION_VIEW);
linkedinIntent.setClassName("com.linkedin.android", "com.linkedin.android.profile.ViewProfileActivity");
linkedinIntent.putExtra("memberId", <member id>);
startActivity(linkedinIntent);

but this code just opens the Linkedin app.
How can I open the specific profile?

A: try {
          getPackageManager().getPackageInfo("com.linkedin.android", 0);
          intent = new Intent(Intent.ACTION_VIEW, Uri.parse("linkedin://profile/yourID"));
    }catch (Exception e) {
            showerror(); // handle exception
    }finally {
        startActivity(intent);
}

A: Just navigating to the link as a website is letting the user to choose between LinkedIn app and web browsers. With:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
context.startActivity(intent);

Tested on Android API 28

A: According to posts on the LinkedIn Developer forums, this functionality is not exposed by their API.
Sources:

*

*http://developer.linkedin.com/forum/android-intent

*http://developer.linkedin.com/forum/mobile-user-profile-url
However, there is an undocumented method which seems to work. Naturally, it may have an oversight on their part to have left it open for use and making of use this naturally comes with the warning since it is undocumented, it may or may not change. If it does change, it may break the functionality of your app
With that said, the suggestion from one of LinkedIn's employee here: https://developer.linkedin.com/comment/3614#comment-3614 has disclosed the above undocumented feature.
http://www.linkedin.com/x/profile/{consumer-key}/{member-token}

Good luck and hopefully, LinkedIn will make such a feature (simple and somehow, still ignored) available via their API.


text:
Q: Can MySQL constrain based on a NULL value combined with an id? I use django-mptt to make a tree structure on a model in a web app.
Unfortunately - once in a while I will get duplicate root nodes in a tree.
These will have NULL as parent_id, and the same tree_id, like this:
+--------+-----------+---------+
| id     | parent_id | tree_id |
+--------+-----------+---------+
| 159092 |      NULL |   52098 |
| 159093 |      NULL |   52098 |
+--------+-----------+---------+

Is there any way to stop this at the database level?
Can I make a constraint in MySQL to avoid getting two or more items with NULL as parent_id and the same tree_id?
Model from models.py with irrelevant fields removed:
class Message(MPTTModel):
    # Threaded messages
    text = textmodels.TextField()

A: The simple answer is no, but you could create insert and update triggers that will block the new value.  If you are using MySQL >= 5.5 you can use something like this -
DELIMITER |

DROP TRIGGER IF EXISTS before_msg_insert|

CREATE TRIGGER before_msg_insert BEFORE INSERT ON message
FOR EACH ROW
BEGIN
    DECLARE xid INT DEFAULT 0;
    IF (NEW.parent_id IS NULL) THEN

        SET xid = (SELECT id FROM message WHERE tree_id = NEW.tree_id AND parent_id IS NULL);

        IF (xid > 0) THEN
            SET @msg = CONCAT("Root node already exists. ID: ", xid);
            SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = @msg;
        END IF;

    END IF;
END|

DROP TRIGGER IF EXISTS before_msg_update|

CREATE TRIGGER before_msg_update BEFORE UPDATE ON message
FOR EACH ROW
BEGIN
    DECLARE xid INT DEFAULT 0;
    IF (NEW.parent_id IS NULL) THEN

        SET xid = (SELECT id FROM message WHERE tree_id = NEW.tree_id AND id <> NEW.id AND parent_id IS NULL);

        IF (xid > 0) THEN
            SET @msg = CONCAT("Root node already exists. ID: ", xid);
            SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = @msg;
        END IF;

    END IF;
END|

DELIMITER ;


text:
Q: how to fetch the data in the foreign key using Entity framework core I am trying to get the categoryName on HttpGet through my foreignKey which is categoryid, here is a picture of my swagger to see what I am trying to achieve:

It should display the categoryName of the Id.
here is my model:
public class ItemTables
{
    [Key]
    public int Id { get; set; }

    public string company { get; set; }

    public string availability { get; set; }

    public decimal price { get; set; }

    public decimal discount { get; set; }

    public decimal tax { get; set; }

    public string description { get; set; }

    public int categoryid { get; set; }

    public categories categories { get; set; }

}

public class categories
{
    [Key]
    public int categoryID { get; set; }

    public string categoryName { get; set; }

    public ICollection<ItemTables> items { get; set; }
}

my context:
public class itemTableDbContext : DbContext
{
    public itemTableDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<ItemTables> ItemTables { get; set; }

    public DbSet<categories> categories { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<ItemTables>()
            .HasOne<categories>(c => c.categories)
            .WithMany(i => i.items)
            .HasForeignKey(f => f.categoryid);

        //modelBuilder.Entity<itemTable>().ToTable("itemtable");

        //modelBuilder.Entity<categories>().ToTable("categories");
    }
}

and here is my itemtableController which it has the [HttpGet]:
public class ItemTableController : ControllerBase
{
    private readonly itemTableDbContext _itemTableDbContext;

    public ItemTableController(itemTableDbContext itemTableDbContext)
    {
        _itemTableDbContext = itemTableDbContext;
    }

    [HttpGet]
    public async Task<IActionResult> GetItemsTable()
    {
        var ItemTable = await _itemTableDbContext.ItemTables.ToListAsync();

        return Ok(ItemTable);
    }

    [HttpPost]
    public async Task<IActionResult> AddItemTable([FromBody] ItemTables itemTableRequest)
    {
        await _itemTableDbContext.ItemTables.AddAsync(itemTableRequest);
        await _itemTableDbContext.SaveChangesAsync();

        return Ok(itemTableRequest);
    }
}

I hope you got what I am trying to achieve, thank you in advance, if you need more information tell me so :)

A: You have to include categories so it will  be retrieved with your items
var ItemTable = await _itemTableDbContext.ItemTables.Include(i=>i.categories).ToListAsync();

you can check this documentation to learn more about the include method https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager
Tips:

*

*Rename the categories class to => Category

*public categories categories { get; set; } => public Category Category {get;set;}


text:
Q: Writing to a topic within a Processor using Kafka Stream DSL I need to use the Kafka Sreams API alongside Processor API. I also want to write different types of Objects to different topics within my processor implementation i.e emit different object on process & punctuate. I have seen there is a KIP-313 flatTransform that would probably solve my problem.
If i use:
inputStream.process(processorSupplier,,)

Since this is a "terminating" operation (its return type is void) could I use an internal Kafka producer within my Processor. I have not seen such an implementation is this a reasonable approach are there any side effects?

A: If you need so low level approach you can build whole topology by your own:
Topology topology = builder.build();
topology.addSource("inputNode","input");
topology.addProcessor("inProcessor", InputProcessor::new, "inputNode");
topology.addSink("sink1",
    (k, v, rc) -> "topic1",
    new StringSerializer(),
    new IntegerSerializer(),
    "inProcessor");
topology.addSink("sink2",
    (k, v, rc) -> "topic2",
    new StringSerializer(),
    new StringSerializer(),
    "inProcessor");

InputProcessor depends on the business logic produce different types of object and pass them to different sink nodes (topics).
Sample example has logic as follow:

*

*if value of message can be parsed to Integer, forward it to two sink nodes (sink1, sink2), to sink1 as Integer to sink2 as String.

*if not forward message only to sink2.

public class InputProcessor extends AbstractProcessor<String, String> {
    @Override
    public void process(String key, String value) {
        try {
            context().forward(key, Integer.parseInt(value), To.child("sink1"));
            context().forward(key, value, To.child("sink2"));
        }
        catch (NumberFormatException nfe) {
            context().forward(key, value, To.child("sink2"));
        }
    }
}


text:
Q: appendchild is not working I am working on nested array. When i am trying to insert data to a div by using appendChild It is throwing an error saying Cannot read property 'appendChild' of null
My Code goes hear

<input type = "button" id = "MyArray"  value ="Show Emps" onclick="showEmployes()"/>

and it is working in this way
function showEmployes(){
        var n = emps.length;

        for (i = 0; i < n ; i++){
            var emp = emps[i];

             for(var key in emp){

                var NewDiv = document.createElement("div");

                NewDiv.innerHTML = key + ": " + emp[key];

                document.getElementById("Employedisplay").appendChild(NewDiv);

             }
             var NewBrk = document.createElement("br")
             Employedisplay.appendChild(NewBrk);
        }
    }

I am not understanding where i am going wrong in my first approach?

A: The below line of code is executed even before the browser add the #Employedisplay element in DOM.
var Employedisplay = document.getElementById("Employedisplay");

So when you click the button, Employedisplay variable is null
It's better to bootstrap your code on page load, or you can get the #Employedisplay element at the start of showEmployee method.

    <input type="button" id="MyArray" value="Show Emps" onclick="showEmployes()" />

A:

<input type = "button" id = "MyArray"  value ="Show Emps" onclick="showEmployes()"/>


text:
Q: Perform GroupJoin and Join in single query in Entity Framework Core I am trying to do a join inside a groupjoin using Linq. Here's the scenario - for each lineitem in an order, I want to get some attributes from the variant for that line item(such as variant options and imageid which are stored in variant and product databases). i want to join lineitem, variant and product databases to get these extra information for the lineitem and then groupjoin this lineitem with the order table. i have done this and got the desired result using two queries but I am not sure how many database queries are run. And in the first case(ie in the join, a limit cannot be specified so I just want to make sure that the first iqueryable in the code below is evaluated only when .ToListAsync() is called). Is this the right way to do it? Any help would be greatly appreciated!
  public async Task<dynamic> GetOrdersAsync(User user, int pageNumber = 1)
        {
            var perPage = 10;
            var lineItemAndVariant = from l in _context.LineItems
                                     join v in _context.Variants
                                     on l.EcomPlatformVariantId equals v.EcomPlatformVariantId
                                     join p in _context.Products
                                     on v.ProductId equals p.Id
                                     where p.UserId == user.Id
                                     select new
                                     {
                                         l.Id,
                                         l.OrderId,
                                         l.Price,
                                         l.Quantity,
                                         l.EcomPlatformLineItemId,
                                         l.EcomPlatformVariantId,
                                         l.Title,
                                         ImageId = v.ImageId ?? p.ThumbnailId, // for adding image
                                         p.MyVendor,
                                         p.MyVendorId,
                                         v.Option1,
                                         v.Option2,
                                         v.Option3,
                                         p.VariantOption1Label,
                                         p.VariantOption2Label,
                                         p.VariantOption3Label
                                     };

            var orders = await _context.Orders
                .Where(o => o.UserId == user.Id)
                .OrderByDescending(o => o.Id)
                .Skip(perPage * (pageNumber - 1)).Take(perPage)
                .GroupJoin(lineItemAndVariant, o => o.Id, l => l.OrderId,
                (o, lineItems) => new
                {
                    o.Id,
                    o.EcomPlatformOrderId,
                    o.CustomerEmail,
                    o.FirstName,
                    o.LastName,
                    o.Address1,
                    o.Address2,
                    o.City,
                    o.Company,
                    o.Country,
                    o.Currency,
                    o.OrderNumber,
                    o.Phone,
                    o.Province,
                    o.TotalPrice,
                    o.UserId,
                    o.Zip,
                    o.CreatedAt,
                    LineItems = lineItems
                })
                .AsNoTracking().ToListAsync();

            return orders;

        }


text:
Q: How to create map variable from string literal in Golang? I have a prepared map structure as a string literal. Notice, it is not a JSON! (look at commas in the last elements of blocks)
dict := `{
    "ru": {
        "test_key": "Тестовый ключ",
        "some_err": "Произошла ошибка",
    },
    "en": {
        "test_key": "Test key",
        "some_err": "Error occurs",
    },
}`

I want to transform this string to real value of map type (map[string]map[string]string). I need it for tests. Is it possible?

A: If this is just for testing, I would remove the "unneeded" commas from the source string and use JSON unmarshaling.
To remove the unneeded commas: I'd use the regexp ,\s*}, and replace it with a single }.
For example:
dict = regexp.MustCompile(`,\s*}`).ReplaceAllLiteralString(dict, "}")

var m map[string]map[string]string
if err := json.Unmarshal([]byte(dict), &m); err != nil {
    panic(err)
}
fmt.Println(m)

Output (try it on the Go Playground):
map[en:map[some_err:Error occurs test_key:Test key] ru:map[some_err:Произошла ошибка test_key:Тестовый ключ]]


text:
Q: method not found exception while invoking method in springboot Feb 17, 2022 10:06:40 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{loginBean.validate}: javax.el.MethodNotFoundException: /index.xhtml @23,80 action="#{loginBean.validate}": Method not found: ritu.login.User@d570e4f.validate()
javax.faces.FacesException: #{loginBean.validate}: javax.el.MethodNotFoundException: /index.xhtml @23,80 action="#{loginBean.validate}": Method not found: ritu.login.User@d570e4f.validate()
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:110)

Here is my login.xhtml file
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:form>

        <h:outputText value="id" />
        <h:inputText id="id" value="#{loginBean.id}"></h:inputText>
        <h:message for="id"></h:message>

        <h:outputText value="name" />
        <h:inputText id="name" value="#{loginBean.name}"></h:inputText>
        <h:message for="name"></h:message>

</h:form>

Here is my class
package ritu.login;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
@ManagedBean(name = "loginBean")
@SessionScoped
public class User implements Serializable{

    private static final long serialVersionUID = -7250065889869767422L;

    @Id
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String validate(Long id, String name) {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/any", "root", "jaygurudev1@");
            PreparedStatement ps = con.prepareStatement("Select id,name from user where id=? and name=?");
            ps.setLong(1, id);
            ps.setString(2, name);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
                return "index.xhtml";
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
                        "Incorrect Username and Passowrd", "Please enter correct username and Password"));
                return "login.xhtml";
            }

        } catch (Exception e) {
            System.out.println("in exception");
        }
        return "ok";

    }
}

why this exception occur and what is this trying to said? i have use h tag in commandButton previosly but it did not work
Caused by: javax.faces.el.MethodNotFoundException: javax.el.MethodNotFoundException: /index.xhtml @23,80 action="#{loginBean.validate}": Method not found: ritu.login.User@d570e4f.validate()
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:91)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 29 more
Caused by: javax.el.MethodNotFoundException: /index.xhtml @23,80 action="#{loginBean.validate}": Method not found: ritu.login.User@d570e4f.validate()
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:109)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 30 more
Feb 17, 2022 10:06:40 AM com.sun.faces.context.ExceptionHandlerImpl log
1100: JSF1073: javax.faces.FacesException caught during processing of INVOKE_APPLICATION 5 : UIComponent-ClientId=, Message=#{loginBean.validate}: javax.el.MethodNotFoundException: /index.xhtml @23,80 action="#{loginBean.validate}": Method not found: ritu.login.User@d570e4f.validate()
Feb 17, 2022 10:06:40 AM com.sun.faces.context.ExceptionHandlerImpl log

A: You have to pass parameter near #{loginBean.validate} in login.xhtml.
Change:

To:


text:
Q: Exception: The Calling thread cannot access this object because a different thread owns it I'm converting a UI from windows forms to WPF. I'm getting the following exception "The Calling thread cannot access this object because a different thread owns it" whenever I try to call anything on this new WPF window I created.
I referred stack overflow and many websites to find out that I should use Dispatcher.CheckAccess() or somethings similar to dispatcher and check access. I tried many such things
This is one of the things that I have used
Private Delegate Sub ShowSkinInvoked()

If (Dispatcher.CheckAccess()) Then
    Me.Show()
Else
    Dim d As ShowSkinInvoked = New ShowSkinInvoked(AddressOf ShowSkin)
    Dispatcher.Invoke(d)
End If

This has removed the exception and while debugging the error is gone but it freezes the application and I cannot do anything other than terminate it. It doesn't even show the window after "Me.Show".
Also, if I compile the program and then make the calling module use this compiled exe by specifying path to exe then for some reason it works perfect.
If this sounds confusing then what I mean is, I have multiple forms. If I call the code in module A to load and display module B then it gives me the exception but if I call the code in module A to run the compiled exe of module B then it runs perfectly.
Any suggestions?

A: When WPF creates a user interface it created a thread that is responsible for handling all the user interaction events and scheduling the rendering.  This is called the dispatcher thread. Many of the objects that it creates are sub classes of DispatcherObject.
You can't call methods on a DispatcherObject from threads other then the Dispatcher thread that created them. The reasons why are complicated but relate to COM interop.
When you are in a Buttons click event you are running on dispatcher thread.
If you are coming from another thread you must get your work to be performed on the dispatcher thread.  It can typically be found by accessing the static current dispatcher Dispatcher.CurrentDispatcher, unless your creating multiple dispatcher threads.
However I would suggest explaining your problem in terms of what work your trying to do with regards to having one form show ui on another.  There are multiple ways like an EventAggregator to communicate between ui that might be more appropriate.


text:
Q: Android converting of file to bitmap returns null always I have an existing File in my application and I want convert it to Bitmap with options. I have a method for that. But always this method returns null and when I try get properties of bitmap I catch NullPointerException. Here's a code:
public static Bitmap convertToBitmap(File file) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    options.inSampleSize = 4;
    return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
}

If I remove options and call BitmapFactory.decodeFile(file.getAbsolutePath()) I'll get OutOfMemoryError on some devices. What can I do with that?

A: you can try the below code :)
    final Uri uri= Uri.fromFile(new File(file))
    try{
        Bitmap selectedImageBitMap= MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
        //you have your image bitmap :)
      }
    catch (FileNotFoundException fileNotFoundException){
        Log.d("sandeep","could not find file");
      }
    catch(IOException ioexception) {
        Log.d("sandeep", "IOException");
      }

Lemme know if you still have issue :) Happy coding :)

A: Try this
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap =BitmapFactory.decodeFile(file.getAbsolutePath(),bmOptions);
bitmap =Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);


text:
Q: Importing a python file as a module from another python file I have the following structure:
edgar_sec
│   ├── __init__.py
│   ├── logs
│   ├── requeriments.txt
│   ├── resources
│   │   ├── __init__.py
│   │   ├── us_states.py
│   │   └── us_stocks_symbol.csv
│   ├── scripts
│   │   ├── __init__.py
│   │   ├── company_info.py
│   │   ├── financial_reports.py
│   │   └── insiders.py
│   └── tests
│       ├── __init__.py
│       ├── company_info_test.py
│       ├── company_info_test2.py
│       └── sec_insiders.py

I want to import us_states.py into company_info_test2.py, so I'm doing import edgar_sec.resources.us_states but I'm getting ModuleNotFoundError: No module named 'edgar_sec'
What is wrong?

A: Try to put tests outside of package
And also tests don't need to be a package
eg.
edgar_sec
│   ├── __init__.py
│   ├── logs
│   ├── requeriments.txt
│   ├── resources
│   │   ├── __init__.py
│   │   ├── us_states.py
│   │   └── us_stocks_symbol.csv
│   ├── scripts
│   │   ├── __init__.py
│   │   ├── company_info.py
│   │   ├── financial_reports.py
│   │   └── insiders.py
└── tests
    ├── company_info_test.py
    ├── company_info_test2.py
    └── sec_insiders.py

Also I see that the project does not follow a standard approach to packaging python applications.
You may have better luck following this tutorial on packaging your python projects:
https://packaging.python.org/tutorials/packaging-projects/


text:
Q: Fedora 14 boot from CD stalls I'm trying to install Fedora 14 on my Dell T3400 (NVidia).
I created a DVD image and used that to successfully install it on another laptop so I know the image is ok.
However, when I boot from DVD on the desktop, it boots up Fedora and then stalls at the blue screen with the Fedora logo.
Is there a means by which I can diagnose what the issue might be?

A: If you push esc.. what do you see ??
or try..
Alt+ctrl+f2
Alt+ctrl+f3
 etc
We need to see what the server is actually doing :D
Then its much easier to diagnose

A: Type "linux text" at the initial boot prompt, and complete the installation in text mode. Then, once you have a working system, figure out your graphics driver issues.


text:
Q: Matplotlib: different stacked bars? I want to create a stacked bar plot with different amount of stacks for each bar. The general example for stacked bars works fine if my data are all homogenous, but I want something that rather looks like the shown example.

This turned out to be whole other level in Matplotlib (while still easy with some Excel-like tool, as you can see). Is there a convenient way of creating this kind of plot in Matplotlib? Thanks.

A: I guess you are working directly in matplotlib, but these days plotting data, especially for quick a view can be easily done  with pandas, following your example we get:
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use("ggplot")
import pandas as pd
import numpy as np

df = pd.DataFrame([pd.Series([10,20,40,10,np.nan]), pd.Series([20,10,30,10,10]), pd.Series([30,40, np.nan, np.nan, np.nan])], index=["Bar1", "Bar2", "Bar3"])

df.plot.bar(stacked=True)
plt.show()


text:
Q: UI Testing (casperjs) with good known status of data (mysql database) I'm using CasperJS for automated UI tests. I've done the basic UI testing and validation with some random data, kind of POC. I've set up this automation using bash script which kicks to start the web server, load MySQL data from SQL file, start CasperJS test cases, stop the web server, check the log files.
Now, I want to start the testing with some good known status of data which are stored in MySQL. So that I can test the list data and form data with detailed field information with some known database status. How should I know the status of data in the database at a moment?
1) Should I use pre-populated JSON dumped file which has status and details about all data?
2) Should I use web service API? (web service APIs are being used to show/save/delete data from the web page)
Let's take an example. I've 5 users in Users table. Now when I open the home page it shows 5 users with some rough details. When I click on any record from the list of users, it shows a form with detailed information about that user. The webpage is requesting to the web application to get the detail about a user with the help of user_id to show the detailed user data in a form. Now I want to check that all the data in that form is populated correctly. So at the next step, what would be the preferred way, should I read content from JSON dumped file or should I use web service API (like webpage does).
Searching this problem online, I also found MYSQL HTTP plugin. Should I consider this as well? and How safe it is to use? (I know from the docs that this plugin is not for the production, it is just for testing purpose only. :) )

A: For the main question in cases like this I would change the database connection string to your testing database (this is a clone).
In your case use your bash script to change the connection string (file copy?) automatically before you run the tests. And when completed change back.
Your testing database is a direct clone of your dev/live databsae but with ONLY the test data you want.  Downside is you need to keep the schema in sync with DEV/LIVE.
Also another point to take into considertion is if your testing changes state (post). If so your testing data might be out of sync. One way is get around this is to drop foreign keys, truncate the data and load in a dump file.
HTH


text:
Q: Lost data when serializing treeview I am writing a program in C#, which assigns data to a class, then assigns that class to the Tag Value of treeview nodes.
I am able to serialize my treeview to file using an answer I found here: Saving content of a treeview to a file and load it later.
However, the Tag of all the nodes is lost using this method when de-serializing the file, or more likely, they are not even being serialized in the first place.
Is it possible to preserve the Tag value of the Nodes when serialized using this method? If so, how?

A: To be serialized successfully by BinaryFormatter, your Tag object must be marked as [Serializable], which indicates that it can be successfully serialized and deserialized by serializing its public and private fields.  If it is so marked, then it will be serialized as part of a TreeNode, as is shown by the reference source:
[TypeConverterAttribute(typeof(TreeNodeConverter)), Serializable,
DefaultProperty("Text"),
SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")]
public class TreeNode : MarshalByRefObject, ICloneable, ISerializable {

    object userData;

    protected virtual void Serialize(SerializationInfo si, StreamingContext context) {

        // SNIP storage of irrelevant fields.

        if (userData != null && userData.GetType().IsSerializable) {
            si.AddValue("UserData", userData, userData.GetType());
        }
    }

    public object Tag {
        get {
            return userData;
        }
        set {
            userData = value;
        }
    }
 }

Note that, if your Tag object is not serializable, it will be silently skipped; no exception will be thrown.

A: I'd like to improve upon this answer.
It's important that [Serializable()] be used before the class and that the class is derived from ISerializable.
Additionally, the presence of the overloaded constructor function that can accept the arguments from deserialization and the GetObjectData function were important.
In essence, the GetObjectData function provides the ability for the serializer to access all information as a string while the overloaded NodeTag constructor can re-interpret that serialized string data and load it back into the object.
I had to construct my class in the following fashion (this is semi-pseudo code):
[Serializable()]
class NodeTag : ISerializable
    {
        public NodeTag(string Subnet)
        {
         Broadcast_Address = Stuff;
         Network_Name = Stuff;
         CIDR_Value = Stuff;
         }
        public string Network_Name { get; set; }
        public string CIDR_Value { get; set; }
        public string Broadcast_Address { get; set; }

        //Deserializer - loads back from file data
        //This is an overloaded function that defines the data object when it is being reconstituted
        public NodeTag(SerializationInfo info, StreamingContext context)
        {
            Network_Name = (String)info.GetValue("Network_Name", typeof(string));
            CIDR_Value = (String)info.GetValue("CIDR_Value", typeof(string));
            Broadcast_Address = (String)info.GetValue("Broadcast_Address", typeof(string));
        }
        //Serializer - loads into file data
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Network_Name", Network_Name);
            info.AddValue("CIDR_Value", CIDR_Value);
            info.AddValue("Broadcast_Address", Broadcast_Address);
        }
    }


text:
Q: Configuration Spring - Kafka for many clusters Kafka? What is best solution? I see people duplicating code to configure kafka for each cluster :(
Is it really necessary to configure Consumer Factory and Producer Factory with different settings every time? And do not use Spring Boot Kafka starter in any way?

A: Spring Boot auto-configuration is by convention for the common microservices use-case: one thing, but simple and clear.
What you are asking is out of Spring Boot scope: the properties configuration is applied only for one ConsumerFactory and one ProducerFactory. As long as you need to connect to different clusters you are on your own. Having a custom ConsumerFactory bean will lead Spring Boot auto-configuration to back off.
You probably can look into a child ApplicationContext configuration with its own provided set of properties. But will it be easier to just have custom configuration for each cluster as you would do without Spring Boot with just a plain Apache Kafka client?
I have no idea if there is some federation solution for Apache Kafka. But that's still out of Spring for Apache Kafka and Spring Boot scope.

A: If you use similar properties for each cluster, you can override the bootstrap.servers property for each @KafkaListener and/or create multiple @KafkaTemplates with the same override.
Then, the same factories can be used.
See https://docs.spring.io/spring-kafka/docs/current/reference/html/#annotation-properties
@KafkaListener(topics = "myTopic", groupId = "group", properties = {
    "max.poll.interval.ms:60000",
    ConsumerConfig.MAX_POLL_RECORDS_CONFIG + "=100"
})

/**
 * Create an instance using the supplied producer factory and properties, with
 * autoFlush false. If the configOverrides is not null or empty, a new
 * {@link DefaultKafkaProducerFactory} will be created with merged producer properties
 * with the overrides being applied after the supplied factory's properties.
 * @param producerFactory the producer factory.
 * @param configOverrides producer configuration properties to override.
 * @since 2.5
 */
public KafkaTemplate(ProducerFactory<K, V> producerFactory, @Nullable Map<String, Object> configOverrides) {


text:
Q: How to generate a Subgroup thru coset representative/group element pairs My main priority is to understand what the question is asking (how the different concepts relate). Secondarily, any hints along the way would be helpful...
Set: K a group.
Set: L a subgroup.
Set: P a set of right coset representatives (w/ e∈P).
Therefore, we have a bijection: P×L → K given by (p,l)↦pl.
Define w(k,p)∈P and z(k,p)∈L by the requirement that kp=w(k,p)z(k,p), for all k∈K, p∈P. Let G be a set of generators of K.
Show that the set of {z(g,p)} where g∈G and p∈P generates L.


text:
Q: what is the difference between ObjectQuery and "var"? Look please below what is the difference between two type of codes. is there any performance difference or what else?
First Codes

                ObjectQuery departmans = staffContext.Departman;
                GridView1.DataSource = departmans;
                GridView1.DataBind();

Second Codes

var departmans = staffContext.Departman;
   GridView1.DataSource = departmans;
                GridView1.DataBind();

Thanks

A: The effective difference in the outputted code depends on the type of Departman.  If the type of Departman is ObjectQuery then the code is equivalent.
The "var" keyword simply tells the compiler, please set the type of this variable to the same type as the expression assigning to it.  In this case, it's the type of Departman.

A: There is no difference (assuming the type of staffContext.Departman is ObjectQuery and not some sub class of ObjectQuery).  The compiler just infers the type based on the right-hand side of the assignment.

A: The type that the var keyword represents has to be known at compile time, so as long as the type actually is the same in both cases the executable code will be identical.
The type is inferred based on the type of the right hand side, so in some cases you need to specify the type to get the result that you want. For example:
Stream s = File.OpenRead(fileName);

This will of course give you a variable of the type Stream. On the other hand:
var s = File.OpenRead(fileName);

This will instead give you a variable of the type FileStream.
As a general rule, if the type on the right hand side isn't obvious, you should not use the var keyword at all.


text:
Q: Python - Timestamp Conversion I have converted some sensor data into CSV format. The data contains a timestamp attribute that is divided into two parts as follows:
measurement_timestamp_begin:
  seconds: 3733032665
  fractions: 3056174174

I need to convert this into standard UNIX timestamp format. I saw several posts for doing the conversion but each method receives a single argument. I don't understand the fraction part.  Does it mean seconds.fraction? e.g. 3733032665.3056174174.

A: Following code converts above mentioned timestamp format to standard UNIX timestamp format.
#!/usr/bin/env python

import datetime, time

unix_epoch = datetime.date(*time.gmtime(0)[0:3])

ntp_epoch = datetime.date(1900, 1, 1)

ntp_delta = (unix_epoch - ntp_epoch).days * 24 * 3600

def ntp_to_unix_time(date):
    return (date - ntp_delta)

print datetime.datetime.fromtimestamp(int(ntp_to_unix_time(3733032665.3056174174))).strftime('%Y-%m-%d %H:%M:%S')


text:
Q: How do we find the derivative of the following function: $F(x)=\sin\Big(\int_0^x \sin\big(\int_0^y \frac{1}{1+t^4}\ dt\big)\ dy\Big)$ using FTC. Find the derivative of the following function:
$F(x)=\sin\Big(\int_0^x \sin\big(\int_0^y \frac{1}{1+t^4}\ dt\big)\ dy\Big)$
I tried applying fundamental theorem of calculus directly but the the integral $\int_0^y \frac{1}{1+t^4}\ dt$ is giving me problems, I started by deriving both sides with respect to x, and by chain rule, the derivative should be f'(g(x))*g'(x). I reached this point and couldn't complete, does anyone have the key for the solution?

A: Well, we are trying to find:
$$\text{p}'\left(x\right):=\frac{\text{d}}{\text{d}x}\left(\sin\left(\underbrace{\int_0^x\sin\left(\int_0^y\frac{1}{1+t^4}\space\text{d}t\right)\space\text{d}y}_{:=\space\text{z}\left(x\right)}\right)\right)\tag1$$
First we use the cain rule, in order to write:
$$\text{p}'\left(x\right)=\frac{\text{d}}{\text{d}x}\left(\sin\left(\text{z}\left(x\right)\right)\right)=\cos\left(\text{z}\left(x\right)\right)\cdot\text{z}'\left(x\right)\tag2$$
Now, we must find $\text{z}'\left(x\right)$:
$$\text{z}'\left(x\right)=\frac{\text{d}}{\text{d}x}\left(\int_0^x\underbrace{\sin\left(\int_0^y\frac{1}{1+t^4}\space\text{d}t\right)}_{:=\space\text{k}\left(y\right)}\space\text{d}y\right)\tag3$$
Using FTC (by definition), we can see:
$$\text{z}'\left(x\right)=\frac{\text{d}}{\text{d}x}\left(\int_0^x\text{k}\left(y\right)\space\text{d}y\right)=\text{k}\left(x\right)\tag4$$
So, we get:
$$\text{p}'\left(x\right)=\cos\left(\text{z}\left(x\right)\right)\cdot\text{k}\left(x\right)=$$
$$\cos\left(\int_0^x\sin\left(\int_0^y\frac{1}{1+t^4}\space\text{d}t\right)\space\text{d}y\right)\cdot\sin\left(\int_0^x\frac{1}{1+t^4}\space\text{d}t\right)\tag5$$