text:
Q: Auth0: Login on Website - Allow access to API in ASP.NET Core Using Auth0 for auth in 2 different ASP.NET Core-applications, how do I allow a user to register/login in one application (the website) and then use credentials somehow to call another application (the API)?
Is it possible to generate a bearer-token, which doesn't expire (but can be regenerated), which can be exposed on the website-app and then used in the HTTP-headers to access the API-app?
What other strategies could be used to make sure a user can use an API, without getting a graphical login-screen?

A: The default JWT token lifetime is 30 days (2592000 seconds) , you can set the lifetime in dashboard . You can use refresh token to renew the access token , Refresh tokens can also expire but are rather long-lived.
You can use Resource owner flow / client credential flow to acquire access token for protected resource . But Resource owner flow needs user's credential, it's not safe to collect user's credential in a web application . And client credential flow uses client's credential which is also not meet your requirement since you need user's login . I am afraid currently there is no never expire JWT tokens in your scenario .


text:
Q: Is there any numerical solver in python with control of each iteration? I am solving a linear system of equation currently i am using
   numpy.linalg.solve

It returns the solution of the linear system.
   I want to have a control such that i can execute iterations
Considering another option
    scipy.optimize.minimize

Documentation describes that we can specify a function which is called
   after every iteration and we could have current parameters.
   I am not sure if they meant that we could get the current resultant vector.
   e.g Simply I want to access x after every iteration, while we are solving Ax=b
I am wondering if somebody has worked with it and can explain!
Thanks

A: The callback keyword argument to scipy.optimize.minimize specifies a function that will be called with the current estimate of the argument that minimizes the function at each iteration.
But minimize is intended for a scalar function (one returning a single value) so I don't see how that is applicable to your example.  You may want to try scipy.optimize.fsolve instead.  It doesn't accept the callback keyword though.  To get around that, you could wrap your linear equation in a callable function object (that returns Ax-b) and then just take the argument that is passed to your callable object.
class Ab:
    def __init__(self, A, b):
        self.A = A
        self.b = b
    def __call__(self, x):
        print 'x =', x
        return A.dot(x) - b

Then use it like this:
>>> A = np.array([[2, 3], [4, 9]], float)
>>> b = np.array([5, 5])
>>> f = Ab(A, b)
>>> optimize.fsolve(f, [0, 0])
x = [0 0]
x = [ 0.  0.]
x = [ 0.  0.]
x = [  1.49011612e-08   0.00000000e+00]
x = [  0.00000000e+00   1.49011612e-08]
x = [ 5.         -1.66666667]
x = [ 5.         -1.66666667]
array([ 5.        , -1.66666667])

fsolve reported only taking 5 iterations so it appears the first two calls may be not actually used for convergence.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get a json of a post method I am trying get data of this site http://veiculos.fipe.org.br/
the json file I want to get is the one that appears on the right of the
image
url = "http://veiculos.fipe.org.br/api/veiculos/ConsultarValorComTodosParametros"

data = {"codigoTabelaReferencia" : "215",
    "codigoMarca" : "2",
    "codigoModelo" : "4564",
    "codigoTipoVeiculo" : "1",
    "anoModelo" : "2015",
    "codigoTipoCombustivel " : "3",
    "tipoVeiculo" : "carro",
    "modeloCodigoExterno" :  "",
    "tipoConsulta" : "tradicional"
    }

c = requests.post(url,data=data)
c.json()

when the last line is executed this error meassege return:
JSONDecodeError: Expecting value: line 2 column 1 (char 2)

At the end of the code I want this dictionary to be returned:
{"Valor":"R$ 14.421,00","Marca":"Alfa Romeo","Modelo":"145 Quadrifoglio 2.0","AnoModelo":1999,"Combustivel":"Gasolina","CodigoFipe":"006002-0","MesReferencia":"agosto de 2018 ","Autenticacao":"hsd0d2ycx5","TipoVeiculo":1,"SiglaCombustivel":"G","DataConsulta":"terça-feira, 28 de agosto de 2018 16:10"}

A: import requests
import json

url = "http://veiculos.fipe.org.br/api/veiculos/ConsultarValorComTodosParametros"

data = {"codigoTabelaReferencia" : "215",
    "codigoMarca" : "2",
    "codigoModelo" : "4564",
    "codigoTipoVeiculo" : "1",
    "anoModelo" : "2015",
    "codigoTipoCombustivel " : "3",
    "tipoVeiculo" : "carro",
    "modeloCodigoExterno" :  "",
    "tipoConsulta" : "tradicional"
    }

c = requests.post(url,data=data)

print json.dumps(data)

A: Try this:
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Language': 'en-US,en;q=0.5',
    'Referer': 'http://veiculos.fipe.org.br/',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest',
    'DNT': '1',
    'Connection': 'keep-alive',
}

data = [
  ('codigoTabelaReferencia', '232'),
  ('codigoMarca', '3'),
  ('codigoModelo', '7'),
  ('codigoTipoVeiculo', '1'),
  ('anoModelo', '1999'),
  ('codigoTipoCombustivel', '1'),
  ('tipoVeiculo', 'carro'),
  ('modeloCodigoExterno', ''),
  ('tipoConsulta', 'tradicional'),
]

response = requests.post('http://veiculos.fipe.org.br/api/veiculos/ConsultarValorComTodosParametros', headers=headers, data=data)

print(response.json())


text:
Q: How to sign in an external ClaimsIdentity using IdentityUser Asp.Net Core 2.2?
Context Summary

I'm building a prototype WebApp which I want to integrate to Quickbooks Online.
This WebApp will in turn offer options to call a WebApi that will be responsible to make the requests against the Quickbooks Online WebApi.
In order to achieve this, I registered the Identity services to make it easier for me to have a login process etc.
Now, it seems that I'm confused between Individual Account (IdentityUser) and ClaimsIdentity.

Signing In

When I click the Login option from the top menu, I get correctly redirected to the Quickbooks Online authentication screen where:

*

*I input my user credentials

*I choose the company I wish to use

*I authorize the WebApp to access the required scopes

On callback, I do a request against the user information endpoint and retrieve all user information needed.

*

*sub

*givenName

*familyName

*email

*emailVerified

And

*

*ClaimsIdentity.IsAuthenticated == true

So, I build the list of claims for the ClaimsPrincipal.Identity which just was authenticated externally, and try to sign it in.
var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
var user = (ClaimsIdentity)context.Principal.Identities.Single(claimsIdentity => claimsIdentity.AuthenticationType == "ecm-qbo");
user.AddClaim(new Claim(type: ClaimTypes.Name, result["givenName"]));
result.ToList().ForEach(kvp => {
    user.AddClaim(new Claim(type: kvp.Key, value: kvp.Value, valueType: null, issuer: "qbo", originalIssuer: "qbo", subject: user));
});

But I get this error once my sign process is completed.

What can I do to avoid it, or to correct it so it signs my user in?

Code Sample

    public void ConfigureServices(IServiceCollection services) {
        services.Configure<CookiePolicyOptions>(options => {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.ConfigureApplicationCookie(o => {
            o.Cookie.Name = "auth_cookie";
            o.Cookie.SameSite = SameSiteMode.None;

            o.Events.OnRedirectToLogin = context => {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                return Task.CompletedTask;
            };
        });

        services.AddAuthentication(o => {
            o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
            .AddOAuth("qbo", "qbo", o => {
                o.CallbackPath = new PathString("/signin-qbo");
                o.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
                o.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
                o.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "givenName");
                o.ClaimActions.MapJsonKey(ClaimTypes.Surname, "familyName");
                o.ClaimActions.MapJsonKey(ClaimTypes.Name, "givenName");
                o.ClientId = Configuration["ecm.qbo.client-id"];
                o.ClientSecret = Configuration["ecm.qbo.client-secret"];
                o.SaveTokens = true;
                o.ClaimsIssuer = "ecm-qbo";
                o.Scope.Add("openid");
                o.Scope.Add("profile");
                o.Scope.Add("email");
                o.Scope.Add("com.intuit.quickbooks.accounting");

                o.AuthorizationEndpoint = Configuration["ecm.qbo.authorization-endpoint"];
                o.TokenEndpoint = Configuration["ecm.qbo.token-endpoint"];
                o.UserInformationEndpoint = Configuration["ecm.qbo.user-info-endpoint"];

                o.Events.OnCreatingTicket = async context => {
                    var companyId = context.Request.Query["realmid"].FirstOrDefault() ?? throw new ArgumentNullException("realmId");
                    var accessToken = context.AccessToken;
                    var refreshToken = context.RefreshToken;
                    var tokens = context.Properties.GetTokens();

                    Configuration["ecm.qbo.access-token"] = accessToken;
                    Configuration["ecm.qbo.refresh-token"] = refreshToken;
                    Configuration["ecm.qbo.realm-id"] = companyId;

                    context.Backchannel.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                    context.Backchannel.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var response = await context.Backchannel.GetStringAsync(context.Options.UserInformationEndpoint);

                    var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
                    var user = (ClaimsIdentity)context.Principal.Identities.Single(claimsIdentity => claimsIdentity.AuthenticationType == "ecm-qbo");
                    user.AddClaim(new Claim(type: ClaimTypes.Name, result["givenName"]));
                    result.ToList().ForEach(kvp => {
                        user.AddClaim(new Claim(type: kvp.Key, value: kvp.Value, valueType: null, issuer: "qbo", originalIssuer: "qbo", subject: user));
                    });

                    await context.HttpContext.SignInAsync(IdentityConstants.ExternalScheme, context.Principal, new AuthenticationProperties {
                        IsPersistent = false,
                        RedirectUri = "/"
                    });
                };
            });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }


text:
Q: Pub/Sub input in templated Dataflow is completely ignoring NestedValueProvider I've create template for Dataflow which is reading messages from Pub/Sub
The problem is that NestedValueProvider is not possible to modify sended via options value and I do not have clue why - below some screens
Passed parameter:

Code:

Result:

If anyone would ask why I needto nest it - I wanted to only require to add subscriptionID and just add prefix with rest of the path..

EDIT
My steps:
1.Created pipeline which is reading from Pub/Sub subscription and for subscription name is using NestedValueProvider for creating subscription name
pipeline.apply(
                            "Read PubSub messages",
                            PubsubIO.readStrings().fromSubscription(
                                    NestedValueProvider.of(
                                            options.getSubscriptionID(),
                                            input -> "projects/ozone-analytics-dev/subscriptions/" + input)
                            )
                    )

2.Created template
3.Running template with valid and existing subscriptionID
4.Seeing an error while creating dataflow job (I think that job didn't even start and this error is through some pre validation cause I can run this flow locally or normally with DataflowRunner but not via template)

A: After analyse - this is rather Google Dataflow bug which only is related to template creation validation (because every other way of Dataflow run is behaving correctly)
I've created issue for that
https://issuetracker.google.com/u/1/issues/157584222
And for now it is the answer for that problem


text:
Q: When I run simple select query, is it possible not to show number of rows affected at the end? I try to use OSQL in order to save query results in text file and later bulk insert those text file to a table. OSQL part is ok, however, in bulk insert, number of rows affected at the end of query results causes error. Here is an example;
select item_number, description, price from item

3536114   Fruit mix     $3.99

3536229   DO 20 liquid  $9.99

3536251   Peppermint    $7.99

(3 rows affected) ------> I do not need this line.

A: Use SET NOCOUNT like so:
SET NOCOUNT ON;

This will:

Stops the message indicating the number of rows affected by a
  Transact-SQL statement from being returned as part of the results.

A: Put this at the top of the query:
SET NOCOUNT ON

When SET NOCOUNT is ON, the count is not returned. When SET NOCOUNT is
  OFF, the count is returned.
The @@ROWCOUNT function is updated even when SET NOCOUNT is ON.
SET NOCOUNT ON prevents the sending of DONE_IN_PROC messages to the
  client for each statement in a stored procedure. For stored procedures
  that contain several statements that do not return much actual data,
  or for procedures that contain Transact-SQL loops, setting SET NOCOUNT
  to ON can provide a significant performance boost, because network
  traffic is greatly reduced.
The setting specified by SET NOCOUNT is in effect at execute or run
  time and not at parse time.

http://msdn.microsoft.com/en-us/library/ms189837.aspx

A: You can achive this by:-
 SET NOCOUNT ON

When SET NOCOUNT is ON, the count (indicating the number of rows affected by a Transact-SQL statement) is not returned. When SET NOCOUNT is OFF, the count is returned.
Check this Documentation


text:
Q: SQL Sub Query when joining table I am back to a similar issue I have had previously. It should be a simple thing, but cannot get my head around it.  Here is an overview of the tables and what I am trying to achieve with this subquery. I am using SQL Server 2008.
Users
This contains a list of users
Login Audit
Contains a list of login attempts. It holds the userID and the loginDate (datetime field)
What I am trying to achieve
I want to be able to show rows of users and their last login date from the audit table.
Here is my query, that would make sense from a laymans perspective! ;-)
SELECT  u.userID, u.fName, u.sName, l.loginDate
   FROM    Users AS u LEFT OUTER JOIN
                      (SELECT    TOP (1) loginDate, userID
                        FROM   LoginAudit) AS l ON l.userID = u.userID
   WHERE   (u.cliID = 1)

This just pulls back the last loginDatefor the last user that logged in. I wanted all of the users to come back regardless if they logged in or not.
Any assistance would be appreciated.
Thanks
nick

A: select a.userid, a.fName, a.sName,
  max(b.loginDate)
from
   users a
   left outer join lastLogin b on a.userid = b.userid
group by a.userid, a.fName, a.sName

A: You want to replace your subquery with
SELECT userID, max(loginDate) as lastLogin FROM LoginAudit GROUP BY userID

And then replace "l.loginDate" in your main query with "l.lastLogin"
The functionality you want is provided by the MAX() function in an aggregate query, not the TOP() function.


text:
Q: extracting values from dataframe1 using conditions set in dataframe2 (pandas, python) _ Part 2 I've asked a similar question in the past, however, its filtering with different conditions. hence, i'm posting this:
I have two dateframe (df1 & df2), i'm trying to figure out how to use conditions from df2 to extract values from df1 and use the extracted values in df2.
df1 = values to exact from
df2 = conditions for exaction and df where the extracted values are used
conditions: df2.ans = df2HJ & df2.P1 = df1 P2 colum
example if df2(df2.HJ = 99 & df2.P1 = 0); Ans = 76 (from df1)
df1

╔════╦════╦══════╦
║ HJ ║ P1 ║  P2  ║
╠════╬════╬══════╬
║  5 ║ 51 ║  33  ║
║ 11 ║ 66 ║  45  ║
║ 21 ║  7 ║  55  ║
║ 99 ║  0 ║  76  ║
║ 15 ║ 11 ║  42  ║
╚════╩════╩══════╩

df2

╔════╦════╗
║ HJ ║ P1 ║
╠════╬════╣
║ 99 ║ 0  ║
║ 11 ║ 66 ║
║  5 ║ 51 ║
║ 21 ║ 7  ║
║ 11 ║ 66 ║
╚════╩════╝

expected result for df2 after exaction from df1

╔════╦════╦═══════╗
║ HJ ║ P1 ║  Ans  ║
╠════╬════╬═══════╣
║ 99 ║ 0  ║   76  ║
║ 11 ║ 66 ║   45  ║
║  5 ║ 51 ║   33  ║
║ 21 ║ 7  ║   55  ║
║ 11 ║ 66 ║   45  ║
╚════╩════╩═══════╝

code for df1
import pandas as pd
import numpy as np
data = {'HJ':[5,11,21,99,15],
'P1':[51,66,7,0,11]
,'P2':[ 33,45,55 ,76 ,42]}
df1 = pd.DataFrame(data)

code for df2
data = {'HJ':[99,11,5,21,11],
'P1':['0','66','51','7','66']}
df2 = pd.DataFrame(data)

Regards
Thank you

A: I don't know why you want this example, cause your expected result  its df1 with other order.
But if you want to connect different dataframes, it will be usefull use .join function: Join panda's function

A: Thanks to @Pol Renau Larrodé pointers i was able to solve the problem.
res = df2.merge(df1, how='inner', left_on=['HJ ', 'P1'], right_on=['HJ ', 'P1'])


text:
Q: Object doesn't support property or method WebBrowser Control I have developed a mobile app (in asp.net) and I am using a WinForms application with the WebBrowser control to demo it.
I my main page I am using a script to hide the address bar:
<script type="text/javascript">
    window.addEventListener("load", function () {
        // Set a timeout...
        setTimeout(function () {
            // Hide the address bar!
            window.scrollTo(0, 1);
        }, 0);
    });
</script>

This has worked ok an several machines but this morning on a new machine I encountered an popup when the page loads:

The machine in question has IE9 installed and I have the Disable Script Debugging setting Checked.
What is the best way to tackle this issue. Can I add some condition in the JS to not execute when running in IE?

A: I know that this problem is from 2012 but there is an answer for it.
At the top of the <head> document where script is added you need to write
<meta http-equiv="X-UA-Compatible" content="IE=edge">

WinForms WebBrowser control is using Internet Explorer but you need to force the latest version there. For eg. if you are using jQuery 2+ it requires IE 9+ so you need to use at least version 9 or later.

A: Webbrowser control doesn't suppert jquery v2.
Use the jquery 1.9.1.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

A: The Webbrowser control is a part of the Internet Explorer itself. And Internet Explorer doesnt support the window.addEventListener method. Use window.attachEvent method instead.
So the script in your page will read like
window.attachEvent("load", function () {
    // Set a timeout...
    setTimeout(function () {
        // Hide the address bar!
        window.scrollTo(0, 1);
    }, 0);
});

Hope this would help you!


text:
Q: How to install ChromeDriver in RedHat Linux? I am trying to use selenium on RHEL(Red Hat).
In order to use Chrome browser, I need to install the chromedriver.
Does anyone know how to install this, or what command I need to use? I did not find any resources on this that worked.
Really appreciate any help.
Thank you.

A: I followed a process which worked for me.
I am using Redhat 7.4, and I've been through a lot to uninstall and install chrome and firefox, got partially successful with chrome and this is what I tried.
In the Linux terminal
Go to the root by typing

*

*su -

Then type

*

*rpm -qa

then (ctrl+f) and search for the keywords "google" or " chrome" or "mozilla" or "firefox" to check whether they are present or not and if they are available, then uninstall( remove ) them by the following command ( if you want to remove them )

*

*yum remove (theWholeName)

this removes the application
Then install chrome by the following process
type this in terminal

*

*wget
https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
then a package gets downloaded in your home folder
Then type the following command - this installs the packages

*

*yum -y install (name of the downloaded folder with extension)

in this case it will be

*

*yum -y install google-chrome-stable_current_x86_64.rpm

This installs google chrome and creates an icon under Application->Internet->googleChrome
IMPportant:
technically, by clicking this googlechrome icon- this should open the browser, but it doesn't open the browser for me, I dont know whats the problem and I appreciate any suggestion regarding this issue.
I open google chrome through terminal using this command

*

*google-chrome --no-sandbox

this opens the chrome browser.


text:
Q: Opening curly brace at a newline in Kotlin Based on Kotlin coding conventions, it is discouraged to put opening curly braces on its own line as semi-colons are optional and that might cause surprising behavior. What would the surprising behavior be if we put the opening brace on its own line?

Formatting
In most cases, Kotlin follows the Java coding conventions.
Use 4 spaces for indentation. Do not use tabs.
For curly braces, put the opening brace in the end of the line where
  the construct begins, and the closing brace on a separate line aligned
  horizontally with the opening construct.
if (elements != null) {
    for (element in elements) {
        // ...
    }
}

(Note: In Kotlin, semicolons are optional, and therefore line breaks are significant. The language design assumes Java-style braces,
  and you may encounter surprising behavior if you try to use a
  different formatting style.)

A: The comment about surprising behavior is not about the curly brace, but more general. Consider this code:
val result = 1
+ 2
println(result)

you might expect this to print "3", but it prints "1" because these are 2 statements, val result = 1 and + 2
You would write it like this in Kotlin if you wanted to break the line:
val result = 1 +
2

this is a simple example, but highlights the difference that not having semicolons to determine the end of a statement makes.


text:
Q: Declaring dependency on Mockito using Maven/pom.xml in IntelliJ IDEA I am relatively new to using Java and would like to improve these unit tests I have written by using mocks. I have heard mockito is a good library so I am trying to declare the dependency in the pom.xml file of my project but wherever I place the lines in the file, I am given an error 'Invalid content was found starting with the element 'dependency'. I have looked on the Mockito docs but they seem to jump straight in to importing at the top of your test files not actually configuring it.
My pom.xml file currently:
<modelVersion>4.0.0</modelVersion>

<groupId>groupId</groupId>
<artifactId>JAirport</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.10</source>
                <target>1.10</target>
            </configuration>
        </plugin>

    </plugins>
</build>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.8.4</version>
    <scope>test</scope>
</dependency>
</project>

Thank you!

A: You need to wrap your <dependency> tag in a <dependencies> tag
<modelVersion>4.0.0</modelVersion>

<groupId>groupId</groupId>
<artifactId>JAirport</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.10</source>
                <target>1.10</target>
            </configuration>
        </plugin>

    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.8.4</version>
        <scope>test</scope>
    </dependency>
</dependencies>
</project>


text:
Q: tf.strings.format automatically wraps a scalar tensor as a list tf.strings.format function automatically wraps a solitary tensor as a list.
For example what if I want to do something like this:
x = tf.convert_to_tensor('x')
[tf.strings.format("/path/to/directory/{}_{}.png", (x, y)) for y in range(2)]

The output will be:
[<tf.Tensor: id=712, shape=(), dtype=string, numpy=b'/path/to/directory/[x]_0.png'>,
 <tf.Tensor: id=714, shape=(), dtype=string, numpy=b'/path/to/directory/[x]_1.png'>]

Whereas a desired output is:
[<tf.Tensor: id=712, shape=(), dtype=string, numpy=b'/path/to/directory/x_0.png'>,
 <tf.Tensor: id=714, shape=(), dtype=string, numpy=b'/path/to/directory/x_1.png'>]

A: EDIT:
You can concatenate strings normally with + operator:
import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    x = tf.convert_to_tensor('x')
    path = tf.constant("/path/to/directory/")
    sep = tf.constant("_")
    ext = tf.constant(".png")
    res = [path + x + sep + tf.constant(str(y)) + ext for y in range(2)]
    print(sess.run(res))
    # [b'/path/to/directory/x_0.png', b'/path/to/directory/x_1.png']

Or, if you don't mind recreating constant tensors (which you probably don't in eager mode), just:
res = ["/path/to/directory/" + x + "_" + str(y) + ".png" for y in range(2)]

You can get the result you want with tf.strings.join:
import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    a = tf.convert_to_tensor('a')
    b = tf.convert_to_tensor('b')
    c = tf.convert_to_tensor('c')
    print(sess.run(tf.strings.join([a, b, c], '/')))
    # b'a/b/c'


text:
Q: Decomposition into partial fractions to compute an integral I'm having problems with:
$$\int_{-\infty}^{\infty}\frac{x^4+1}{x^6+1}dx$$
I was thinking: $\frac{x^4+1}{x^6+1}$ is an even function and the interval $(-\infty,\infty)$ is symmetric about 0, we could write the integral like:
$$2\int_{0}^{\infty}\frac{(x^4+1)}{x^6+1}dx$$
And for $\frac{x^4+1}{x^6+1}$, I will use the partial fractions. I will write $x^6+1$ like a sum of cubes $x^6+1=(x^2)^3+1^3$ and use the formula $a^3+b^3=(a+b)(a^2-ab+b^2)$ and in the end we will have
$$x^6+1=(x^2+1)(x^4-x^2+1)$$ But now I'm stuck and do not know how to decompose $x^4-x^2+1$. I was thinking about $(x^2-1)x^2+1$ or $(x^2-\frac{1}{2})^2+\frac{3}{4}$ but I need a form for that like $-(-1+\sqrt3 x-x^2) (1+\sqrt3 x+x^2)$...
A little help here?

A: HINT:
As $y^3+1=(y+1)(y^2-y+1),$
$$\dfrac{x^4+1}{x^6+1}=\dfrac{x^4-x^2+1}{x^6+1}+\dfrac{x^2}{x^6+1}=\dfrac1{x^2+1}+\dfrac{x^2}{x^6+1}$$
Set $x^3=u$ for the second part

A: Another way,
Solution :
\begin{align}
\int_{-\infty}^{\infty}\frac{x^4+1}{x^6+1}\,\mathrm dx&=2\int_{0}^{\infty}\frac{x^4+1}{x^6+1}\,\mathrm dx\\[7pt]
&=2\int_{0}^{\infty}\frac{x^4\,\mathrm dx}{x^6+1}+2\int_{0}^{\infty}\frac{\mathrm dx}{x^6+1}\tag{$\color{red}{❤}$}\\[7pt]
&=\frac{\pi}{3\sin\left(\frac{5\pi}{6}\right)}+\frac{\pi}{3\sin\left(\frac{\pi}{6}\right)}\\[7pt]
&=\bbox[5pt,border:3px #FF69B4 solid]{\color{red}{\large\frac{4\pi}{3}}}
\end{align}

Explanation :
$(\color{red}{❤})\;$ $\displaystyle\int_0^\infty\frac{x^{\large n-1}}{x^m+1}\ \,\mathrm dx=\frac{\pi}{m\sin\left(\frac{n\pi}{m}\right)}\,$ for $\,0<n<m$.

A: $$\begin{eqnarray*}\int_{\mathbb{R}}\frac{x^4+1}{x^6+1}\,dx&=&2\int_{\mathbb{R}^+}\frac{x^4+1}{x^6+1}\,dx=2\int_{0}^{1}\frac{x^4+1}{x^6+1}\,dx+2\int_{1}^{+\infty}\frac{x^4+1}{x^6+1}\,dx\\&=&4\int_{0}^{1}\frac{x^4+1}{x^6+1}\,dx=4\int_{0}^{1}\sum_{k\geq 0}(-1)^k\left(x^{6k}+x^{6k+4}\right)\,dx\\&=&4\sum_{k\geq 0}(-1)^k\left(\frac{1}{6k+1}+\frac{1}{6k+5}\right)=4\sum_{k\geq 0}\frac{\chi(k)}{k}\end{eqnarray*}$$
where $\chi(k)$ is a Dirichlet character $\!\!\pmod{12}$, that equals one if $k\in\{1,5\}\pmod{12}$, minus one if $k\in\{7,11\}\pmod{12}$ and zero otherwise. We know in advance that:
$$ \sum_{k\geq 0}\frac{(-1)^k}{2k+1}=\arctan 1=\frac{\pi}{4},$$
$$ \sum_{k\geq 0}\frac{(-1)^k}{6k+3}=\frac{1}{3}\,\arctan 1=\frac{\pi}{12},$$
hence by summing these series we get $\sum_{k\geq 0}(-1)^k\left(\frac{1}{6k+1}+\frac{1}{6k+5}\right)=\frac{\pi}{3}$, so:

$$ \int_{\mathbb{R}}\frac{x^4+1}{x^6+1}\,dx = \color{red}{\frac{4\pi}{3}}.$$


text:
Q: Batch - Remove Range/specific words In perforce I print the list of shelved/changes to the file with the following batch script :
for %%A IN (%ShelvedCHL%) DO (
    echo Change List: %%A
    p4 -p %PPort% -c %PClient% unshelve -s %%A && if NOT %ERRORLEVEL%==0 exit -1
)>> list.txt

Here is my list.txt
Change List: 24536
//GSA/TOC.h#1 - unshelved, opened for edit
... /GSA/TOC.h - also opened by test@dev
... /GSA/TOC.h - also opened by test@dev
//odata/oenums.h#6 - unshelved, opened for edit
... //odata/oenums.h#6 - also opened by test@dev

I want to have the following output, basically remove sentence after - with dash as well : or even any perforce command to have less information and just list of files :
 //GSA/TOC.h#1
 ... /GSA/TOC.h
 ... /GSA/TOC.h
 //odata/oenums.h#6
 ... //odata/oenums.h#6

I would appreciate any help, thanks in advance!

A: You can do this in p4 natively without doing hardly any scripting at all.  Check out this blog post:
https://www.perforce.com/blog/fun-formatting
You can see the fields in a Perforce message by running it with the -e global opt*, like this:
p4 -e files ...
Then you can use any or all of those fields when reformatting the output, like this:
p4 -F "just the filename please: %depotFile%" files ...
*see also -Ztag which gives you an alternate dictionary of output fields

A: At first, let us take a look at your code:

*

*I do not know the program p4, but I assume it is setting the ErrorLevel. So since this value is updated in the same block of code as you want to read it, you need to use delayed expansion, so place setlocal EnableDelayedExpansion on top of your script and use !ErrorLevel! instead of %ErrorLevel%. Another way is to replace if not !ErrorLevel!==0 by ifnot ErrorLevel 1, meaning if ErrorLevel is not greater than and not equal to 1, or expressed in a simpler way, if ErrorLevel is less than 1, but this works only if the program does not set a negative value.

*Even if you corrected the ErrorLevel issue, the if query would never eb executed because of the conditional command concatenation operator %%, because this lets the following command only execute in case the preceding one succeeded, meaning that its exit code1 equals zero. Therefore to execute the if statement, use the unconditional operator &. Anyway, there is also another conditional operator ||, which lets the following command only execute in case the exit code is a non-zero value; this one could replace your if condition completely.

*The exit command does not only quit the batch file, it also terminates the command prompt (cmd) instance which the batch script ran in. To quit the batch file only use exit /B instead.

*You are setting the ErrorLevel to -1 by exit -1. You can do this, of course, but usually negative values are avoided; hence let me suggest a positive value like 1 (by exit /B 1).

*You are opening and closing the file list.txt for every single iteration of the for loop. This reduces overall performance. Furthermore, if list.txt already exists, the data becomes appended; if you do not want that you need to place del "list.txt" 2> nul before the for loop to initially delete the file. Anyway, to write the entire file at once, put another pair of parentheses around the for loop. You can then chose whether to append to an already existing file using the redirection operator >>, or to overwrite it using operator > (without any need to delete it first).

All this results in the following improved script:
(for %%A in (%ShelvedCHL%) do (
    echo Change List: %%A
    p4 -p %PPort% -c %PClient% unshelve -s %%A || exit /B 1
)) > "list.txt"

Depending on what %ShelvedCHL% contains (it seems to be 24536 in your sample data, so not a file path/name/mask), the for loop might even be superfluous, although I cannot know at this point...

Anyway, all of the above does still not yet account for removal of the partial string beginning with SPACE + - + SPACE, so let us implement this now:
To keep it simple, we could just modify the file list.txt after the above code, using this code (see all the explanatory rem remarks; the mentioned string manipulation is called sub-string substitution):
rem // Read file `list.txt` line by line:
(for /F "usebackq delims= eol=|" %%L in ("list.txt") do (
    rem // Assign line string to variable:
    set "LINE=%%L"
    rem // Enable delayed expansion to be able to do string manipulation:
    setlocal EnableDelayedExpansion
    rem /* Replace every occurrence of ` - ` by a single character `|`, then use this one
    rem    as a delimiter to split the line string as `for /F` requires single-character
    rem    delimiters; just using `-` is not good as they might occur in the partial
    rem    strings that need to be kept, I suppose; the `|` must not occur in them: */
    for /F "tokens=1 delims=| eol=|" %%K in ("!LINE: - =|!") do (
        rem // Disable delayed expansion to not lose `!`-marks:
        endlocal
        rem // Return the split string, that is the part before the (first) ` - `:
        echo %%K
    )
)) > "list_NEW.txt"

The resulting data is contained in the file list_NEW.txt. To have it in the original file, append the following line to the code:
move /Y "list_NEW.txt" "list.txt" > nul

1... Usually the exit code and ErrorLevel are the same, but there are in fact some rare cases where they may differ.


text:
Q: java.io.IOException:Environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials I want to use google cloud speech api in and android app for which I am following this link provided by google https://cloud.google.com/speech-to-text/docs/libraries#client-libraries-install-java
I have tried the solution provided in link https://developers.google.com/accounts/docs/application-default-credentials but it is still not working.
Windows Environment Variable user and system both have GOOGLE_APPLICATION_CREDENTIALS=C:\Users\ANSH\Downloads\credential.json
All the necessary imports are present.
 private void recognizeSpeech(){
    try{
        SpeechClient speechClient = SpeechClient.create();
        String languageCode="en-US";
        int sampleRateHertz=16000;
        RecognitionConfig.AudioEncoding encoding = RecognitionConfig.AudioEncoding.LINEAR16;
        RecognitionConfig config =
                RecognitionConfig.newBuilder()
                        .setLanguageCode(languageCode)
                        .setSampleRateHertz(sampleRateHertz)
                        .setEncoding(encoding)
                        .build();
        Path path = Paths.get(fileName);
        byte[] data = Files.readAllBytes(path);
        ByteString content = ByteString.copyFrom(data);
        RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(content).build();
        RecognizeRequest request =
                RecognizeRequest.newBuilder().setConfig(config).setAudio(audio).build();
        RecognizeResponse response = speechClient.recognize(request);
        for (SpeechRecognitionResult result : response.getResultsList()) {
            // First alternative is the most probable result
            SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
            outputText.setText(alternative.getTranscript());
        }
    }
    catch (Exception e){
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }
}

credential.json contains the key downloaded using the service account
ENVIRONMENT VARIABLE IMAGE
https://cloud.google.com/speech-to-text/docs/libraries mentions a note.
Note: Cloud Java client libraries do not currently support Android.
Does it mean it can not be used in android studio? If yes how to use it?

A: You might want to check this github link to see how the exception was resolved, but please consider that the Speech To Text Client Libraries specifies that doesn't support Android, as it was posted in the comments.
In addition, as your question is about an issue when setting authentication in your Android App, I would recommend you use an OAuth 2.0 client ID. You will need to generate an OAuth 2.0 client ID from the Google Console and then follow Android Instructions for passing requestIdToken or requestServerAuthCode in the GoogleSignInOptions. Also, please keep in mind that this doesn't guarantee the correct integration between Speech API and Android, so if you get this work please share it with us.


text:
Q: why is my dropdown selection not being submitted? I have a dropdown list when the form is submitted it is submitted null...
html:
@Html.DropDownListFor(c => Model.HowOftenCar, Model.HowOftenCar, new { id = "CompDrop" })

Model:
 public IEnumerable<SelectListItem> HowOftenCar { get; set; }

Controller:
IList<string> HowOftenCar = new List<string>();
HowOftenCar.Insert(0, "More than once a week");
HowOftenCar.Insert(1, "Once a month");
HowOftenCar.Insert(2, "Once a year");
model.HowOftenCar = HowOftenCar.Select(c => new SelectListItem()
{
  Text = c,
  Value = c
});

Post:
 [HttpPost]
 public ActionResult Index(Competition model)
 {
    if (ModelState.IsValid)
    {}
 }

I have also tried...
 @Html.DropDownListFor(c => Model.HowOftenCar, new SelectList(Model.HowOftenCar, "Value","Text"), new { id = "CompDrop" })

A: You're not using DropDownListFor correctly.
The first parameter is the property on the model you want to populate. If you want to populate the HowOftenCar property on the model, it should be of the type of the value - in this case, it looks like a string.
public string HowOftenCar { get; set; }

The second parameter is the list of choices. You've got that right, but it needs to be something else than the property you're trying to set.
IList<string> HowOftenCarChoices = new List<string>
{
    "More than once a week",
    "Once a month",
    "Once a year"
};

model.HowOftenCarChoices = HowOftenCar.Select(c => new SelectListItem()
{
    Text = c,
    Value = c
});

So then you'll end up with
@Html.DropDownListFor(m => m.HowOftenCar, Model.HowOftenCarChoices)

Note that you don't need the id property, because DropDownListFor will automatically give it the id of HowOftenCar, based on the lambda.


text:
Q: delete row from table where column does not exist in another table I have this SQL query that deletes a user's preferences from USERPREF table if they have not logged in for 30 days (last login date located in MOMUSER table), however, it does not verify that the user still exists in MOMUSER. How can I change this so that if USERPREF.CUSER does not exist in MOMUSER.CODE that the USERPREF row is also deleted in that situation since they will not have a last login date?
    DELETE USERPREF FROM USERPREF
    INNER JOIN MOMUSER ON MOMUSER.CODE = USERPREF.CUSER
    WHERE MOMUSER.LOG_START < GETDATE()-30

A: Change to an outer join, reverse the condition (so you match users you want to keep) and move it into the join, then use IS NULL to delete rows without joins:
DELETE USERPREF
FROM USERPREF
LEFT JOIN MOMUSER ON MOMUSER.CODE = USERPREF.CUSER
    AND MOMUSER.LOG_START >= GETDATE()-30
WHERE MOMUSER.LOG_START IS NULL

Recall that an outer join returns all nulls when the join misses. By moving the date condition into the join, you get to exercise it but not require a joined row. The where clause filters out all rows that have the kind of data you want to keep - leaving only those you want to delete.

A: Not 100% I understand your question but I think that you might be looking for a left join and check if MOMUSER.LOG IS NULL (should be null if it didn't actually join
DELETE USERPREF FROM USERPREF
LEFT JOIN MOMUSER ON MOMUSER.CODE = USERPREF.CUSER
WHERE MOMUSER.LOG_START < GETDATE()-30
OR MOMUSER.LOG_START IS NULL

A: DELETE  FROM USERPREF u
 WHERE NOT EXISTS(SELECT NULL
                    FROM MOMUSER MOMUSER
                   WHERE MOMUSER.CODE = u.CUSER AND  MOMUSER.LOG_START < GETDATE()-30)

A: This is an extension to Seth Answer but using cte.Remeber and clause in join eliminates the values before joining
with cte
    as
    (
    select
    *
    from USERPREF up
    left join
    MOMUSER  mu
    on
    mu.CODE = up.CUSER
    and MOMUSER.LOG_START >= GETDATE()-30
    where MOMUSER.LOG_START IS NULL
    )
    ---select * from cte
    delete from cte


text:
Q: Properties of OLS under non-stationary variables I estimate the following equation using OLS:
$y_{t} = a + b*x_{t} + u_t$.
I performed ADF tests for both y and x series and found that H0 (the existence of unit root) can not be rejected. I also performed ADF test for residuals $\hat{u}_t$ and got the same result. $R^2 > 0.9$ and t-stat for $\hat{b}$ is sufficiently greater than zero.
I remembered from my university courses that regressing non-stationary variables lead to spurious regression: t-stat is meaningless and no longer follows t-distribution and $\hat{b}$ is not consistent. The only exception is the case of cointegrated variables.
The question is: exactly which assumptions of Gauss-Markov theorem are violated? Why the $\hat{b}$ is not consistent? Why we can't just adjust $\hat{Var}(\hat{b})$ using standard errors in the Newey-West form to have consistent estimates of standard errors of coefficients in the case of heteroscedasticity and serial correlation?


text:
Q: Should comma be specified after "I" in case of a sentence like I myname? This question is about a confusion that I always had in my mind.
My question:
Suppose I am writing a sentence(for a speech or something like that) that actually begins like
I myname and the sentence continues.

My question is that should there be a comma after I?

A: Yes. There should be a comma after I and after your name.
"I, Christine Lopez, am standing in front of you today to discuss about......."


text:
Q: Is hashing of just "username + password" as safe as salted hashing I want to hash "user + password".
[EDIT: prehashing "user" would be an improvement, so my question is also for hashing "hash(user) + password". If cross-site same user is a problem then the hashing changed to hashing "hash(serviceName + user) + password"]
From what I read about salted hash, using "user + password" as input to hash function will help us avoid problem with reverse hash table hacking. The same thing can be said about rainbow table.
Any reason why this is not as good as salted hashing?

A: A salted hash has several advantages over the approach you mention.

*

*Salt adds uniqueness. Since it is randomly generated each time a password is created or changed, it guarantees that two identical passwords have different hashes. Using the username would sort of achieve this goal, but the salt is more effective since it changes with the password while a username normally does not change. It is stronger over time.

*Salt introduces more entropy. The number of bytes in a salt may be more or less than a username, but introduce more entropy. A salt is completely random in all eight bits per byte. A username is at best an email address with 52 letters (upper and lower case), 10 numbers, and a few punctuation. Let's say 64 characters, so 6 bits per byte (and typically less).

*Assuming the username is known, the same password would hash to the same predictable value in multiple password records. Salt is random and not tied to the login, so the same username and password combination would still result in different hashed passwords when using random salt.

Salt can be arbitrary length and contain a lot of entropy, making the hashed password more secure.
For more information, I recommend you visit the information security stack exchange site.

A: The short answer is that when it comes to security, and especially when it comes to cryptography, don't roll your own. Use vetted schemes that meet the approval of the security community in general. Your home-grown method is practically guaranteed to have flaws that you haven't thought of.
For a longer answer, read Thomas Pornin's excellent treatise on how to securely hash passwords. Most of what I'll write here is contained in that answer.
For password hashing, there are three generally-approved hashing functions: PBKDF2, bcrypt and scrypt. I won't compare them in this answer; none of these is a wrong choice. Several threads on Security Stack Exchange compare them, in particular Do any security experts recommend bcrypt for password storage? and Are there more modern password hashing methods than bcrypt and scrypt?.
Now, getting to the technical answer to your question, there are two things wrong with using e.g. SHA-256(username + password) as the password hash. The first thing is that user names are not unique. This has several implications:

*

*In particular, this makes it obvious when a user has picked the same password on different sites, which can help for some targeted attacks.

*Using a weak, predictable "salt" also facilitates non-targeted attacks that focus on the most common user names, e.g. a rainbow table with the 1000 most common user names and the 1,000,000 most common passwords has the same size as a rainbow table with the 1,000,000,000 most common passwords for unsalted hashes, and still catches quite a few weak passwords. A truly unique salt makes precomputed table useless.

The salt technically doesn't have to be random, but it needs to be unique, and using a random string is the easiest way of meeting this requirement.
For more details about salts, see Why are salted hashes more secure? and Convincing my manager to use salts. A pepper may optionally be combined with the salt — it's a good defense against some common attacks (database dump by SQL injection).
A second problem with your approach is that something like SHA-2(salt+password) is not good either. A hash function must be slow — legitimate servers only compute one authentication value, whereas attackers must make a lot of failed attempts, so slowness penalizes the attacker more. General-purpose hash functions like SHA-1 and SHA-2 are designed to be fast, they are no good for password hashing. You can turn them into a good password hash function by repeating them many times — but don't roll your own, because the devil is in the details: PBKDF2 is based on this principle.


text:
Q: SCALA: How to use collect function to get the latest modified entry from a dataframe? I have a scala dataframe with two columns:

*

*id: String

*updated: Timestamp

From this dataframe I just want to get out the latest date, for which I use the following code at the moment:
df.agg(max("updated")).head()
// returns a row

I've just read about the collect() function, which I'm told to be
  safer to use for such a problem - when it runs as a job, it appears it is not aggregating the max on the whole dataset, it looks perfectly fine when it is running in a notebook -, but I don't understand how it should
  be used.

I found an implementation like the following, but I could not figure how it should be used...
df1.agg({"x": "max"}).collect()[0]

I tried it like the following:
df.agg(max("updated")).collect()(0)

Without (0) it returns an Array, which actually looks good. So idea is, we should apply the aggregation on the whole dataset loaded in the drive, not just the partitioned version, otherwise it seems to not retrieve all the timestamps. My question now is, how is collect() actually supposed to work in such a situation?
Thanks a lot in advance!

A: I'm assuming that you are talking about a spark dataframe (not scala).
If you just want the latest date (only that column) you can do:
df.select(max("updated"))

You can see what's inside the dataframe with df.show(). Since df are immutable you need to assign the result of the select to another variable or add the show after the select().
This will return a dataframe with just one row with the max value in "updated" column.
To answer to your question:

So idea is, we should apply the aggregation on the whole dataset loaded in the drive, not just the partitioned version, otherwise it seems to not retrieve all the timestamp

When you select on a dataframe, spark will select data from the whole dataset, there is not a partitioned version and a driver version. Spark will shard your data across your cluster and all the operations that you define will be done on the entire dataset.

My question now is, how is collect() actually supposed to work in such a situation?

The collect operation is converting from a spark dataframe into an array (which is not distributed) and the array will be in the driver node, bear in mind that if your dataframe size exceed the memory available in the driver you will have an outOfMemoryError.
In this case if you do:
df.select(max("Timestamp")).collect().head

You DF (that contains only one row with one column which is your date), will be converted to a scala array. In this case is safe because the select(max()) will return just one row.
Take some time to read more about spark dataframe/rdd and the difference between transformation and action.

A: It sounds weird. First of all you don´t need to collect the dataframe to get the last element of a sorted dataframe. There are many answers to this topics:
How to get the last row from DataFrame?


text:
Q: Конвертация строки в массив Мне нужно конвертировать строку текста в массив и чтобы на консоли показывало каждый символ строки и десятичное значение этого символа. Не могу найти ошибку
public class Test {
    public static void main(String[] args) {

        String str = "Abcdefg";
        char[] cArray = str.toCharArray();

        for (char c : cArray ) {
            char myChar = str.charAt(c);
            int myInt = (int)myChar;
            System.out.println(c + myInt);
        }

    }
}

A: @Luchnik, char myChar = str.charAt(c);   это Вы зря. А вот так (почти как у Вас) работать будет
    for (char c : cArray ) {
       int myInt = c;
       System.out.println("'"+c+"'  " + myInt);
    }

'A'  65
'b'  98
'c'  99
'd'  100
'e'  101
'f'  102
'g'  103

Я немного изменил println(), чтобы вывод красивей был.


text:
Q: Output values from checkboxes via protoype/constructor i am trying to output the values from form elements , i manage to output the single values from select elements but how can i output multiple values if more than one checkbox is selected. See if anyone could help ? maybe i need to pass the checkbox values via array !
<title></title>

size : <select id = "test1">
<option>Large</option>
<option>Medium</option>
<option>small</option>

</select>

Base : <select id = "test2">
<option>Thick</option>
<option>Thin</option>
</select>

Tomato:<Input type ="checkbox">
Onion:<Input type ="checkbox">
Paprika:<Input type ="checkbox">

<input type="submit" value = "Submit" onclick ="buttonClick()" />

Code can also be viewed here : http://jsfiddle.net/bhEeZ/2/

A: This should do it: jsFiddle example
function Pizza(s, t, tops) {
    this.size = s;
    this.type = t;
    this.toppings = tops;
}
Pizza.prototype.myPizza = function() {
    document.getElementById('box').innerHTML = "This is a " + this.size + " Pizza with " + this.type + " base and the toppings include: " + this.toppings.join(', ');
};
function buttonClick() {
    x = document.getElementById('test1').value;
    y = document.getElementById('test2').value;
    z = new Array();
    var chk_arr = document.getElementsByName("topping[]");
    for (var i = 0; i < chk_arr.length; i++) {
        if (document.getElementsByName("topping[]")[i].checked) z.push(document.getElementsByName("topping[]")[i].value);
    }
    Tuesday = new Pizza(x, y, z);
    Tuesday.myPizza();
}


text:
Q: DNX SDK version 'dnx-clr-win-x86.1.0.0-preview1-002702' failed to install When I tried to open a .Net core RC2 migrated project in my local, i get the following error message
---------------------------
Microsoft Visual Studio
---------------------------
DNX SDK version 'dnx-clr-win-x86.1.0.0-preview1-002702' failed to install. The solution will use DNX SDK version 'dnx-clr-win-x86.1.0.0-rc1-update1' for this session.
---------------------------
OK
---------------------------

any ideas why the latest specified version of .Net core couldn't be installed in my local? What is it I am missing here?
How do I install the latest specified version?
Please share some light on this?

A: This error is message usually an indicator that a previous installation (.NET Core rc1 or some of the rc2 nightlies) of .NET Core Tooling/Framework wasn't uninstalled.
To validate it, go to the "Control Panel" > "Programs and features" and search for ".NET Core" or "Microsoft .NET Core" and uninstall any previous version. Then install the correct .NET Core runtime and tooling version for RC2 and it should work.


text:
Q: InstanceOf Object Inheritance Is it possible to determine whether an object is of a specific class, rather than whether an object is a parent class or that class? i.e. only return true if its that specific class, and false if it is the parent class.
For example:
class ExampleClass {
    ...
}

class ExampleClassExtension extends ExampleClass {
    ...
}

$a = new ExampleClass();
$b = new ExampleClassExtension();

var_dump($b instanceof ExampleClass) //Returns true as ExampleClassExtension is inherited from ExampleClass although I would like it to return false.

Is there any way to ignore the inheritance and check whether an object is specifically that class and return false if it is the parent class or child class or just any class that isn't the specific class I'm checking for?

A: If you want to specifically check if a class is equal to a certain class, you can use reflection
<?php

class ExampleClass {
    public const A = 'a';
}

class ExampleClassExtension extends ExampleClass {
    public const B = 'b';
}

$a = new ExampleClass();
$b = new ExampleClassExtension();

$reflectionClass = new ReflectionClass($b);
var_dump($reflectionClass->getName() === ExampleClass::class);


text:
Q: Can you get a dataUrl of an external SVG image on the same domain? Is it possible to get a dataUrl (or simply the SVG source code) of an SVG image which is not inline SVG, but an external SVG file on the same domain?
I had a look at https://github.com/sampumon/SVG.toDataURL, but it only works for inline SVG, not for external SVG files.
To be clear, I am not looking to convert the SVG image to a PNG and then get the PNG's dataUrl, I need to get at the actual SVG code.
The solution would need to be open source and work in most modern browsers.
Here's a minimal version of what I'm trying to do:
<!DOCTYPE html>

I think the obvious thing to do here is to put the SVG image on a canvas and then get a dataURL from the canvas, like this:
source = new Image();
source.src = 'myImage.svg';
source.onload = function(event){
    c = document.getElementById('canvas');
    ctx = c.getContext('2d');
    ctx.drawImage(source,0,0,116,23);
    data = c.toDataURL('image/svg', 1.0);
    alert(data);
};

But this gives me a PNG dataURL, not SVG.
I also looked at XMLSerializer, which seemed promising, but I can't work out how to get at the internal SVG. Doing this:
svgImg = document.getElementById('foo');
s = new XMLSerializer();
console.log(s.serializeToString(svgImg));

Just gives the following console output:

A: Justin Taddei gave the answer: it's fetch. I get the feeling it was dumb of me not to know this but on the other hand I bet I'm not the only one to get confused by this, so here's the code that worked:
async function getText(file) {
    let x = await fetch(file);
    let y = await x.text();
    console.log(y);
}

getText("myImage.svg");

There's info about fetch here: https://www.w3schools.com/js/js_api_fetch.asp


text:
Q: How much VRAM do I need for training a Keras model Hello I recently started my bachelor Project in which I need to train a LSTM model which has following structure
inputs (InputLayer)         [(None, None, 80)]        0
masking (Masking)           (None, None, 80)          0
lstm (LSTM)                 (None, None, 100)         72400
outputs (TimeDistributed)   (None, None, 39)          3939
=================================================================
Total params: 76,339
Trainable params: 76,339
Non-trainable params: 0
inputs = tf.keras.Input(shape=(None,nb_features), name = 'inputs')

    x = tf.keras.layers.Masking(mask_value = data.MASK_VALUE)(inputs)

    x = tf.keras.layers.LSTM(hidden_units,
                             return_sequences = True,
                             dropout = dropout_rate)(x)

    dense = tf.keras.layers.Dense(nb_skills, activation = 'sigmoid')
    outputs = tf.keras.layers.TimeDistributed(dense, name = 'outputs')(x)

Now my qeustion how much VRAM I need for training. I have a 2080ti with 11GB of VRAM inside my Station and I dont know if that is enough. Maybe there is some helpful site which calculates something like that. I try to find it myself but I dont think that something like that exists yet.
Thanks for your help

A: 11GB VRAM should be enough. I have trained a 400K+ parameter model with 3 LSTM layers that easily fits inside my 4GB VRAM. If are using GPU, you can also use Tensorboard profiling to view the memory profile of the model when you start training it. There you can see your peak VRAM usage on the GPU device.


text:
Q: Excel column number from column name How to get the column number from column name in Excel using Excel macro?

A: While you were looking for a VBA solution, this was my top result on google when looking for a formula solution, so I'll add this for anyone who came here for that like I did:
Excel formula to return the number from a column letter (From @A. Klomp's comment above), where cell A1 holds your column letter(s):

=column(indirect(A1&"1"))

As the indirect function is volatile, it recalculates whenever any cell is changed, so if you have a lot of these it could slow down your workbook. Consider another solution, such as the 'code' function, which gives you the number for an ASCII character, starting with 'A' at 65. Note that to do this you would need to check how many digits are in the column name, and alter the result depending on 'A', 'BB', or 'CCC'.
Excel formula to return the column letter from a number (From this previous question How to convert a column number (eg. 127) into an excel column (eg. AA), answered by @Ian), where A1 holds your column number:

=substitute(address(1,A1,4),"1","")

Note that both of these methods work regardless of how many letters are in the column name.
Hope this helps someone else.

A: I think you want this?
Column Name to Column Number
Sub Sample()
    ColName = "C"
    Debug.Print Range(ColName & 1).Column
End Sub

Edit: Also including the reverse of what you want
Column Number to Column Name
Sub Sample()
    ColNo = 3
    Debug.Print Split(Cells(, ColNo).Address, "$")(1)
End Sub

FOLLOW UP

Like if i have salary field at the very top lets say at cell C(1,1) now if i alter the file and shift salary column to some other place say F(1,1) then i will have to modify the code so i want the code to check for Salary and find the column number and then do rest of the operations according to that column number.

In such a case I would recommend using .FIND See this example below
Option Explicit

Sub Sample()
    Dim strSearch As String
    Dim aCell As Range

    strSearch = "Salary"

    Set aCell = Sheet1.Rows(1).Find(What:=strSearch, LookIn:=xlValues, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

    If Not aCell Is Nothing Then
        MsgBox "Value Found in Cell " & aCell.Address & _
        " and the Cell Column Number is " & aCell.Column
    End If
End Sub

SNAPSHOT

A: You could skip all this and just put your data in a table. Then refer to the table and header and it will be completely dynamic. I know this is from 3 years ago but someone may still find this useful.
Example code:
Activesheet.Range("TableName[ColumnName]").Copy

You can also use :
activesheet.listobjects("TableName[ColumnName]").Copy

You can even use this reference system in worksheet formulas as well. Its very dynamic.
Hope this helps!

A: Write and run the following code in the Immediate Window
?cells(,"type the column name here").column

For example ?cells(,"BYL").column will return 2014. The code is case-insensitive, hence you may write ?cells(,"byl").column and the output will still be the same.

A: Based on Anastasiya's answer. I think this is the shortest vba command:
Option Explicit

Sub Sample()
    Dim sColumnLetter as String
    Dim iColumnNumber as Integer

    sColumnLetter = "C"
    iColumnNumber = Columns(sColumnLetter).Column

    MsgBox "The column number is " & iColumnNumber
End Sub

Caveat: The only condition for this code to work is that a worksheet is active, because Columns is equivalent to ActiveSheet.Columns. ;)

A: Here's a pure VBA solution because Excel can hold joined cells:
Public Function GetIndexForColumn(Column As String) As Long
    Dim astrColumn()    As String
    Dim Result          As Long
    Dim i               As Integer
    Dim n               As Integer

    Column = UCase(Column)
    ReDim astrColumn(Len(Column) - 1)
    For i = 0 To (Len(Column) - 1)
        astrColumn(i) = Mid(Column, (i + 1), 1)
    Next
    n = 1
    For i = UBound(astrColumn) To 0 Step -1
        Result = (Result + ((Asc(astrColumn(i)) - 64) * n))
        n = (n * 26)
    Next
    GetIndexForColumn = Result
End Function

Basically, this function does the same as any Hex to Dec function, except that it only takes alphabetical chars (A = 1, B = 2, ...).
The rightmost char counts single, each char to the left counts 26 times the char right to it (which makes AA = 27 [1 + 26], AAA = 703 [1 + 26 + 676]).
The use of UCase() makes this function case-insensitive.

A: In my opinion the simpliest way to get column number is:
Sub Sample()
    ColName = ActiveCell.Column
    MsgBox ColName
End Sub


text:
Q: How to export string about France to Microsoft excel file? One string file Str.rc about French language is here:
ID_STR_BRIGHTNESS;,"Luminosité"
ID_STR_CHILE_EASTER_ISLAND;,"Île de Pâques"
ID_STR_CURRENT_CH;,"Saisie chaîne"
ID_STR_DETAILS;,"Détails"

......
Now I can export it to a Microsoft Str.xls like this:
cat ./Str.rc | sed 's/.*,//g' > ./Str.xls

But it will get,for example,'D茅tails' from 'Détails' in this way.
By the way,I try to get the file Str.rc encoding format via command: enca Str.rc,
and it return as following:
enca: Cannot determine (or understand) your language preferences.
Please use `-L language', or `-L none' if your language is not supported
(only a few multibyte encodings can be recognized then).
Run `enca --list languages' to get a list of supported languages.

So,what can I do for this?

A: You can probably tweak your Unix tools to handle the encoding correctly. However if you just want to strip the data before the ',' using Python:
with open('Str.xls', 'w') as ofp:
   with open('Str.rc') as fp:
       for line in fp:
           ofp.write(line.split(',',1)[1])

If you want to run that from the commandline without saving it as a file first you can cut and paste:
python -c "with open('Str.xls', 'w') as ofp:
    with open('Str.rc') as fp:
       for line in fp:
           ofp.write(line.split(',',1)[1])"


text:
Q: Equivalent of ModX chunks I'm looking for the equivalent of ModX's chunks in CMSMS. I've found Global Content but this doesn't appear to be what I want.
I want to be able to define some HTML, have it completely hidden from the end user editors that will be using the CMS to edit the site, and insert it into various templates like you can do with ModX's chunks.

A: You are looking for User Defined Tags.
They are PHP code blocks that you can use in your templates/global content blocks/content pages.


text:
Q: Compare dates of two files Python I am comparing the dates of two files in Python (If the last modification time from today to yesterdey is 24 hours) from a remote machine:
I am trying by this way:
commandcomp = 'echo `stat -c%Y /var/tmp/check_ipsleft/today.txt /var/tmp/check_ipsleft/yesterday.txt` | bc'
outputcomp = check_output(commandcomp, shell=True)

In the local machine this command works:
`echo `stat -c%Y /var/tmp/check_ipsleft/today.txt /var/tmp/check_ipsleft/yesterday.txt` | bc`

/bin/sh: -c: línea 0: EOF inesperado mientras se buscaba un ``' coincidente
/bin/sh: -c: línea 1: error sintáctico: no se esperaba el final del fichero
Traceback (most recent call last):
  File "checkipleft.py", line 46, in <module>
    outputcomp = check_output(commandcomp, shell=True)
  File "/opt/python-dsmc/lib/python2.7/subprocess.py", line 573, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'echo "stat -c%Y `/var/tmp/check_ipsleft/today.txt" - "stat /var/tmp/check_ipsleft/yesterday.txt" | bc' returned non-zero exit status 1

A: There is no need to call shell commands in order to retrieve the modification time of a file:
os.stat(filename)

provides a names tuple with all kind of metadata about the file:
os.stat_result(st_mode=33204, st_ino=33035339, st_dev=64769, st_nlink=1, st_uid=1000, st_gid=1000, st_size=589825, st_atime=1597670243, st_mtime=1597662878, st_ctime=1597670176)

As documented the st_mtime field contains the time of most recent content modification as a UNIX timestamp.
You can do any kind of calculation with this, for example:
os.stat('1.txt').st_mtime - os.stat('2.txt').st_mtime


text:
Q: New instance of a class with next.js not working I'm trying to use a js carousel (siema) in a next.js app, but can't get it to work. I get errors no matter what I try.
I have a slideshow component called HomeSlideShow.js:
import Head from "next/head";
import Siema from "../.next/static/js/siema";

const HomeSlideShow = props => (

as per the docs. Wherever I try it, it errors. Any pointers?
Thank you.

A: I think you need to convert function component into class component and try to initialize siema plugin inside componentDidMount lifycycle method as it is executed after initial render
import Head from 'next/head';
import Siema from '../.next/static/js/siema';

class HomeSlideShow extends React.component {
  componentDidMount() {
    new Siema();
  }

  render() {
    return (


text:
Q: Thumbnail style in note pages with beamer I'm making a presentation with LaTeX beamer and editing some notes about the frames.
I managed to change the background color of notes with \setbeamercolor{note page} but I still have a white background in the frame thumbnail (at the top right of the note page).
The problem is that on my presentation frames, my texts are white on a colored background :

and the thumbnails background become white in the note page in addition of  deleting the top (navigation) and bottom (title) bars. thumbnail are not readable anymore.

Is it possible to get the thumbnails showing exactly what we see on frames ?
If not, is it possible to modify the text and background colors inside the thumbnails, by modifying a LaTeX command or setting a specific beamer style (like \setbeamercolor{background canvas} for frames) ?

A: beamer uses \insertslideintonotes to insert a frame thumbnail into notes page. This command is defined in beamerbasenotes.sty file:
\newcommand{\insertslideintonotes}[1]{{%
  \begin{pgfpicture}{0cm}{0cm}{#1\paperwidth}{#1\paperheight}
    \begin{pgflowlevelscope}{\pgftransformscale{#1}}%
      \color{normal text.bg}
      \pgfpathrectangle{\pgfpointorigin}{\pgfpoint{\paperwidth}{\paperheight}}
      \pgfusepath{fill}
      \color{normal text.fg}
      {\pgftransformshift{\pgfpoint{\beamer@origlmargin}{\footheight}}\pgftext[left,bottom]{\copy\beamer@frameboxcopy}}
    \end{pgflowlevelscope}
  \end{pgfpicture}%
  }}

As you can see, it draws a background rectangle with color normal text.bg and the frame contents (stored in \beamer@frameboxcopy) is added in normal text.fg color.
Thus, you need to force normal text.bg color to be like the one used in note page. As I don't know what could be the effect of changing normal text color, another solution would be to change \insertslideintonotes definition and use the color you want as background just there. This can be done with next code:
\documentclass[notes]{beamer}
\usepackage{blindtext}

\makeatletter
\renewcommand{\insertslideintonotes}[1]{{%
  \begin{pgfpicture}{0cm}{0cm}{#1\paperwidth}{#1\paperheight}
    \begin{pgflowlevelscope}{\pgftransformscale{#1}}%
      \color{blue!40}  %<-------- Change color here
      \pgfpathrectangle{\pgfpointorigin}{\pgfpoint{\paperwidth}{\paperheight}}
      \pgfusepath{fill}
      \color{normal text.fg}
      {\pgftransformshift{\pgfpoint{\beamer@origlmargin}{\footheight}}\pgftext[left,bottom]{\copy\beamer@frameboxcopy}}
    \end{pgflowlevelscope}
  \end{pgfpicture}%
  }}
\makeatother

\setbeameroption{show notes}
\setbeamercolor{note page}{bg=red!30}
\setbeamercolor{background canvas}{bg=blue!40}
\setbeamercolor{normal text}{fg=white}

\begin{document}

\begin{frame}
   \blindtext
\end{frame}
\note[itemize]
{\item First note
\item Second note.}

\end{document}


text:
Q: Typescript/Request-Promise: Cannot invoke an expression whose type lacks a call signature I have a server endpoint that I want to either return the result of an async request or a promise rejection Promise.reject('error message'), however when I add the Promise.reject to the function instead of just returning the async request, I get this error:
Cannot invoke an expression whose type lacks a call signature. Type '{ <U>(onFulfill?: (value: any) => U | PromiseLike<U>, onReject?: (error: any) => U | PromiseLike<...' has no compatible call signatures.
I am confused because Promise.reject has a then method. Here is the code:
const funcThatReturnsPromise = (data) => {
    const validatedData = validateKeyData(data)
    if(validatedData) {
      return request.post({
        url: '/apiurl',
        json: true,
        body: validatedData
      })
    } else {
      return Promise.reject('TESTING rejected')
    }
}

const funcThatDoesWork = ((req, res) => {
    return funcThatReturnsPromise(req.body)
    .then(data => {
       if(data) {
         const theId = data.id
         const fullData = { ...req.body, theId }
       }
    })
    .catch(error => {
       console.log('ERROR', error)
       res.status(500).send({code: 'unknown', message: error})
    })
 })

A: Since RequestPromise is based on Promise<any> from Bluebird, but not identical to it, the funcThatReturnsPromise really returns the union type RequestPromise | Promise<never>, which hasn't got the required call signature for then (it has two ones, typed independently, and compiler can't call both at once).
The same problem would arise in the following simple code:
const prom = Math.random() > 0.5 ? Promise.resolve(true) : Promise.resolve(0);
// prom has a type Promise<number> | Promise<boolean>
prom.then(data => { const test = 1; }); // error: then() is ambiguous

I've found two ways to work with this:

*

*(not typesafe) Just assert the rejected promise to be Promise<any>:
const funcThatReturnsPromise = (data) => {
     const validatedData = validateKeyData(data)
     if(validatedData) {
       return request.post({
         url: '/apiurl',
         json: true,
         body: validatedData
       })
     } else {
       return Promise.reject('TESTING rejected') as Promise<any>
     }
 }

*(typesafe) Make a correct typings for both return values. It will be something like this:
const funcThatReturnsPromise = (data) => {
    const validatedData = validateKeyData(data)
    if(validatedData) {
      return request.post({
        url: '/apiurl',
        json: true,
        body: validatedData
      }) as Partial<Promise<ResultType>> & Pick<Promise<ResultType>, 'then' | 'catch'>
    } else {
      return Promise.reject('TESTING rejected') as Promise<ResultType>
    }
}

where ResultType is... well, the typeof data we are waiting for.
Note that we can't just assert request.post({...}) as Promise<ResultType>, since RequestPromise doesn't provide the full Promise API, but we can force the compiler to know that at least methods then and catch of Promise are here (and possibly something else).


text:
Q: Josephus game using java I am currently having problems with my Josephus code.
The purpose of the code is to ask a user for 3 integers and then execute.
For some sequence of numbers it works perfectly while other sequences it produces the wrong output. For example if I enter 7(size), 1(holder) 3(pass). I get the last integer as 3 when it is suppose to be 2. I am also having an issue with the size not starting at 1.
For Example if I define my size as 7, it is suppose to start at 1.2.3... but instead starts at 8.2.4..
I believe the problem lies with the deleteList method. Since I notice that when the program reaches the sequence where the list is (2,3,5,7), it does not delete properly. I can't figure why it is deleting 3 instead of 5.
       public void deleteList(int holder, int pass, int listSize){// method to determine which number gets deleted

          while(listSize!= 1){

          Link current = find(holder, listSize);

          Link previous = first;

          for(int i = 1; i < pass; i++){
             current = current.next;

          }

          previous = current;

          current = current.next;

          if(current == first){
                  first = first.next;

          }
          else{

             previous.next = current.next;

          }
          holder = current.next.iData;
          displayList(--listSize);
          }
       }


text:
Q: Div alignment issues on IE7 I have this site here http://thornwoodfinehomes.com and on the home page I have a centered gallery and this is the case in all browser except IE7. In IE7 the gallery is aligning to the right.
How do I center this in ie 7?
the div structure for the gallery goes .tn3gallery1, .tn3e-gallery, .tn3e-image1 ... below is the CSS:
.tn3gallery1 {
margin-left: -42px;
margin-top: -30px;
}

.tn3e-gallery {
position: relative;
width: 1067px;
height: auto;
line-height: normal;
}

.tn3e-image {
border: 3px solid #93928D;
position: absolute;
left: 20px;
top: 20px;
width: 1067px;
height: 450px;
background-color: #000000;
}


text:
Q: Receiving emails that my Microsoft azure student account's credits will expire even though it hasn't been 12 months I have an issue with my Microsoft azure student account's credits. I get emails claiming that the credits of my account will run out in a couple of days even though, It's been under a month since I initially signed up. As the free trial states that I have 12 months free.

A: Welcome to Stack Overflow!
If this is with regards to the Azure for Students Starter offer, you may open a Support ticket with us so our Team can assist you further. Thanks.


text:
Q: Spring Data @Query on fields The @Query on the property retrieves the values only if I retrieve the entity from the DB.
@NodeEntity
public class Team
{
    @GraphId
    private Long nodeId;

    @RelatedTo (type = "PREVIOUSLY_KNOWN_AS")
    private Team previouslyKnownAs;

    @Query ("START t=node({self}) MATCH t-[:PREVIOUSLY_KNOWN_AS]-other RETURN other")
        private Iterable<Team> aliases;
}

The below test works only if I uncomment the line to read it explicitly from the db. Why is it necessary? I see the query being run after the save(t) but the alias field is null if I doesn't read it from DB by uncommenting the line
@Test
public void alias()
{
    Team t = new Team();
    t.setName("Alpharetta One");

    Team prev = new Team();
    prev.setName("Previous Name");
    teamRepo.save(prev);

    t.setPreviouslyKnownAs(prev);
    teamRepo.save(t);

    //t = teamRepo.findOne(t.getNodeId());//only works if I uncomment
    assertNotNull(t.getAliases());
}

A: Try
 t=teamRepo.save(t);

I dont think that the save operation will update the POJO which you give to it, while the returned Object should be a managed enttiy.
The key lies in the reference documentation

The @Query annotation leverages the delegation infrastructure supported by Spring Data Neo4j.It provides dynamic fields which, when accessed, return the values selected by the provided query language expression.

Since it is a dynamic field, the value isnt instanciated but instead fetched from the DB every time the get method is called. To do this, a proxy object has to be used. However there is no way for SDN to change your t Object reference to the proxy object, and thats why its not working, if you are not using the entity returned by save().


text:
Q: XMonad Compilation Error using Incorrect Data.Map So I'm sitting here compiling XMonad for myself because I do not like being provided with version 0.9.1 by my package manager and like 0.9.2. The current problem is that the compilation of XMonad itself succeeds but then I get a weird error when xmonad tries to parse my config file:
xmonad.hs:254:15:
    Couldn't match expected type `containers-0.3.0.0:Data.Map.Map
                                    (ButtonMask, KeySym) (X ())'
           against inferred type `M.Map (KeyMask, KeySym) (X ())'
    In the `keys' field of a record
    In the first argument of `xmobar', namely
        `myBaseConfig
           {modMask = myModMask,
            workspaces = withScreens nScreens myWorkspaces,
            layoutHook = myLayoutHook nScreens, manageHook = myManageHook,
            borderWidth = myBorderWidth,
            normalBorderColor = myNormalBorderColor,
            focusedBorderColor = myFocusedBorderColor, keys = myKeys,
            mouseBindings = myMouseBindings, logHook = myLogHook}'
    In the second argument of `(=<<)', namely
        `xmobar
           (myBaseConfig
              {modMask = myModMask,
               workspaces = withScreens nScreens myWorkspaces,
               layoutHook = myLayoutHook nScreens, manageHook = myManageHook,
               borderWidth = myBorderWidth,
               normalBorderColor = myNormalBorderColor,
               focusedBorderColor = myFocusedBorderColor, keys = myKeys,
               mouseBindings = myMouseBindings, logHook = myLogHook})'

I was able to trace the cause of the problem down and it is displayed in this ghci session below:
GHCi, version 6.12.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
$ :m xmonad
syntax:  :module [+/-] [*]M1 ... [*]Mn
$ :m XMonad
$ :t XConfig
XConfig
  :: String
     -> String
     -> String
     -> l Window
     -> ManageHook
     -> (Event -> X Data.Monoid.All)
     -> [String]
     -> KeyMask
     -> KeyMask
     -> (XConfig Layout
         -> containers-0.3.0.0:Data.Map.Map (ButtonMask, KeySym) (X ()))
     -> (XConfig Layout
         -> containers-0.3.0.0:Data.Map.Map
              (ButtonMask, Button) (Window -> X ()))
     -> Dimension
     -> X ()
     -> X ()
     -> Bool
     -> XConfig l
$
Leaving GHCi.

The problem seems to be this line:
         -> containers-0.3.0.0:Data.Map.Map (ButtonMask, KeySym) (X ()))

I would have thought that it might have said:
         -> M.Map (ButtonMask, KeySym) (X ()))

I am just wondering if I diagnosed the problem correctly and if so, what can I do to fix it?

A: Looks like you might have two versions of containers installed. You can confirm this with:
$ ghc-pkg list containers
/home/dons/lib/ghc-7.0.3/package.conf.d
    containers-0.4.0.0
/home/dons/.ghc/x86_64-linux-7.0.3/package.conf.d
    containers-0.3.0.0

while that by itself is fine, the problems occur when you have some of your libraries compiled against one version, and some against another. When those libraries in turn are brought together, e.g. by xmonad, you get type errors of this sort -- the diamond dependency problem.
A solution is to remove one of the versions of containers, and recompile any libs that then break, so you have a clean toolchain.

A: You could also hide one of those packages with:
ghc-pkg hide containers-0.3.0.0


text:
Q: return two lists from a list comprehension -- performance In my program, I am getting all directories and files(walk) then write all of them to a dictionary by file names as keys and paths as values, then get a keyword from interface (tk.Entry) and return all matches to two lists. I will show them(tk.Listbox) and open the selected one(win32shell).
I used this one to create two lists with one comprehension. In the comments, it says "Just running two separate list comprehensions is simpler and probably faster though." so thats makes me confused about which one to use. Because this program will run through ~3TB data which I don't have right now so i can not run and see which will be faster.
This is my minimized code, I removed interface and defined keyword and path by keywrd, folder variables respectively.
import os
import sqlite3

audio_ext = [".mp3",".mp4","etc..."]
folder = "C:\\Users\\Lafexlos\\Music"
keywrd = "mo"  ##searching keyword which I normally get from user by Entry

conn = sqlite3.connect(":memory:")
data  = conn.cursor()
data.execute(" create table if not exists audio(path text,\
                filename text UNIQUE) ")

for roots ,dirs ,files in os.walk(folder):
    for item in os.listdir(roots):
        if "."+item.split(".")[-1].lower() in audio_ext:
        #Above line is not eye-friendly but is only checks file's extension
            data.execute(" INSERT OR IGNORE into audio \
                (path, filename) VALUES (?,?)",(roots,item))

lines = {}
musics = data.execute("select * from audio")
[lines.update({row[1]:row[0]}) for row in musics]

# This is the option 1. Using zip to create two lists
results,paths = zip(*[(k,v) for k,v in lines.items() if keywrd in k])

# This is option 2. Running same list comprehension twice
results = [k for (k,v) in lines.items() if keywrd in k]
paths = [v for (k,v) in lines.items() if keywrd in k]

print ("Results: ", results)
print ("\n\nPaths: ", paths)

As I mentioned above, my question is which one would be faster when working large amount of data?

A: Use zip():
results, paths = zip(*((k, v) for k, v in lines.items() if keywrd in k))

as this'll produce the two lists in one step. The alternative is to use one for loop:
results = []
paths = []
for (k,v) in lines.items():
    if keywrd in k:
        results.append(k)
        paths.append(v)

List comprehensions are great if you want to build one list; if you need multiple from the same loop, just use the loop.
However, since this data comes from a SQLite query, your best bet would be to have SQLite limit the rows to those that match:
data.execute("select * from audio if filename LIKE ?", ('%{}%'.format(keywrd),))

Your lines dictionary is far more efficiently built with a dictionary comprehension:
musics = data.execute("select * from audio")
lines = {row[1]: row[0] for row in musics}

or using a more specific query and a direct loop over the cursor:
data.execute("SELECT path, filename FROM audio WHERE filename LIKE ?",
             ('%{}%'.format(keywrd),))
paths, results = zip(*data)

LIKE against a string with % wildcards on both sides produces the same results an an in test in Python; if keywrd is contained in filename the row matches.
Now there is no need to create an intermediary dictionary either.

A: Faster is to use a for-loop:
results = []; add_result = result.append
paths = []; add_path = path.append
for k,v in lines.items():
    if keywrd in k:
        add_result(k)
        add_path(v)

Fastest is to use your in-memory-sqlite database to do the filtering.


text:
Q: Is there a way to force the sharepoint RSS viewer web part to get the latest 5 RSS feed items I added an RSS viewer web part to our sharepoint online site page, and i define this RSS feed url http://feeds.bbci.co.uk/news/world/rss.xml + i define to get 5 items as follow:-

now i thought that i will get the latest 5 RSS items inside the RSS Viewer web part. but when i type the RSS feed url inside my browser, i found that the 5 RSS items inside our RSS viewer web part are not actually the latest 5.. so my question is if we can force the RSS viewer web part to get the latest items (in our case the latest 5 items)? as currently i am not sure which criteria the RSS viewer web part is actually using to get the 5 RSS items in our case (as seems they are not the latest 5 and are not the 5 items sorted alphabetically )?

A: There is no way to get latest 5 RSS items in RSS viewer webpart. But from RSS feeds source should return latest feeds in XML.


text:
Q: Firebase using Node Js function notification not receiving in android but it work directly from firebase panel i am trying to implement notification in android app. i implement the code and receiving notification into my android device from Firebase panel directly. and when i trying to use node js method its not working . i am using third party web services in android device please
below code is my node js function code.
please help me i already check and search on many site but this type of problem not founded , thanks in advance
this same code i already implement in my old application and work fine but those application fully connected with firebase . but this current app i am using web services.
const functions = require('firebase-functions');
var admin = require("firebase-admin");

var serviceAccount = require("./xxxxxxx-xxxxx-firebase-adminsdk-xxxxx-xxxxxxxxxx.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://xxxxxxx-xxxxx.firebaseio.com"
});

//Notification Method
exports.sendNotification = functions.database.ref("/Notifications/{first_id}")
.onCreate((snapshot,context)=>{

     const id=context.params.first_id;
     const data2=snapshot.val()
     var token=data2.Token
     var text= data2.Name

// Send a message to the device corresponding to the provided
// registration token.

     return Promise.all([token,text]).then(results =>{

            var payload = {
                     data:{
                          username: "name",
                          usertoken: token,
                          notificationTitle: "name1",
                          notificationMessage: "ntest"
                       }
                   };

             return admin.messaging().sendToDevice(token, payload)
      })

})

<!-- Notification Services Manifest file-->
        <service
            android:name=".FCM_Serivces.MyFirebaseNotificationService" android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/> <!-- Get Notification -->
            </intent-filter>
        </service>
        <service
            android:name=".FCM_Serivces.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>  <!-- Get Token Id -->
            </intent-filter>
        </service>

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        String token = FirebaseInstanceId.getInstance().getToken();
        registerToken(token);
    }

    private void registerToken(String token) {

    }
}

//Java Class
public class MyFirebaseNotificationService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getNotification() != null) {

            SendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());

        }
    }

    private void SendNotification(String title,String msg){
        Intent intent=new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);

        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        notificationBuilder.setContentTitle(title);
        notificationBuilder.setContentText(msg);

        notificationBuilder.setAutoCancel(false);
        notificationBuilder.setSound(defaultSound);
        notificationBuilder.setContentIntent(pendingIntent);

        NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,notificationBuilder.build());

    }

}

//Gradle

    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'com.google.firebase:firebase-functions:16.1.3'

    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'org.apache.httpcomponents:httpclient:4.5.8'

//i use this code in click lister for send data with token for notification
DatabaseReference referenceNotification =FirebaseDatabase.getInstance().getReference().child("Notifications").push();
                Map<String,String> mMap=new HashMap<>();

                mMap.put("Name","01");
                mMap.put("Token", FirebaseInstanceId.getInstance().getToken());
                mMap.put("Title","Test");
                mMap.put("Message","1234");
                referenceNotification.setValue(mMap)

i receive on log this result of function
"Function execution took 501 ms, finished with status: 'ok'"

A:
The method getToken() is deprecated. You can use getInstanceId()
  instead.

For getting device token and saving it for further use:
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, instanceIdResult -> {
    String newToken = instanceIdResult.getToken();
    Log.e("newToken", newToken);
    getActivity().getPreferences(Context.MODE_PRIVATE).edit().putString("myToken", newToken).apply();
});

On saving to database:
mMap.put("Token",
getActivity().getPreferences(Context.MODE_PRIVATE).getString("myToken", "empty :("));

Now use the token send a notification using node server:
//Notification Method
exports.sendNotification = functions.database.ref("/Notifications/{first_id}")
.onCreate((snapshot,context)=>{

     const id=context.params.first_id;
     const data2=snapshot.val()
     var token=data2.Token
     var text= data2.Name

         var payload = {
                 data:{
                      username: "name",
                      usertoken: token,
                      notificationTitle: "name1",
                      notificationMessage: "ntest"
                   },
                   token: deviceRegistrationToken
               };

    admin.messaging().send(payload)
        .then(() => {
            console.log("success");
            return null;
        })
        .catch(error => {
            console.log(error);
        });

}


text:
Q: How to externalize application.properties files in Spring Boot to e.g. external dependent JAR? I have a simple Maven module (not a Spring Boot application) in which I have placed my application.properties file.
I have 6-7 Spring Boot applications and I don't want to have an application.properties file in each and every application directory. I prefer it, if it is at one single place (external Maven module).
I am adding the maven module as a dependency in each of those Spring Boot application poms.
But, when I run those applications, it is not able to auto-detect the application.properties file because it is coming from a dependent jar not present physically in each of their application directories.
Is there any way to make this possible? I would like to avoid having properties files in 6-7 different locations, because that becomes tough to manage and handle.
Thank you in advance!

A: Consider using Spring Cloud Config that provides server and client-side support for externalized configuration in a distributed system. It requires some small effort, but it is very useful in long term. Config server manages configuration files (.properties or .yml), you can still use different config per profile (e.g. application-test.properties, application-prod.properties etc.). Your application has a higher priority, so you can always override properties coming from config server if needed. Another cool feature is that config server can utilize Git repository, so you can easily version all your configuration files. It also supports encryption - any fragile data can be encrypted so only your application knows how to decrypt it.
Config server
Config server is nothing else than a simple Spring Boot application that can be implemented as:
@SpringBootApplication
@EnableConfigServer
public class ConfigServer {
  public static void main(String[] args) {
    SpringApplication.run(ConfigServer.class, args);
  }
}

with simple application.properties file included:
server.port: 8888
spring.cloud.config.server.git.uri: file://${user.home}/config-repo

with dependency in pom.xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

Config client
On client side you add a dependency to your pom.xml (or its equivalent in build.gradle if you use Gradle):
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-client</artifactId>
</dependency>

and all you have to do is add a URL to config server to your application.properties (or application.yml if you use YAML insted):
spring.cloud.config.uri: http://myconfigserver.com

Config files structure
Now let's say you have set up Git repository for your configuration files. Let's assume that your applications are named like horus, venus, mercury etc. and you have 3 different profiles: dev, test and prod. You also have some configuration that is common for all applications. In this case your configuration files structure would look like this (I will use properties files here but it applies to YAML as well):

*

*application.properties - common config for all apps no matter what profile they use

*application-dev.properties - common config for all apps running with dev profile

*application-test.properties - common config for all apps running with test profile

*application-prod.properties - common config for all apps running with prod profile

*horus.properties - horus app config for, common for all profiles

*horus-dev.properties - horus app config for dev profile only

*horus-test.properties - horus app config for test profile only

*horus-prod.properties - horus app config for prod profile only

*etc.

There are some additional options that can be set (like encryption, connection strategy (fail fast or ignore) etc.), everything is well described and documented in official documentation https://cloud.spring.io/spring-cloud-config/ Hope it helps you making a good choice for managing your configuration in distributed application environment. Config server is a solution that was invented to solve this problem.

A: While Szymon Stepniak's answer certainly is a "by-the-book" of Spring Boot answer, I understand your situation, and even tried to do what you try to do by myself. Indeed, you can't define application.properties in other "external modules".
Here is how I've solved it:

*

*Create a configuration in the "common" module

*Create a property file in src/main/resources. It shouldn't be named application properties, It's better to provide a unique name for it (at least this is how I've done it, so let's assume that the file is called application-common.properties)

*Use @PropertySources annotation to define a property file and load it with configuration.
Here is an example:
package com.myapp.common;
@Configuration
@PropertySources({
    @PropertySource("classpath:application-common.properties")
})
public class MyConfiguration {
    // you don't really have to define beans
}

Now if you want this configuration to load automatically only because the dependency is defined in your spring boot module of your build system, I've found the best to utilize spring factories:

*

*Create the file src/main/resources/META-INF/spring.factories

*Place the following into this file:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.myapp.common.MyConfiguration


text:
Q: Count the sum of a subset of the index in a pandas series I have a pandas.core.series.Series with some data, now I want to calculate the sum of the index 0 to 13. How would I do that?
This is what tried so far:
#preg.prglngth.value_counts().sort_index()

prglnght_var = preg['prglngth']
prglnght_var.ser[:14]

The series data looks like this:
0       15
1        9
....
47       1
48       7
50       2
Name: prglngth, dtype: int64

A: You can try:
prglnght_var.loc[:14].sum()

.loc is a method of the series class.
It selects the rows or columns (the rows, in this case) for the criteria you choose (in this case, all lines from 0 to 13)
It returns a series
.sum is a method of a series that will sum all values in it.
As the series is already filtered for the lines you want, it will sum all values that you want.