text:
Q: XText generate unambigious grammar I have create xtext grammar and have warnings(see it bellow) I understand that XText have generated ambigious ANTLR grammar, but don't understand why.
So, what is wrong in my grammar?
Regards,
Vladimir
grammar com.idc.net.Validator with org.eclipse.xtext.common.Terminals

generate validator "http://www.idc.com/net/Validator"

Model:
    netDescriptions+=NetDescription+;

NetDescription:
    descriptionPairs+=DescriptionPair+;

DescriptionPair:
    IPADDR | NETMASK | SPEED | MTU | TSO | GATEWAY | VLAN | ROUTER | SUBNET | NO_VLANS | VLAN;
//List of numbers with 3 digit
 VLAN:
    'VLAN_' name=ID '='
    value=IntList;

IntList:
    valueList+=INT+ | '"' valueList+=INT+ '"';

IPAddrList:
    ipNum1=INT '.' ipNum2=INT '.' ipNum3=INT '.' ipNum4=INT;

//List of numbers with 3 digit
 NO_VLANS:
    'NO_VLANS_' name=ID '=' list+=IntList;

SUBNET:
    'SUBNET_' name=ID '=' list+=IPWithQuotes;

ROUTER:
    'ROUTER_' name=ID '=' list+=IPWithQuotes;

GATEWAY:
    'GATEWAY_' name=ID '=' list+=IPWithQuotes;

MTU:
    'MTU_' name=ID '=' val=IntWithQuotes;

TSO:
    'TSO_' name=ID '=' '"' value=ON_OFF '"';

ON_OFF:
    'on' | 'off';

NETMASK:
    'NETMASK_' name=ID '=' list+=IPWithQuotes;

SPEED:
    'SPEED_' name=ID '=' value=IntWithQuotes;

IPADDR:
    'IPADDR_' name=ID '=' list+=IPWithQuotes;

IPWithQuotes:
    IPAddrList | '"' IPAddrList '"';

IntWithQuotes:
    value=INT | '"' value=INT '

"';
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:132:2: Decision can match input such as "'SPEED_'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:132:2: Decision can match input such as "'GATEWAY_'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:132:2: Decision can match input such as "'VLAN_'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:132:2: Decision can match input such as "'IPADDR_'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:132:2: Decision can match input such as "'MTU_'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:132:2: Decision can match input such as "'TSO_'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:132:2: Decision can match input such as "'NO_VLANS_'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:132:2: Decision can match input such as "'NETMASK_'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:132:2: Decision can match input such as "'ROUTER_'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:132:2: Decision can match input such as "'SUBNET_'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:150:2: Decision can match input such as "'VLAN_' RULE_ID '=' RULE_INT" using multiple alternatives: 7, 11
As a result, alternative(s) 11 were disabled for that input
warning(200): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:150:2: Decision can match input such as "'VLAN_' RULE_ID '=' '"' RULE_INT '"'" using multiple alternatives: 7, 11
As a result, alternative(s) 11 were disabled for that input
error(201): ../com.idc.net.validator/src-gen/com/idc/net/parser/antlr/internal/InternalValidator.g:150:2: The following alternatives can never be matched: 11

A: there are two problems
first VLAN is twice in the list. so it should be
DescriptionPair:
    IPADDR | NETMASK | SPEED | MTU | TSO | GATEWAY | VLAN | ROUTER | SUBNET | NO_VLANS;

then you have a list of lists problem here
Model:
    netDescriptions+=NetDescription+;

NetDescription:
    descriptionPairs+=DescriptionPair+;

that should be either
Model:
    netDescriptions=NetDescription;

NetDescription:
    descriptionPairs+=DescriptionPair+;

or
Model:
    netDescriptions+=NetDescription+;

NetDescription:
    descriptionPairs=DescriptionPair;


text:
Q: How to set FormsAuthentication in asp.net mvc 3 with Entity Framework mapper? I'm trying to set authentication username and password manually in web.config file in my mvc 3 app:
<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
  <credentials passwordFormat="Clear">
    <user name="admin" password="secret" />
  </credentials>
</authentication>

And the following warning occures:
Warning 1   The element 'authentication' has invalid child element 'credentials'. List of possible elements expected: 'forms, passport'.    C:\Users\Aleksey\documents\visual studio 2012\Projects\SportStore\SportStore.WebUI\Web.config   20  8   SportStore.WebUI
I also tried to use aspnet_regsql.exe tool, but I use Entity Framework mapper, so my database has (.sdf) extension (SQL Server Compact Edition Database File) which is not supported. I tried to add Microsoft.AspNet.Providers.SqlCE via nuget package manager. 4 default providers adn new connection string have appeared in web.config file. I changed connection strings of providers to "EfDbContext" (class that inherits from DbContext), nothing's work.
I'm new to authentication.  Mabby You know some useful source where "how to use EF in authentication" is descibed in detail?
Thank You in advance.

A: It should be
<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880">
  <credentials passwordFormat="Clear">
    <user name="admin" password="secret" />
  </credentials>
  </forms>
</authentication>

redpajama_set_name: RedPajamaStackExchange


text:
Q: SharePoint 2013 Search Service Application I have built a SharePoint 2013 environment and everything was successfully setup. Then I had to disconnect the SharePoint 2013 server from the Farm, then I reconnected it to the farm again using the SharePoint 2013 products configuration wizard, then I re-run the AutoSPInstaller script I used to install SharePoint 2013 originally and this time the search service application was not successfully  provisioned (already provisioned during initial install via AutoSPInstaller).
In search service application search administration page, I get the following message under "Search Application Topology":
"Unable to retrieve topology component health states. This may be because the admin component is not up and running"
Has anyone come across this issue before? how was it resolved?
I have installed the required/additional hotfixes: KB2472264, KB2554876, KB2708075, KB2765317...
Would deleting the Search Service Application and the database (data) associated with it via central admin, then running the AutoSPInstaller script again fix this issue? has anybody tries this method?
Any suggestions would be greatly appreciated... I am tearing my hair out at this minute...
Thanks in advance

A: After much researching on the internet, the one thing that resolved this issue was to delete the search service application via central admin altogether and then re-provisioning it again. In my occasion this was provisioned via "AutoSPInstaller" which did the trick and resolved the message:
"Unable to retrieve topology component health states. This may be because the admin component is not up and running"

A: 1.Remove corrupt search service applications:
http://pointsforsharing.com/Lists/Posts/Post.aspx?ID=5
2.Run powershell script:
$hostA = Get-SPEnterpriseSearchServiceInstance -Identity "YourServerName"
Start-SPEnterpriseSearchServiceInstance -Identity $hostA
$UP = Get-SPServiceApplicationProxy | where {$_.TypeName -like "Usage*"}
$UP.Provision()
Get-SPEnterpriseSearchServiceInstance –Identity $hostA
$hostA

A: I've gotten this working by installing these updates BEFORE INSTALLING SHAREPOINT. If I install these updates after installing SharePoint, I don't have much luck with this..


text:
Q: R seq: what is the exact value? Are there limitations to seq? I can not explain this:
x=seq(from=.008, to=.015, by=.001)
x
[1] 0.008 0.009 0.010 0.011 0.012 0.013 0.014 0.015
x[2]
[1] 0.009
x[x==0.009]
numeric(0)
x[x==.01]
[1] 0.01

What is the exact value of x[2]?
To my surprise:
(.008+.001)==.009
[1] FALSE
(.08+.01)==.09
[1] TRUE

How does R sum 0.008+.001 and what is the exact value?
As @joran pointed out, the question has already been answered.
In this case, the easiest solution is
x[round(x,3)==.009]
[1] 0.009
round(.008+.001,3)==.009
[1] TRUE


text:
Q: Is it possible to create Realm class without default values for parameters? I understand that this is not possible with Kotlin because Realm needs an empty constructor.
However, this creates an issue that we may accidentally create a RealmObject without setting all the required fields. Hence, the purpose of required fields is lost.
I was wondering if someone has found a way around this Realm limitation.


text:
Q: Get the record with the max value in nested dictionnaries I want to write a function that examines a dictionary and returns two keys ("name" and "cost") for the record with the maximum cost in "food":
[{'age': 'Dark',
  'armor': '0/1',
  'attack': 4,
  'build_time': 21,
  'cost': {'Food': 60, 'Gold': 20},
  'created_in': 'https://age-of-empires-2-api.herokuapp.com/api/v1/structure/barracks',
  'description': 'Basic infantry swordsman. Quick and cheap to create',
  'expansion': 'Age of Kings',
  'hit_points': 40,
  'id': 15,
  'line_of_sight': 4,
  'movement_rate': 0.9,
  'name': 'Militia',
  'reload_time': 2.0},
 {'age': 'Dark',
  'armor': '0/0',
  'build_time': 30,
  'cost': {'Food': 50},
  'created_in': 'https://age-of-empires-2-api.herokuapp.com/api/v1/structure/castle',
  'description': 'Cannot be produced so the cost and build time just for the sake of interest',
  'expansion': 'Age of Kings',
  'hit_points': 75,
  'id': 20,
  'line_of_sight': 6,
  'movement_rate': 1.32,
  'name': 'King'}]

Here it would be militia and ({'Food': 60, 'Gold': 20})
So I tried
def filter_by_age(filtered_data, age):
  return sorted(filtered_data, key=filtered_data['cost']['food].get, reverse=True)[:1]['name', 'cost']

But I got:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-262726f1a4ab> in <module>()
      1 def filter_by_age(filtered_data):
      2     return sorted(filtered_data, key=filtered_data['cost']['food'].get, reverse=True)[:1]['name', 'cost']
----> 3 filter_by_age(filter_by_age(data, 'Dark'))

TypeError: filter_by_age() takes 1 positional argument but 2 were given

A: You can use max with key. seq is your input list.
res = max(seq, key=lambda x:x['cost']['Food'])
print(res['name'], res['cost'])

Output
Militia {'Food': 60, 'Gold': 20}


text:
Q: Vue Router works fine in development, but doesn't match routes in production I have a Vue SPA that's being served by an ASP Core API. When I run it in development mode, everything works perfectly. But as soon as I deploy it to production (on an Azure App Service), I always get a blank page.
It seems to be specifically the router that can't match the routes, as I can put some arbitrary HTML into my App.vue, and that will render.
If I go into the developer tools, I can see that the index.html and all .js files download successfully and there are no errors in the console. This is true no matter what URL I visit e.g. myapp.com and myapp.com/login, both download everything but nothing displays on screen.
I have seen several posts saying to change the routing mode to hash, but I still get the same result with that.
Please see below my files:
main.ts
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import vuetify from './plugins/vuetify';
import { LOGIN_INITIALISE } from './use-cases/user-auth/AuthModule';

Vue.config.productionTip = false;

store.dispatch(LOGIN_INITIALISE)
  .then(() => {
    new Vue({
      router,
      store,
      vuetify,
      render: (h) => h(App),
    }).$mount('#app');
  });

App.vue
<template>

test

    <router-view></router-view>

</template>

router/index.ts
import Vue from 'vue';
import {} from 'vuex';
import VueRouter, { RouteConfig } from 'vue-router';
import store from '@/store';
import {
  HOME,
  LOGIN,
  SIGNUP,
  USERS,
} from './route-names';

Vue.use(VueRouter);

const routes: Array<RouteConfig> = [
  {
    path: '/',
    name: HOME,
    component: () => import('@/views/Home.vue'),
  },
  {
    path: '/login',
    name: LOGIN,
    component: () => import('@/views/Login.vue'),
  },
  {
    path: '/signup',
    name: SIGNUP,
    component: () => import('@/views/SignUp.vue'),
  },
  {
    path: '/users',
    name: USERS,
    component: () => import('@/views/Users.vue'),
    beforeEnter: (to, from, next) => {
      if (store.getters.userRole === 'Admin') {
        next();
      } else {
        next({ name: HOME });
      }
    },
  },
  {
    path: '*',
    name: '404',
    component: {
      template: '404 Not Found',
    },
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach((to, from, next) => {
  if (store.getters.isAuthenticated) {
    next();
  } else if (to.name === LOGIN || to.name === SIGNUP) {
    next();
  } else {
    next({ name: LOGIN });
  }
});

export default router;

A: Finally after completely rebuilding my router piece by piece, I found the issue. I found that the problem was in this global route guard:
router.beforeEach((to, from, next) => {
  if (store.getters.isAuthenticated) {
    next();
  } else if (to.name === LOGIN || to.name === SIGNUP) {
    next();
  } else {
    next({ name: LOGIN });
  }
});

Specifically, the isAuthenticated getter was throwing an error (silently), so all of the routes were failing before they could render. I wrapped my isAuthenticated logic in a try-catch that returns false if an error is thrown, and now everything works fine.
I still don't understand why this only affects the production build, but hopefully this experience will be useful to others stuck in the same situation.


text:
Q: internet connection problems with the iphone 3 i have had an iphone 3 for a year. no problems! i recently updated my iphone to ios 6, it was fine for a day, and then suddenly, my facebook, instagram and whatsapp/kik stopped working, i was still able to access twitter and snapchap though. Why isn't my iphone allowing me to access certain internet based apps? it simply won't load. please help!

A: I've had this issue on my iPhone too after update to iOS6, I had to reset the network settings. This will clear all remembered WIFI networks and force you to connect to them again, creating new network settings. This means you will have to manually connect to your WIFI network again, and if required enter its password afterwards.
You can reset the network settings by selecting:
Settings -> General -> Reset -> Reset Network Settings
Also what can help is trying to clear the history of your Safari browser, you can do that by going to the Bookmarks -> History and then press the Clear button on the lower left hand corner of the screen.


text:
Q: /ɪə/ diphthong in modern speech I'm working on my pronunciation with a teacher from England. So, learning the British accent.
In the last lesson we were discussing /ɪə/ diphthong. She says that nowadays it should be pronounced as /i:ə/ rather than /ɪə/. I did some research and couldn't really find anything that confirms it. But, I found that in fact /ɪə/ shifted towards /ɪː/. Similarly to /eə/ → /ɛː/. Also, this seems to support it.
Is my teacher being wrong? What option should I use to not sound old-fashioned? Is it common to use /ɪː/ instead of /ɪə/?
Thanks in advance!


text:
Q: The formal parameter ""@response"" was not declared as an OUTPUT parameter, but the actual parameter passed in requested output Yes, I have seen this question.  No, it has not solved my problems.
I am working on an application in VB.Net that interfaces with an SQL Server Database.  Currently I am trying to have the VB.Net app Execute the following Stored Procedure on the Database:
CREATE PROCEDURE dbo.AddSupplierAddress(
    @Supplier VARCHAR(100),
    @Street   VARCHAR(100),
    @City     VARCHAR(50),
    @Region   VARCHAR(50),
    @Code     VARCHAR(7),
    @Info     VARCHAR(500) = NULL,
    @response NVARCHAR(500) = OUTPUT
) AS
BEGIN
    DECLARE @SupplierID INT, @RegionID INT
    SELECT @SupplierID = supplier_id
      FROM suppliers
     WHERE supplier_name = @Supplier
    IF @SupplierID IS NULL
    BEGIN
        SET @response = 'Could not add address to Supplier "' + @Supplier + '".  Supplier does not exist.'
        RETURN
    END
    SELECT @RegionID = region_id
      FROM regions
     WHERE region_name = @Region
    IF @RegionID IS NULL
    BEGIN
        SET @response = 'Could not add address to Supplier "' + @Supplier + '". Region "' + @Region + '" does not exist.'
        RETURN
    END
    IF(EXISTS(SELECT supplier_id, street FROM supplier_addresses WHERE supplier_id = @SupplierID AND street = @Street))
    BEGIN
        SET @response = 'Could not add address to Supplier "' + @Supplier + '".  Address already exists in database.'
        RETURN
    END
    BEGIN TRANSACTION AddSuppAddr
    BEGIN TRY
        INSERT supplier_addresses(supplier_id, street, city, region_id, zip_code, notes)
        VALUES (@SupplierID, @Street, @City, @RegionID, @Code, @Info)
        COMMIT TRANSACTION AddSuppAddr
        SET @response = 'Success'
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION AddSuppAddr
        DECLARE @varErrorMessage NVARCHAR(4000), @varErrorSeverity INT, @varErrorState INT;
        SELECT @varErrorMessage = ERROR_MESSAGE(), @varErrorSeverity = ERROR_SEVERITY(), @varErrorState = ERROR_STATE();
        RAISERROR(@varErrorMessage, @varErrorSeverity, @varErrorState);
    END CATCH
END
GO

Now I have run this Procedure on the database itself using the following:
DECLARE @Resp NVARCHAR(500)
EXEC AddSupplierAddress 'Test Name', '123 main st.', 'Hamilton', 'Ontario', 'L84B5N', NULL, @Resp
PRINT @Resp

The procedure works fine.  (One small issue I am having is that @Resp never gets set to my output value when testing these procedures on the database, but that is a different problem that I am not trying to solve here).  In my VB.Net program I am trying to run this procedure using the following code:
Private Sub CreateBtn_Click(sender As Object, e As EventArgs) Handles createBtn.Click
    If CreateSupplier(supplierTxt.Text, websiteTxt.Text, True) Then
        Dim message As String = ""
        If setAddress Then
            If AddSupplierAddress(supplierTxt.Text, streetTxt.Text, cityTxt.Text, regionTxt.Text, codeTxt.Text, infoTxt.Text, True) Then
                message = "Supplier and address have been added to the database."
            Else
                DeleteSupplier(supplierTxt.Text)
                Return
            End If
        Else
            message = "Supplier has been added to the database."
        End If
        If MessageBox.Show(message & vbCrLf & "Would you like to add any Contacts?", "Data Added", MessageBoxButtons.YesNo) = DialogResult.Yes Then
            Dim contact As New NewContactForm(supplierTxt.Text, False, True) With {
                .MdiParent = MdiParent
            }
            contact.Show()
        End If
    End If
End Sub

Public Function AddSupplierAddress(ByVal supplier As String,
                                   ByVal street As String,
                                   ByVal city As String,
                                   ByVal region As String,
                                   ByVal code As String,
                                   Optional info As String = "",
                                   Optional displayError As Boolean = False) As Boolean
    Dim errorMsg As String = ""
    Dim CMD As New SqlCommand("AddSupplierAddress")
    CMD.Parameters.Add("@Supplier", SqlDbType.VarChar).Value = supplier
    CMD.Parameters.Add("@Street", SqlDbType.VarChar).Value = street
    CMD.Parameters.Add("@City", SqlDbType.VarChar).Value = city
    CMD.Parameters.Add("@Region", SqlDbType.VarChar).Value = region
    CMD.Parameters.Add("@Code", SqlDbType.VarChar).Value = code
    If Not info.Equals("") Then CMD.Parameters.Add("@Info", SqlDbType.VarChar).Value = info
    If ExecuteCMDWithReturnValue(CMD, errorMsg) Then
        Return True
    Else
        If displayError Then
            MessageBox.Show(errorMsg, "Database Error")
            Return False
        Else
            Return False
        End If
    End If
End Function

Public Function ExecuteCMDWithReturnValue(ByRef CMD As SqlCommand, ByRef errorMessage As String) As Boolean
    Try
        OpenDBConnection()
        CMD.Parameters.Add("@response", SqlDbType.NVarChar, 500).Direction = ParameterDirection.Output
        CMD.Connection = DB_CONNECTION
        CMD.CommandType = CommandType.StoredProcedure
        CMD.ExecuteNonQuery()
        Dim result As String = CMD.Parameters("@response").Value
        If result.Equals("Success") Then
            ExecuteCMDWithReturnValue = True
        Else
            errorMessage = result
            ExecuteCMDWithReturnValue = False
        End If
    Catch ex As Exception
        Throw New Exception("Database Error: " & ex.Message)
        ExecuteCMDWithReturnValue = False
    Finally
        CloseDBConnection()
    End Try
End Function

Now as I said above, I am not getting this error when I run the Stored Procedure on the Database.  What is even weirder is I have another setup of procedures that are coded the exact same, with the only difference being every instance of supplier is replaced with customer and they all work fine!
The specific error I am getting is in the title, but so you don't have to scroll up its:

The formal parameter ""@response"" was not declared as an OUTPUT parameter, but the actual parameter passed in requested output.

What could be causing my problem?

A: Congratulations, you ran into a nasty T-SQL gotcha. It "allows" string parameter defaults to be specified without quotes, so that
@response NVARCHAR(500) = OUTPUT

Is actually equivalent to
@response NVARCHAR(500) = 'OUTPUT'

Which is of course not the same thing as declaring the parameter as an output parameter, since that's
@response NVARCHAR(500) OUTPUT

This is especially bad because the default values allow only constants -- not functions or expressions -- and yet the quotes being optional allows for some really misleading declarations:
@from DATETIME = GETDATE

This will fail only when the procedure is called without specifying a value for @from: at that point the string 'GETDATE' will be converted to DATETIME (which, of course, fails).


text:
Q: Get header info from php://input I have a file(image) from  device that is send via put
PUT /r.php HTTP/1.1
User-Agent: PHS/2.0.6
Host: localhost
Accept: */*
Content-Name: cam20141020084031.jpg,10001019
Content-Length: 35183
Expect: 100-continue

This is how I get picture that was send:
$res = file_get_contents("php://input");

$file = fopen('1.jpg', "w");
fputs($file, $res);
fclose($file);

I need to get content-name separately too. I can't find anywhere how can I get it. Can anyone help?
UPDATE
$res = file_get_contents("php://input");
$vars=parse_str($res,$post_vars);
$headers = getallheaders();
$contentName=$headers['Content-Name'])
$file = fopen('1.jpg', "w");
$fileVar= fopen('1.txt', "w");
fputs($file, $res);
fputs($fileVar,$res);
fclose($fileVar);
fclose($file);

Strange, but this code seems to be loading forever.
UPDATE 1
When I print_r it I understand that it's not headers of put request it's headers of page. Not what I need.

A: You can try using getallheaders() function, which exists for sole purpose of retrieving request headers:
$headers = getallheaders();
var_dump($headers['Content-Name']);

Note that it might be best to preprocess keys to take care of headers such as Content-name (note the change of letter case near -).


text:
Q: Neo4j Traversal API limitation? we are trying to use the Traversal API to retrieve, for a given set of company nodes, only the company nodes that provide all the products that are contained in the product Nodes list. Prior attempts at using Cypher were not performing well. In this example:
Company 1 provides product A and B
Company 2 provides product A and B and C
Company 3 provides product A and C

If all 3 companies are included in company list query, and product A and C are in product list in query, we would want returned only Company 2 and 3 since they provide product A and C. Here is our query:
for ( Path position : Traversal.description()
.depthFirst()
.uniqueness(Uniqueness.NODE_GLOBAL)
.relationships(Rels.PROVIDES_PRODUCT, Direction.OUTGOING)
.evaluator((Evaluator) Evaluators.includeWhereEndNodeIs(productNodes))
.traverse(companyNodes))

If we use the Evaluator.includeWhereEndNodeIs(productNodes) we get back all the companies that provide ANY of the products in the productNodes list(all 3 companies in above example). If we use the Evaluators.includeIfContainsAll(productNodes) evaluator, we don't get any company nodes back if there is more than one product in the product nodes list.
Any suggestions appreciated.

A: I'm not sure if it's possible in one statement, but you could nest them. Company2 and Company3 will be returned in the following case:
for (final Path position : Traversal
            .description()
            .depthFirst()
            .uniqueness(Uniqueness.RELATIONSHIP_LEVEL)
            .relationships(RelType.PROVIDES_PRODUCT, Direction.OUTGOING)
            .evaluator(
                    (Evaluator) Evaluators.endNodeIs(Evaluation.INCLUDE_AND_CONTINUE, Evaluation.EXCLUDE_AND_CONTINUE,
                            productA)).traverse(company1, company2, company3)) {
        for (final Path position2 : Traversal
                .description()
                .depthFirst()
                .uniqueness(Uniqueness.RELATIONSHIP_LEVEL)
                .relationships(RelType.PROVIDES_PRODUCT, Direction.OUTGOING)
                .evaluator(
                        (Evaluator) Evaluators.endNodeIs(Evaluation.INCLUDE_AND_CONTINUE, Evaluation.EXCLUDE_AND_CONTINUE,
                                productC)).traverse(position.startNode())) {
            System.out.println(position2.startNode());
        }
}

A: Are the (company)-[:PROVIDES_PRODUCT]->(product) only one level always? In that case it would be fine with a simple loop like this:

Set<Node> companies = new HashSet<Node>( asList( companyNodes ) );
for ( Node product : productNodes )
{
    Set<Node> companiesForThisProduct = new HashSet<Node>();
    for ( Relationship rel : product.getRelationships( PROVIDES_PRODUCT, INCOMING ) )
        companiesForThisProduct.add( rel.getStartNode() );
    companies.retainAll( companiesForThisProduct );
}

I quickly hacked up your example with your dataset and it works fine.


text:
Q: Echo JSON response with PHP I am trying to echo a portion of my JSON response from the Plaid API.
Here is the code:
$data = array(
            "client_id"=>"test_id",
            "secret"=>"test_secret",
            "public_token"=>"test,fidelity,connected");
        $string = http_build_query($data);

    //initialize session
    $ch=curl_init("https://tartan.plaid.com/exchange_token");

    //set options
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //execute session
    $exchangeToken = curl_exec($ch);
    echo $exchangeToken;
    $exchangeT = json_decode($exchangeToken);
    echo $exchangeT['access_token'];
    //close session
    curl_close($ch);

Here is the response:
{ "sandbox": true, "access_token": "test_fidelity" }

I also get a 500 Internal Server Error, which results from the echo $exchangeT line.  I want to take the access_token portion of the JSON response, echo it to verify, and eventually save it to a database.

A: If you pass true as second parameter in your json_decode then you will get an array instead of object
 so
change this
     $exchangeT = json_decode($exchangeToken, true);
// it wii output as $exchangeT = array('sandbox'=>true,'access_token'=>'test_fidelity');
        echo $exchangeT['access_token'];

for more info read http://php.net/manual/en/function.json-decode.php

A: *

*json_decode Manual
And the function signature:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

From the function definition, you can see that the second argument $assoc is by default false. What this argument does (and it's name suggests), is that when TRUE, returned objects will be converted into associative arrays.
So, in your case,
$exchangeToken = json_decode($exchangeToken, true);

should do what you need.

A: just pass true as second parameter, json_decode() returns in array format instead of object if second parameter is true.
 $exchangeT = json_decode($exchangeToken, true);


text:
Q: Display of box widget on site i'm using box-widget on my site and my problem is the following: Widget is displayed incorrectly after full page download. If i start working with it during loading everything is fine and it is fully functional after page load. But if i wait for full loading then widget shows message than area of widget is small. (In fact area is bigger then 330x400)
Now widget is available at http://sp-hosting.nichost.ru/pi/index.php/reestr (on the third tab  named ФАЙЛЫ)

A: The width doesn't accept a %.  So when you send in 100%, I believe that looks like a request for a 100 pixel wide control, which is really too narrow for us to support.  You have to specify # of pixels you want the width to be.


text:
Q: Setting the ping interval on the SignalR .NET Client I've set up a signalr API endpoint (WS only) with the following configuration:
                .AddHubOptions<MyHub>(options =>
                {
                    options.ClientTimeoutInterval = TimeSpan.FromSeconds(120);
                    options.KeepAliveInterval = TimeSpan.FromSeconds(60);
                })

Now, the .net client application pings the endpoint every ~15 seconds and gets closed after few tries.
How to configure the .net client to ping the server every 60 seconds?
I've checked the following code, but it didn't help:
                .WithUrl("signalrendpointaddress", options =>
                {
                    options.CloseTimeout = TimeSpan.FromSeconds(120);
                    options.WebSocketConfiguration = (configuration) => { configuration.KeepAliveInterval = TimeSpan.FromSeconds(60); };
                })

A: If you want to change KeepAliveInterval to 60 seconds,you need to change serverTimeoutInMilliseconds.
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.serverTimeoutInMilliseconds = 2 * 60 * 1000;

serverTimeoutInMilliseconds:

The server timeout in milliseconds. If this timeout elapses without receiving any messages from the server, the connection will be terminated with an error. The default timeout value is 30,000 milliseconds (30 seconds).

For more details,you can refer to the official doc.


text: Q: Connect IPv4-only devices to IPv6-only services and vice versa I have mobile devices (Android), whose network providers do not support IPv6. My fiber network provider (for internet connection at home) uses only IPv6 with Dual Stack lite, so they are only reachable via IPv6. I have a couple services running at home (HTTP/HTTPS/Email-Server via POP3&SMTP/and soon applications developed by myself) (on Raspbian/Debian) which i need to be able to connect to from every network (IPv4). I have a VPS (Debian 9) with full Dual Stack access with an option to rent an entire /64 IPv6-Subnet. How can i make my home services (IPv6 only) available to the entire web (using the static IPv4 and IPv6 address of the VPS) and also provide my Android devices with IPv6?


text:
Q: Add n elements numpy array I have a numpy array and I want to add n elements with the same value until the length of the array reaches 100.
For example
my_array = numpy.array([3, 4, 5])

Note that I do not know the length of the array beforehand. It may be anything 3 <= x <= 100
I want to add (100 - x) more elements, all with the value 9.
How can I do it?

A: There are two ways to approach this: concatenating arrays or assigning them.
You can use np.concatenate and generate an appropriately sized array:
my_array = # as you defined it
remainder = [9] * (100 - len(my_array))
remainder = np.array(remainder)
a100 = np.concatenate((my_array, remainder))

Alternatively, you can construct a np.full array, and then overwrite some of the values using slice notation:
a100 = numpy.full(100, 9)
my_array = # as you defined it
a100[0:len(my_array)] = my_array

A: It's important to remember with numpy arrays, you can't add elements like you can with lists.  So adding numbers to an array is not really the best thing to do.
Far better is to start with an array, and replace the elements with new data as it comes in.  For example:
import numpy as np
MY_SPECIAL_NUMBER = 100
my_array = np.array[3, 4, 5]
my_new_array = np.ones(100) * MY_SPECIAL_NUMBER
my_new_array[:my_array.size] = my_array

my_new_array is now what you want.

A: If you "cannot" know the size of your mysterious array:
fillvalue=9
padding=numpy.ones(100)*fillvalue
newarray=numpy.append(myarray, padding)
newarray=newarray[:100]


text:
Q: Verifying the Gaussian Transformation of $exp\left\{\frac{1}{2}\sum_{i,j} S_i J_{ij} S_j\right\}$ from "Advanced Mean Field Methods" The book Advanced Mean Field Methods mentions the following equation as a result of a "simple gaussian transformation".
$$
exp\left\{\frac{1}{2}\cdot\textbf{s}^T \cdot \textbf{J} \cdot\textbf{s}\right\} = \frac{1}{(2\pi)^{N/2}\sqrt{det(J)}} \int_{-\infty}^\infty \prod_i dx_i \exp\left\{-\frac{1}{2}\sum_{ij}x_i(\textbf{J}^{-1})_{ij}x_j + \sum_ix_iS_i\right\}
$$
It is assumed that $\textbf{J}$ is positive definite. I would like to derive this for myself as I try to with all the expression I come across. Looking at the right-hand side, it is very similar to a multivariate normal distribution with $\mu = \textbf{s}$ and $\Sigma=\textbf{J}$
$$\frac{1}{(2\pi)^{N/2}\sqrt{det(J)}} \exp\left\{-\frac{1}{2}(\textbf{x}-\textbf{s})^T\textbf{J}^{-1}(\textbf{x}-\textbf{s})\right\}$$
$$
= \frac{1}{(2\pi)^{N/2}\sqrt{det(J)}} \exp\left\{-\frac{1}{2}\left(\textbf{x}^T\textbf{J}^{-1}\textbf{x} + \textbf{s}^T\textbf{J}^{-1}\textbf{s}\right) +\textbf{x}^T\textbf{J}^{-1}\textbf{s}\right\}.
$$
We are missing some terms and gaining some extra terms. Here, I don't know how to proceed, or if I am on the right track. I would like to take the expectation of some $g(\textbf{x}) =e^{f(\textbf{x} ; \textbf{s})}$ with respect to the multivariate normal above to cancel the extra terms and add the missing ones. However, my attempts at solving for such an $g$ does not lead to an easily interpretable one nor give reason to think we would have equality. I feel I am not taking the right approach.
I would greatly appreciate ideas and insights. Thank you.

A: Let's consider the argument of the exponential on the R.H.S.:
$$
-\frac{1}{2} \bf{x}^T \bf{J}^{-1} \bf{x} + \bf{x}^T\cdot \bf{s}
$$
the trick is to add and subtract here a suitable quantity to complete the square. The correct choice (suggested by the solution you have) is clearly
$$
\frac{1}{2}\bf{s}^T \bf{J} \bf{s}.
$$
After this your exponent reads:
$$
\left(-\frac{1}{2} \bf{x}^T \bf{J}^{-1} \bf{x} + \bf{x}^T\cdot \bf{s} - \frac{1}{2}\bf{s}^T \bf{J} \bf{s} \right) + \frac{1}{2}\bf{s}^T \bf{J} \bf{s}
$$
Now the term in brackets can be written as a quadratic form $-\frac{1}{2} \bf{y}^T \bf{J}^{-1} \bf{y}$ if you define
$$
\bf{y} = \bf{x} - \bf{J}\bf{s}
$$
and with the assumption that $\bf{J}$ is a symmetric matrix, so that $\bf{J}^T=\bf{J}$.
In conclusion, your integral can be performed with a linear change of variable $\bf{x} \to \bf{y}$ (notice that this is simply a shift of your variable, so the extrema remain infinite and the Jacobian of the transformation is the identity):
$$
\frac{\exp{\left[\frac{1}{2}\bf{s}^T \bf{J} \bf{s} \right]}}{(2\pi)^{N/2}\sqrt{\det{\bf{J}}}} \int D\bf{y} \exp{\left[-\frac{1}{2} \bf{y}^T \bf{J}^{-1} \bf{y}\right]} = \exp{\left[\frac{1}{2}\bf{s}^T \bf{J} \bf{s} \right]}.
$$
where I have used the standard Gaussian integral result in the last equality.
Notice that this formula is a very useful trick to study mean field theory in classical and quantum field theories of interacting systems, and is often called Hubbard-Stratonovich transformation.


text:
Q: Store formatted strings, pass in values later? I have a dictionary with a lot of strings.
Is it possible to store a formatted string with placeholders and pass in a actual values later?
I'm thinking of something like this:
d = {
  "message": f"Hi There, {0}"
}

print(d["message"].format("Dave"))

The above code obviously doesn't work but I'm looking for something similar.

A: You use f-string; it already interpolated 0 in there. You might want to remove f there
d = {
          # no f here
  "message": "Hi There, {0}"
}

print(d["message"].format("Dave"))

Hi There, Dave

A: Issue: mixing f-String with str.format

Technique
Python version

f-String
since 3.6

str.format
since 2.6

Your dict-value contains an f-String which is immediately evaluated.
So the expression inside the curly-braces (was {0}) is directly interpolated (became 0), hence the value assigned became "Hi There, 0".
When applying the .format argument "Dave", this was neglected because string already lost the templating {} inside. Finally string was printed as is:

Hi There, 0

Attempt to use f-String
What happens if we use a variable name like name instead of the constant integer 0 ?
Let's try on Python's console (REPL):
>>> d = {"message": f"Hi There, {name}"}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined

OK, we must define the variable before. Let's assume we did:
>>> name = "Dave"; d = {"message": f"Hi There, {name}"}
>>> print(d["message"])
Hi There, Dave

This works. But it requires the variable or expression inside the curly-braces to be valid at runtime, at location of definition: name is required to be defined before.
Breaking a lance for str.format
There are reasons

*

*when you need to read templates from external sources (e.g. file or database)

*when not variables but placeholders are configured independently from your source
Then indexed-placeholders should be preferred to named-variables.
Consider a given database column message with  value "Hello, {1}. You are {0}.". It can be read and used independently from the implementation (programming-language, surrounding code).
For example

*

*in Java: MessageFormat.format(message, 74, "Eric")

*in Python: message.format(74, 'Eric').

See also:
Format a message using MessageFormat.format() in Java


text:
Q: Bubble Sort ArrayIndexOutOfBounds in Java for(i=0;i<=4;i++)
            {
                for(j=0;j<=4;j++)
                {
                    if(hand[j] > hand[j+1])
                    {
                        temp = hand[j];
                        hand[j] = hand[j+1];
                        hand[j+1] = temp;
                    }
                }
            }

When I try to run this bubble sorting program, there's an ArrayIndexOutOfBounds Exception. Why? And how do I fix it?

A: You are accessing hand[] from index 0 to 5 (since it is j+1). Size of hand[] must be at least 6 for you to be able to do it. In your case, it is not, hence the error.

A: This happens due the fact your array size is 5 thus the range is from 0-4 while you try to get in the last iteration the value from hand[j+1] that means hand[5] which produces this exception.

A: As everyone else said, when you have 5 elements in the array you can only access indices 0 to 4. As far as fixing goes, it should be:
for(i=0;i<4;i++)
{
    for(j=0;j<4-i;j++)
    {
        if(hand[j] > hand[j+1])
        {
            temp = hand[j];
            hand[j] = hand[j+1];
            hand[j+1] = temp;
        }
    }
}


text:
Q: How to get the MailItems of a specific folder in Outlook My folder is called "Request Mailbox" in Outlook
How can I get a list of all mailitems in that folder

A: To get list of MailItems, you can simply do this
MailItem list will be displayed as Email
Option Explicit
Sub MailItems()
    Dim olNamespace As Outlook.NameSpace
    Dim olFolder  As Outlook.MAPIFolder
    Dim olItem As Outlook.MailItem

    Set olNamespace = Application.GetNamespace("MAPI")
    Set olFolder = olNamespace.GetDefaultFolder(olFolderInbox).Folders("Request Mailbox")

    Set olItem = Application.CreateItem(olMailItem) ' Creat EMail
    With olItem
        For Each olItem In olFolder.Items
            Debug.Print olItem.Subject ' Print to immediate window
            .body = .body & olItem.Subject & vbCrLf ' Print to Email
            Debug.Print olItem.SenderName
            .body = .body & olItem.SenderName & vbCrLf
            Debug.Print olItem.ReceivedTime
            .body = .body & olItem.ReceivedTime & vbCrLf & vbCrLf
        Next ' vbCrLf = vb: Visual Basic Cr: Carriage Return Lf: LineFeed
        .Subject = "Mail Items" ' Subject
        .Display    ' Display Msg
    End With

End Sub

For Shared Folder Try this
Option Explicit
Sub ShareMailItems()
    Dim olNamespace As Outlook.NameSpace
    Dim olShareName As Outlook.Recipient
    Dim olShareInbox As Outlook.Folder
    Dim olItem As Outlook.MailItem

    Set olNamespace = Application.GetNamespace("MAPI")
    Set olShareName = olNamespace.CreateRecipient("0m3r@email.com") '// Owner's email address
    Set olShareInbox = olNamespace.GetSharedDefaultFolder( _
                 olShareName, olFolderInbox).Folders("Request Mailbox") '// FolderName

    Set olItem = Application.CreateItem(olMailItem) ' Creat EMail
    With olItem
        For Each olItem In olShareInbox.Items
            Debug.Print olItem.Subject ' Print to immediate window
            .body = .body & olItem.Subject & vbCrLf ' Print to Email
            Debug.Print olItem.SenderName
            .body = .body & olItem.SenderName & vbCrLf
            Debug.Print olItem.ReceivedTime
            .body = .body & olItem.ReceivedTime & vbCrLf & vbCrLf
        Next ' vbCrLf = vb: Visual Basic Cr: Carriage Return Lf: LineFeed
        .Subject = "Mail Items" ' Subject
        .Display    ' Display
    End With
End Sub

A: For a delegate mailbox already open in Outlook, use Application.Session.Folders.("TheDelegateMialboxName@YourCompany.com").Folders("TheFolderName")


text:
Q: Handling resources across local vs sandboxed maven test environments The standard maven directory structure includes resources as follows:
  src/main/resources
  src/test/resources

When a maven build is initiated on a sandboxed environment - e.g. jenkins then all of the artifacts in those directories become available at the sandboxed "current" directory - and without resorting to any paths - either relative or absolute.
But when running mvn test locally the sandboxed environment is not in play: instead it is just the root directory of the project. In this case those resources would seem to need to be accessed via src/main[test]/resources.
Specifically: in a sandboxed environment all of the classes to be run are unpacked into a temporary directory *along with the resources under src/[test|main]/resources*.  Therefore: the files/artifacts undersrc/[test|main]/resources` are present in the current directory. The "relative" path to those resources is thus
    ./

But in the local environment - e.g. running mvn test at the root directory of a local git clone - then the current directory is the git repo root dir. The "relative" path to the artifacts is thus
./src/[test|main]/resources

While I realize the artifacts can also be accessed via classLoader.getResourceAsStream I have apis' that require File access.  We use api's like listFiles() and there is also the need to generate files in the given directories using file:// uri as well as literal paths. so we do need file paths.
What can be done here to normalize the paths across these different use cases/environments?


text:
Q: Select last part of a string in iTerm2 using standard shortcut Using iTerm2, I am currently typing this command (notice the cursor at the end of addons):

If my terminal would be like any other text input I use on my Mac, I could use the shortcut Alt + Shift + left arrow to select the word addons. This is why I use the natural text editing key mapping in iTerm2, to be like other text editing tools.
However, I cannot find how to get the same behavior on iTerm2, which I would like to result in this after using the shortcut:

Is there any way to get this behavior using key mappings or something else?


text:
Q: How to show the current time and the duration of an audio using Pyglet? I am new in Python - Pyglet and Stackoverflow. I would like know how to show the current playing time and the total duration of an audio in Pyglet. It is clearly given in Pyglet Docs but I don't excactly understood how to  use it properly. So kindly I would like to request for help.
It would be lot easier by showing an example. Thanks!
Here is my code..
from tkinter import*
import pyglet

root = Tk()

player = pyglet.media.Player()
song = "er.mp3"
src = pyglet.media.load(song)
player.queue(src)

def play():
    player.play()

def pause():
    player.pause()

button_1 = Button(root,text = "Play", command = play)
button_1.pack()
button_2 = Button(root,text = "Pause", command = pause)
button_2.pack()

root.mainloop()

(Sorry For Bad English)

A: Short answer is:
current_time = player.time

That will give/store the time of the currently playing audio.
What you do with this information is up to you, I assume you want to add it to a label or something.
v = StringVar()
Label(master, textvariable=v).pack()

# Probably in a event driven loop or something.
v.set(player.time)

However the long answer is, don't mix your libraries.
Pyglet is great for 2D/3D rendering since you can hook into the GL libraries pretty well.
What Pyglet does not do great is Audio (even tho it has support for it).
Tkinter on the other hand does nothing of these things but instead gives you buttons and other "widgets".
I would recommend using any other library under how to play music through python with mpg321 for playing audio with tkinter.
Either The Snack Sound Toolkit or winsound if you're on windows.


text:
Q: Правильная настройка Denwer Здравствуйте. Очень сильно нужна помощь.
Есть задача установить Denwer Windows Server 2008 r2.
Однако процесс осложняется тем, что я узнал о самом Денвере в тот же день, когда мне поставили эту задачу.
Основной вопрос таков - есть ли некие подводные камни и прочие подвохи, которые могут ожидать меня в процессе установки?
И если можно, то дайте ссылку на какую нибудь статью по установке (язык статьи не сильно принципиален). Сам ничего не нашел.
A: Ставил его на Windows Server 2012, оочень быстро все поставил и установил. НО он ооочень медленный, если сервак слабый - порой 500 ошибку кидает.
Сам когда-то искал доп.инфу по нему, но кроме официальной документации ничего не нашел.
P.S На XP кстати денвер бегает резво
Почему бы не собрать стандартный сервер (WAMP)?


text:
Q: Choose default photo viewer app to open from Windows Camera History: I recently began getting errors when trying to open images in the default Microsoft Photos app. It turned out I'm not the only one with the problem and I'm not the only one who is unable to solve it, so I installed a different app to view photos (IrfanView). (There is an app but one can also install it as a program.)
Problem: When I open Windows Camera, as usual the last photo I took is shown at the bottom right of the screen. When clicking it, the photo used to be opened in Microsoft Photos. But since that app doesn't work anymore (in fact I removed it in powershell) I want Windows Camera to open the photo in a different app (IfranView). How can I do this?
I set IrfanView as the default photo viewer, but that doesn't help.
When I try to open a photo in Windows Camera, I'm asked to choose an app from the Microsoft store, but there appears to be no way to actually select an app. It just opens the store and that's it. After that, I get the error

0xA00F428B<FailedToLaunchPhotosApp>

A: There are multiple places to set default applications in Windows 10:

*

*Press Windows, type default pr and select Default Programs.

*The first option to Set your default programs sets the handling of generic file types, e.g. images (.PNG, .JPEG, .BMP, .TIFF, etc.) would be handled by Photo viewer.

*Near the bottom of the dialog, select Associate a file type or protocol with a a program to set the specific file type used by Windows Camera, .JPG.

*If IrfanView is in the list, well and good, select it.

However, it it is not listed, Microsoft will not allow the selection of an alternate applications (as opposed to the Metro [deprecated] apps). In order to select IrfanView, do the following.

*

*Press WindowsE to open Explorer.

*Navigate to This PC > Pictures > Camera Roll.

*Right-click on a .JPG image.

*Select Open with >.

*If IrfanView is not shown, select Choose another app.

*Click on Always use this app to open .JPG files.

*Navigate to IrfanView and set it as the default.

Next time you double-click a .JPG, it should open in the correct application.


text:
Q: Java explode method for int array currently trying to create an explode method for integers similar to php's with no luck because I can't find information on this subject unless it's a string. My end goal is to make (for ex.) 1,2,3 -> 1,1,2,2,3,3

A: Reading the docs for explode, then this is just String.split(${regex})
"1,2,3".split(",")
But what you have is not that. I have also produced a solution for that as well.
@Test
public void name() {
    int[] result = Arrays.stream(new int[] {1, 2, 3}).flatMap(i -> Arrays.stream(new int[] {i, i})).toArray();
    System.out.println(Arrays.toString(result));
}

[1, 1, 2, 2, 3, 3]


text:
Q: slice and merge 2 arrays is there a good way to slice and merge 2 arrays based on empty values for example
first array
      0 => string 'Perfect all gorgeous and arrived in less than 1 month for brazil' (length=64)
      1 => string '' (length=0)
      2 => string '' (length=0)
      3 => string 'Good figures for their money, only instead of bits normal stick child bit rastroilsya' (length=85)
      4 => string '' (length=0)
      5 => string '' (length=0)

second array
 0 => string '' (length=0)
      1 => string 'http://g01.a.alicdn.com/kf/UTB8jjnecFfFXKJk43Otq6xIPFXaw.jpg" data-eid="eid-201782563197' (length=88)
      2 => string 'http://g01.a.alicdn.com/kf/UTB87.bdcNHEXKJk43Jeq6yeeXXaZ.jpg" data-eid="eid-201782563197' (length=88)
      3 => string '' (length=0)
      4 => string 'http://g01.a.alicdn.com/kf/UTB8cxXwg4HEXKJk43Jeq6yeeXXam.jpg" data-eid="eid-201833045441' (length=88)
      5 => string 'http://g04.a.alicdn.com/kf/UTB824Xwg4HEXKJk43Jeq6yeeXXaB.jpg" data-eid="eid-201833045441' (length=88)

I want them to be like this array
array (size=2)
  0 =>
    array (size=2)
      'comment' => string 'Perfect all gorgeous and arrived in less than 1 month for brazil' (length=64)
      'images' =>
        array (size=2)
          0 => string 'http://g01.a.alicdn.com/kf/UTB8jjnecFfFXKJk43Otq6xIPFXaw.jpg" data-eid="eid-201782563197' (length=88)
          1 => string 'http://g01.a.alicdn.com/kf/UTB87.bdcNHEXKJk43Jeq6yeeXXaZ.jpg" data-eid="eid-201782563197' (length=88)
  1 =>
    array (size=2)
      'comment' => string 'Good figures for their money, only instead of bits normal stick child bit rastroilsya' (length=85)
      'images' =>
        array (size=2)
          3 => string 'http://g01.a.alicdn.com/kf/UTB8cxXwg4HEXKJk43Jeq6yeeXXam.jpg" data-eid="eid-201833045441' (length=88)
          4 => string 'http://g04.a.alicdn.com/kf/UTB824Xwg4HEXKJk43Jeq6yeeXXaB.jpg" data-eid="eid-201833045441' (length=88)

How to do it ?

A: Got something that will help. It will work with more inputs if you need. It might not work best if your second array has more than one breaking blank. Just working on updated code to solve such issues.
<?php

$arr1 = array("input", "", "", "another input", "", "", "yet another input", "");
$arr2 = array("", "p1", "p2", "", "p01", "p02", "","p11" );

$inp = array("comment" => $arr1, "images" => $arr2);

function mangle_arrays($input) {
    $out = array();
    $gen = 0;
    foreach($input as $key=>$val) {
        $id = $gen?-1:0;
        if ($gen) {
            foreach($val as $v) {
                if ($v) {
                    $out[$id][$key][] = $v;
                } else {
                    $id++;
                }
            }
        } else {
            foreach($val as $v) {
                if ($v) {
                    $out[$id] = array();
                    $out[$id][$key] = $v;
                    $id++;
                }
            }
        }
        $gen++;
    }
    return $out;
}

// your code goes here
echo "<pre>";
print_r(mangle_arrays($inp));

Results
Array
(
    [0] => Array
        (
            [comment] => input
            [images] => Array
                (
                    [0] => p1
                    [1] => p2
                )

        )

    [1] => Array
        (
            [comment] => another input
            [images] => Array
                (
                    [0] => p01
                    [1] => p02
                )

        )

    [2] => Array
        (
            [comment] => yet another input
            [images] => Array
                (
                    [0] => p11
                )

        )

)


text:
Q: tinymce - resize/scale handelers are not in the same place as resize object Tinymce re-size/scale handlers are not appearing in the same place where the re-sizable/scalable object are, but far below the object.
I am using inline feature, this issue is happening with all re-sizable, like table, image etc.
Here is the screenshot of issue:

A: I got the solution, position of parent of re-sizable object need to be relative


text:
Q: Efficient way to convert Dataframe to RDD in Scala/SPARK? I have a dataFrame = [CUSTOMER_ID ,itemType, eventTimeStamp, valueType] which I convert to RDD[(String, (String, String, Map[String, Int]))] by doing the following:
 val tempFile = result.map( {
     r => {
         val customerId = r.getAs[String]( "CUSTOMER_ID" )
         val itemType = r.getAs[String]( "itemType" )
         val eventTimeStamp = r.getAs[String]( "eventTimeStamp" )
         val valueType = r.getAs[Map[String, Int]]( "valueType" )
         (customerId, (itemType, eventTimeStamp, valueType))
          }
          } )

Since my my input is huge, this takes much time. Is there any efficient way to convert the df to RDD[(String, (String, String, Map[String, Int]))] ?

A: The operation you've described is as cheap as it's going to get.  Doing a few getAs and allocating a few tuples is almost free.  If it's going slow, that's probably unavoidable due to your large data size (7T).  Also note that Catalyst optimizations cannot be performed on RDDs, so including this kind of .map downstream of DataFrame operations will often prevent other Spark shortcuts.


text:
Q: Why is refreshtoken always null using the Auth0 passport strategy Using the auth0 passport strategy
https://github.com/auth0/passport-auth0
My callback always has null for a refresh token.  Calling the auth0 lock function directly gives me a refreshtoken as expected, however using this oauth passport strategy doesn't return a refreshtoken.  Do I need to pass an offline_access scope to auth0 - and if so, how do I pass it in using the Auth0Strategy?
passport.use(new Auth0Strategy({
    domain:       config.auth0.domain,
    clientID:     config.auth0.clientId,
    clientSecret: config.auth0.secret,
    callbackURL:  '/login/return'
  },
  function(accessToken, refreshToken, extraParams, profile, done) {
    console.log('refresh token is always null', refreshToken);
 }
});

A: Yes, you need to request one (by adding scope=offline_access). You do this when you send the initial authorization request (e.g. via Lock, or auth0.js, or by simply following link with the right parameters). It is not dependent on passport really. Makes sense?
e.g. try with this:
app.get('/login',
  passport.authenticate('auth0', {scope: 'offline_access'}), function (req, res) {
  res.redirect("/");
});


text:
Q: Identifying the current user requesting the rest endpoints I am trying to implement authentication and authorization using angular and java where I came across "identifying the current user asking for resource" from this Link
The point where I am not able to understand is getting the user from getUserPrincipal() method using jax-rs SecurityContext.
Security Context:
requestContext.setSecurityContext(new SecurityContext() {

    @Override
    public Principal getUserPrincipal() {

        return new Principal() {

            @Override
            public String getName() {
                return email;
            }
        };
    }
}

The above method apparently returns a user but the question is from where? I have searched on this topic but no where I see code for fetching the user from DB or any other resource.
Where as I have implemented some thing like this for validation:
@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the HTTP Authorization header from the request
        String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Check if the HTTP Authorization header is present and formatted correctly
        if (authorizationHeader == null || !authorizationHeader.startsWith("Basic ")) {
            throw new NotAuthorizedException("Authorization header must be provided");
        }

        // Extract the token and email address from the HTTP Authorization header
        String email = requestContext.getHeaderString("Email");
        String token = authorizationHeader.substring("Basic".length()).trim();

        try {
            // Validate the token
            validateToken(email, token);

        } catch (Exception e) {
            requestContext.abortWith(
                    Response.status(Response.Status.UNAUTHORIZED).build());
        }

    private void validateToken(String email, String token) throws Exception {
        // Check if it was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
        try {
            TokenSaverAndValidatorDAO tokenValidator = new TokenSaverAndValidatorDAO();
            String result = tokenValidator.checkTokenFromDB(email, token);
            if (result.equals(token)) {
                System.out.println("Token is same");
            } else {
                System.out.println("Token is not same");
                throw new Exception();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The above method validateToken() calls a method from DAO class for validation:
public String checkTokenFromDB(String email, String token) {
        String result = "";
        try {
            String query = "Select USR_TOKEN From TBL_USER where USR_PRIMARY_EMAIL= ? ";
            Connection con = DBConnection.getConnection();
            PreparedStatement statement = con.prepareStatement(query);
            statement.setString(1, email);
            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                result = rs.getString("USR_TOKEN");
            }

        } catch (Exception ex) {
            System.out.println("Error in TokenSaverDAO class");
            ex.printStackTrace();
        }
        return result;
    }

How do I use jax-rs securityContext in my application. Does it apply to my scenario?
I am sending the headers from angular like this:
$httpProvider.interceptors.push(['$q', '$location', '$localStorage', 'jwtHelper', function ($q, $location, $localStorage, jwtHelper) {
    return {
        'request': function (config) {
            config.headers = config.headers || {};
            if ($localStorage.token) {
                var decodeToken = jwtHelper.decodeToken($localStorage.token);
                config.headers.Email = decodeToken.email;
                config.headers.Authorization = 'Basic ' + $localStorage.token;
            }
            return config;
        },
        'responseError': function (response) {
            if (response.status === 401 || response.status === 403) {
                $location.path('/Login');
            }
            return $q.reject(response);
        }
    };
}]);

Where the headers are set like this:
config.headers.Email = decodeToken.email;
config.headers.Authorization = 'Basic ' + $localStorage.token;


text:
Q: Load the root view when app enter into background in iPhone sdk I am developing an application which has 4 views and use navigation controller to navigate through. The first view is login interface. I just want to display login view when user press home button from second view. I have tried to use popToRootViewControllerAnimated in applicationDidEnterBackground. This does not work. Because I need to do this job only user press home button from second view (Second view contains MKMapView).
Can you please let me know what is the best option for this job? Basically I just need to check what view I am currently on.
Many Thanks

A: You could log a BOOL variable that the viewDidAppear function on your second controller sets to YES. And when you leave that view set it to NO.  In applicationDidEnterForeground check it.  If it is YES then the user left while in the second view.


text:
Q: Spyder doesn't launch from Anaconda on MacBook I just installed Anaconda to start coding in Python. However, after installing, the moment I launch Spyder I get the error "Python quit unexpectedly" error. I have tried running "conda update --all" and even reinstalling anaconda but no help.
Just for a sanity check, I looked up python version in the Terminal it is 3.7.6. If anyone can suggest a way to fix it'll be most helpful.
Entire Problem detail & system configuration below
Process:               python [6870]
Path:                  /opt/anaconda3/python.app/Contents/MacOS/python
Identifier:            python
Version:               0
Code Type:             X86-64 (Native)
Parent Process:        ??? [6869]
Responsible:           python [6870]
User ID:               501

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes:       0x0000000000000001, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Termination Signal:    Illegal instruction: 4
Termination Reason:    Namespace SIGNAL, Code 0x4
Terminating Process:   exc handler [0]

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   _multiarray_umath.cpython-37m-darwin.so 0x00000001075b144b npy_cpu_supports + 139
1   _multiarray_umath.cpython-37m-darwin.so 0x000000010742f0fe InitOperators + 94
2   _multiarray_umath.cpython-37m-darwin.so 0x000000010742dc00 PyInit__multiarray_umath + 160
3   com.continuum.python            0x0000000105bc3c1d _PyImport_LoadDynamicModuleWithSpec + 557
4   com.continuum.python            0x0000000105bc3033 _imp_create_dynamic + 243
5   com.continuum.python            0x0000000105a57c0f _PyMethodDef_RawFastCallDict + 255
6   com.continuum.python            0x0000000105a5931d PyCFunction_Call + 61
7   com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
8   com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
9   com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
10  com.continuum.python            0x0000000105b95d67 call_function + 183
11  com.continuum.python            0x0000000105b92b92 _PyEval_EvalFrameDefault + 42226
12  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
13  com.continuum.python            0x0000000105b95d67 call_function + 183
14  com.continuum.python            0x0000000105b92afc _PyEval_EvalFrameDefault + 42076
15  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
16  com.continuum.python            0x0000000105b95d67 call_function + 183
17  com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
18  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
19  com.continuum.python            0x0000000105b95d67 call_function + 183
20  com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
21  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
22  com.continuum.python            0x0000000105b95d67 call_function + 183
23  com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
24  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
25  com.continuum.python            0x0000000105a5a978 object_vacall + 248
26  com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
27  com.continuum.python            0x0000000105bbc798 PyImport_ImportModuleLevelObject + 3640
28  com.continuum.python            0x0000000105b91919 _PyEval_EvalFrameDefault + 37497
29  com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
30  com.continuum.python            0x0000000105b81e9b builtin_exec + 347
31  com.continuum.python            0x0000000105a57c0f _PyMethodDef_RawFastCallDict + 255
32  com.continuum.python            0x0000000105a5931d PyCFunction_Call + 61
33  com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
34  com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
35  com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
36  com.continuum.python            0x0000000105b95d67 call_function + 183
37  com.continuum.python            0x0000000105b92b92 _PyEval_EvalFrameDefault + 42226
38  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
39  com.continuum.python            0x0000000105b95d67 call_function + 183
40  com.continuum.python            0x0000000105b92afc _PyEval_EvalFrameDefault + 42076
41  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
42  com.continuum.python            0x0000000105b95d67 call_function + 183
43  com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
44  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
45  com.continuum.python            0x0000000105b95d67 call_function + 183
46  com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
47  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
48  com.continuum.python            0x0000000105a5a978 object_vacall + 248
49  com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
50  com.continuum.python            0x0000000105bbc798 PyImport_ImportModuleLevelObject + 3640
51  com.continuum.python            0x0000000105b809d5 builtin___import__ + 149
52  com.continuum.python            0x0000000105a59388 PyCFunction_Call + 168
53  com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
54  com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
55  com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
56  com.continuum.python            0x0000000105b95d67 call_function + 183
57  com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
58  com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
59  com.continuum.python            0x0000000105a577c7 _PyFunction_FastCallDict + 231
60  com.continuum.python            0x0000000105a5a978 object_vacall + 248
61  com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
62  com.continuum.python            0x0000000105bbbd03 PyImport_ImportModuleLevelObject + 931
63  com.continuum.python            0x0000000105b91919 _PyEval_EvalFrameDefault + 37497
64  com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
65  com.continuum.python            0x0000000105b81e9b builtin_exec + 347
66  com.continuum.python            0x0000000105a57c0f _PyMethodDef_RawFastCallDict + 255
67  com.continuum.python            0x0000000105a5931d PyCFunction_Call + 61
68  com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
69  com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
70  com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
71  com.continuum.python            0x0000000105b95d67 call_function + 183
72  com.continuum.python            0x0000000105b92b92 _PyEval_EvalFrameDefault + 42226
73  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
74  com.continuum.python            0x0000000105b95d67 call_function + 183
75  com.continuum.python            0x0000000105b92afc _PyEval_EvalFrameDefault + 42076
76  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
77  com.continuum.python            0x0000000105b95d67 call_function + 183
78  com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
79  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
80  com.continuum.python            0x0000000105b95d67 call_function + 183
81  com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
82  com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
83  com.continuum.python            0x0000000105a5a978 object_vacall + 248
84  com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
85  com.continuum.python            0x0000000105bbc798 PyImport_ImportModuleLevelObject + 3640
86  com.continuum.python            0x0000000105b809d5 builtin___import__ + 149
87  com.continuum.python            0x0000000105a59388 PyCFunction_Call + 168
88  com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
89  com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
90  com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
91  com.continuum.python            0x0000000105b95d67 call_function + 183
92  com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
93  com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
94  com.continuum.python            0x0000000105a577c7 _PyFunction_FastCallDict + 231
95  com.continuum.python            0x0000000105a5a978 object_vacall + 248
96  com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
97  com.continuum.python            0x0000000105bbbd03 PyImport_ImportModuleLevelObject + 931
98  com.continuum.python            0x0000000105b91919 _PyEval_EvalFrameDefault + 37497
99  com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
100 com.continuum.python            0x0000000105b81e9b builtin_exec + 347
101 com.continuum.python            0x0000000105a57c0f _PyMethodDef_RawFastCallDict + 255
102 com.continuum.python            0x0000000105a5931d PyCFunction_Call + 61
103 com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
104 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
105 com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
106 com.continuum.python            0x0000000105b95d67 call_function + 183
107 com.continuum.python            0x0000000105b92b92 _PyEval_EvalFrameDefault + 42226
108 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
109 com.continuum.python            0x0000000105b95d67 call_function + 183
110 com.continuum.python            0x0000000105b92afc _PyEval_EvalFrameDefault + 42076
111 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
112 com.continuum.python            0x0000000105b95d67 call_function + 183
113 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
114 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
115 com.continuum.python            0x0000000105b95d67 call_function + 183
116 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
117 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
118 com.continuum.python            0x0000000105a5a978 object_vacall + 248
119 com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
120 com.continuum.python            0x0000000105bbc798 PyImport_ImportModuleLevelObject + 3640
121 com.continuum.python            0x0000000105b809d5 builtin___import__ + 149
122 com.continuum.python            0x0000000105a59388 PyCFunction_Call + 168
123 com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
124 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
125 com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
126 com.continuum.python            0x0000000105b95d67 call_function + 183
127 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
128 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
129 com.continuum.python            0x0000000105a577c7 _PyFunction_FastCallDict + 231
130 com.continuum.python            0x0000000105a5a978 object_vacall + 248
131 com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
132 com.continuum.python            0x0000000105bbbd03 PyImport_ImportModuleLevelObject + 931
133 com.continuum.python            0x0000000105b91919 _PyEval_EvalFrameDefault + 37497
134 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
135 com.continuum.python            0x0000000105b81e9b builtin_exec + 347
136 com.continuum.python            0x0000000105a57c0f _PyMethodDef_RawFastCallDict + 255
137 com.continuum.python            0x0000000105a5931d PyCFunction_Call + 61
138 com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
139 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
140 com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
141 com.continuum.python            0x0000000105b95d67 call_function + 183
142 com.continuum.python            0x0000000105b92b92 _PyEval_EvalFrameDefault + 42226
143 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
144 com.continuum.python            0x0000000105b95d67 call_function + 183
145 com.continuum.python            0x0000000105b92afc _PyEval_EvalFrameDefault + 42076
146 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
147 com.continuum.python            0x0000000105b95d67 call_function + 183
148 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
149 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
150 com.continuum.python            0x0000000105b95d67 call_function + 183
151 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
152 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
153 com.continuum.python            0x0000000105a5a978 object_vacall + 248
154 com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
155 com.continuum.python            0x0000000105bbc798 PyImport_ImportModuleLevelObject + 3640
156 com.continuum.python            0x0000000105b809d5 builtin___import__ + 149
157 com.continuum.python            0x0000000105a58bd8 _PyMethodDef_RawFastCallKeywords + 392
158 com.continuum.python            0x0000000105b95de2 call_function + 306
159 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
160 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
161 com.continuum.python            0x0000000105b81e9b builtin_exec + 347
162 com.continuum.python            0x0000000105a57c0f _PyMethodDef_RawFastCallDict + 255
163 com.continuum.python            0x0000000105a5931d PyCFunction_Call + 61
164 com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
165 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
166 com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
167 com.continuum.python            0x0000000105b95d67 call_function + 183
168 com.continuum.python            0x0000000105b92b92 _PyEval_EvalFrameDefault + 42226
169 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
170 com.continuum.python            0x0000000105b95d67 call_function + 183
171 com.continuum.python            0x0000000105b92afc _PyEval_EvalFrameDefault + 42076
172 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
173 com.continuum.python            0x0000000105b95d67 call_function + 183
174 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
175 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
176 com.continuum.python            0x0000000105b95d67 call_function + 183
177 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
178 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
179 com.continuum.python            0x0000000105a5a978 object_vacall + 248
180 com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
181 com.continuum.python            0x0000000105bbc798 PyImport_ImportModuleLevelObject + 3640
182 com.continuum.python            0x0000000105b91919 _PyEval_EvalFrameDefault + 37497
183 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
184 com.continuum.python            0x0000000105b81e9b builtin_exec + 347
185 com.continuum.python            0x0000000105a57c0f _PyMethodDef_RawFastCallDict + 255
186 com.continuum.python            0x0000000105a5931d PyCFunction_Call + 61
187 com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
188 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
189 com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
190 com.continuum.python            0x0000000105b95d67 call_function + 183
191 com.continuum.python            0x0000000105b92b92 _PyEval_EvalFrameDefault + 42226
192 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
193 com.continuum.python            0x0000000105b95d67 call_function + 183
194 com.continuum.python            0x0000000105b92afc _PyEval_EvalFrameDefault + 42076
195 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
196 com.continuum.python            0x0000000105b95d67 call_function + 183
197 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
198 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
199 com.continuum.python            0x0000000105b95d67 call_function + 183
200 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
201 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
202 com.continuum.python            0x0000000105a5a978 object_vacall + 248
203 com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
204 com.continuum.python            0x0000000105bbc798 PyImport_ImportModuleLevelObject + 3640
205 com.continuum.python            0x0000000105b809d5 builtin___import__ + 149
206 com.continuum.python            0x0000000105a59388 PyCFunction_Call + 168
207 com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
208 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
209 com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
210 com.continuum.python            0x0000000105b95d67 call_function + 183
211 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132
212 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
213 com.continuum.python            0x0000000105a577c7 _PyFunction_FastCallDict + 231
214 com.continuum.python            0x0000000105a5a978 object_vacall + 248
215 com.continuum.python            0x0000000105a5ab83 _PyObject_CallMethodIdObjArgs + 243
216 com.continuum.python            0x0000000105bbbd03 PyImport_ImportModuleLevelObject + 931
217 com.continuum.python            0x0000000105b91919 _PyEval_EvalFrameDefault + 37497
218 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
219 com.continuum.python            0x0000000105b81e9b builtin_exec + 347
220 com.continuum.python            0x0000000105a57c0f _PyMethodDef_RawFastCallDict + 255
221 com.continuum.python            0x0000000105a5931d PyCFunction_Call + 61
222 com.continuum.python            0x0000000105b93d9d _PyEval_EvalFrameDefault + 46845
223 com.continuum.python            0x0000000105b8746e _PyEval_EvalCodeWithName + 414
224 com.continuum.python            0x0000000105a58a03 _PyFunction_FastCallKeywords + 195
225 com.continuum.python            0x0000000105b95d67 call_function + 183
226 com.continuum.python            0x0000000105b92b92 _PyEval_EvalFrameDefault + 42226
227 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
228 com.continuum.python            0x0000000105b95d67 call_function + 183
229 com.continuum.python            0x0000000105b92afc _PyEval_EvalFrameDefault + 42076
230 com.continuum.python            0x0000000105a582d5 function_code_fastcall + 117
231 com.continuum.python            0x0000000105b95d67 call_function + 183
232 com.continuum.python            0x0000000105b93ad4 _PyEval_EvalFrameDefault + 46132


text:
Q: issues configuring firewall rules for Postgres on Centos I am attempting to follow this guide to allow remote connections to postgres http://www.cyberciti.biz/tips/postgres-allow-remote-access-tcp-connection.html
At the moment I am running into issues with the firewall.
I have it setup so I have a /tmp/v4 that I can modify and just restore my firewall rules from.
I have tried 2 settings.
The one the guide recommends:
-A INPUT -p tcp -s 0/0 --sport 1024:65535 -d 00.000.000.00  --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -p tcp -s 00.000.000.00 --sport 5432 -d 0/0 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT

When I use this setting and run nc ipofserver 5432 I get Ncat: connection timed out
If I try settings
-I INPUT -p tcp -s 00.000.000.00  --dport 5432 -j ACCEPT
-I INPUT -p tcp -s 00.000.000.00  --dport 5432 -j ACCEPT

I run the same ncat command, I get Ncat: Connection refused
I use the same base firewalls (not what is listed above) on another server for serving redis and it works correctly.
firewalld has been disabled on this box in favor of iptables, mostly for familiarity purposes.
Both machines are CentOS 7
00.000.000.00 replaces the IP of the computer I am actually using

A: centos7 uses firewall-cmd out of the box, unless you have disabled it. I assume you have not because you would have mentioned it otherwise.
With that assumption in place, then you can simply run this on your postgresql host:
firewall-cmd --add-service=postgresql

Once you have verified that it works, then you can run it again with the permanent switch to make it stick after reboots:
firewall-cmd --add-service=postgresql --permanent

If you install the bash-completion package, after re-logging in, firewall-cmd autocompletes, making it really easy to use.
Edit: OP indicates he does not use firewall-cmd. So assuming he uses the old iptables service, then the canonical way to modify is to edit /etc/sysconfig/iptables.
If you want to allow incoming connections to port 5432/tcp in that host, then you need to add this line
-A INPUT -m state --state NEW -m tcp -p tcp --dport 5432 -j ACCEPT

before
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

and the reload the iptables service. This will of course allow all connections to the database server from any host.
If you want to limit what hosts may connect (let's limit it to one, 111.222.111.222), then:
-A INPUT -p tcp -s 111.222.111.222 --sport 1024:65535 --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT

That should do it, remove the other one, of course, and reload the iptables service


text:
Q: Most probable value vs typical value in a specific simulation could you please give me some hint on how to tackle the following question?
I think I am not on the right way as I am thinking that deriving the pdf of a product of $N$ uniformly distributed random variables on the interval [1,2] is mandatory for the solution. The question is from this book.
I know that the most probable value is the one that makes the derivative of the pdf equal to zero. But I do not get what the author exactly means with his hint.

$2.5\;$ Generate numerically $M$ random numbers $x$ each being the product of $N$ independent random numbers equally distributed between $1$ and $2$ with $M$ between $10^3$ and $10^6$ and $N$ between $5$ and $50$.  Approximate the distribution of $x$ by a histogram and compare the evolution with $N$ of the most probable value $x_\text{mp}$ of $x$ with its average $\langle\!\langle x \rangle\!\rangle$ and the quantity $x_\text{typ} := \exp(\langle\!\langle \ln x \rangle\!\rangle)$.  Could you give an argument why asymptotically (for $N \to \infty$) the most probable value and $x_\text{typ}$ should coincide?  Why is the most probable value always smaller than $x_\text{typ}$ in the simulations?
  (Hint: Compare the equations determining the most probable value of $x$ and of $\ln x$.)

[First attempt to solve the question - by using the result provided here]

I got that the key of the question is to make use of the Central Limit Theorem.
We have $X=Y_1 \dotsb Y_N$ where $Y$ are iid and are uniformly distributed on $[1,2]$.
Hence, by the central limit theorem, $\ln(X)=\ln(Y_1)+\dotsb+\ln(Y_N)$ is approximately normally distributed for $N$ sufficiently large.
So, lets calculate the mean and vaiance of $\ln(Y)$. As $Y\sim U[1,2]$, it is immediate that $\ln(Y)\sim e^y \,,y\in [0,\ln(2)]$. Hence, after some integration we have the first two moments of $\ln(Y)$. They are:
$$\mu :=\text{mean}(\ln(Y))=\ln(4)-1=0,38629$$
and
$$V:=\text{variance}(\ln(Y))= 1-2\ln^2(2)=0.03909$$
Hence, $\ln(X)\sim N(N\mu,NV)$.
As $\ln(X)$ is normally distributed, then X is lognormally distributed. More preciselly $X\sim \text{logN}(N\mu,NV)$.
Hence, we have everything that we need to finish the exercise.
The author asks for a comparasion among $x_{mp}$ and $x_{typ}$. So lets do it:
$x_{mp}:= \text{mode}(X)= e^{N\mu-NV}$ That is the mode that wikipedia gives for the lognormal distribution.
$$x_{typ}:=e^{\mathbb{E}(\ln(X))}= e^{N\mu}$$.
Finally, as $N \rightarrow \infty$, we have:
$$x_{mp}= e^{N\mu-NV}=e^{N(0.34)}\rightarrow \infty$$
$$x_{typ}= e^{N\mu}= e^{N(0.38)}\rightarrow \infty$$


text:
Q: Node.JS Command Prompt I was messing around with the npm package today and I noticed that all of my commands were being run from my command prompt on my machine rather than through the node.js command line that comes with the download.
Bottom line: Why is there a node command prompt if you run commands from your local command prompt?
I saw there was a question like this here: node.js command line tool but it doesnt exactly answer the question.
I appreciate any help out there.

A: The node.js command prompt has your node.js environment set-up. Most of time, if you try to install some global package through your local command prompt, it will not work as expected, but if you use node.js command prompt it will. Happened to me while trying to use the express-generator.


text:
Q: What does the $f^!$ do for line bundles on a curve? I'm trying to understand what does inverse exceptional image $f^!$ of a coherent sheaf look like.
Let's say for the sake of this question that $f:X\rightarrow Y$ is a finite flat morphism between schemes. In this case, my understanding is that $f^!$ is a functor from coherent sheaves on $Y$ to coherent sheaves on $X$, and that if $\mathcal{F}$ is a coherent sheaf on $Y$ then $f^!\mathcal{F}$ can be described as $\underline{Hom}_{\mathcal{O}_Y}(f_*(\mathcal{O}_X),\mathcal{F})$.
If $X$ and $Y$ are affine then it's not hard to work out what this does for a coherent sheaf on Y.
As another basic case, I'm trying to understand what happens if $\mathcal{L}$ is a line bundle on $Y$, in terms of divisors. Say $D=\sum{P_i}$ is a divisor on $Y$, and $\mathcal{L}(D)$ is the corresponding line bundle. My understanding is that if $f$ is etale then $f^! = f^*$, so that in that case $f^!(\mathcal{L}(D))=\mathcal{L}(D')$ where $D'=\sum_i\sum_{f(Q)=P_i}{Q}$.
Can we understand $f^!(\mathcal{L}(D))$ in general (by which I mean, when $f$ is assumed finite flat but not necessarily etale)? (can we say something more specific than $f^!\mathcal{L}(D)=\underline{Hom}_{\mathcal{O}_Y}(f_*(\mathcal{O}_X),\mathcal{L}(D))$, in terms of the divisor $D$)? And how should I think of the functor $f^!$ for general coherent sheaves, in this setting?
Thanks!


text:
Q: Funcion de Ocultar boton con JQuery Como hago para pasar esto a jQuery
id="btn_submit" onclick="javascript:document.getElementById('btn_submit').style.visibility = 'hidden';

Es para ocultar o bloquear un botón temporalmente para evitar el doble submit de un formulario, ¿Hay alguna otra manera de evitarlo?

A: Básicamente al hacer click al id btn_submit
 le cambia la propiedad CSS visibility a hidden
Se le agrega un tiempo de 2 segundos con setTimeout()
  $("#btn_submit").on('click',function(){ //Evento Click
     $("#btn_submit").css('visibility', 'hidden'); //Cambio de propiedad CSS
     setTimeout(function(){ //Se aguardan los milisegundos marcados en la próxima linea
       $("#btn_submit").css('visibility', 'visible');
     }, 2000); //2000 milisegundos == 2 segundos
   });

Aqui tienes mas sobre setTimeout https://www.w3schools.com/jsref/met_win_settimeout.asp

A: no entendi bien lo de el doble submit pero aqui te dejo un codigo para hacer lo que quieres con jquery:
$("#btn_submit").click(function(){ //le decimos cuando hagas click ejecute una funccion anonima

  $(this).hide(); //y que oculte este elemento clickeado

 $(this).css("visivility","0"); //o si quieres darle simplemente una visivilidad 0 seria asi
})


text:
Q: If $f,g$ are scalar functions then $\sup\{f(x)-g(y)\}=\sup\{f(x)\}-\inf\{g(y)\}$. Statement
Let be $A\subseteq\Bbb{R}^n$ and let be $f,g:A\rightarrow\Bbb{R}$ functions. So $\sup\{f(x)-g(y)\}=\sup\{f(x)\}-\inf\{g(y)\}$.
Clearly $f(x)\le\sup\{f(x)\}$ and $-g(y)\le-\inf\{f(y)\}$ and so summing $f(x)-g(y)\le\sup\{f(x)\}-\inf\{g(y)\}$ and so $\sup\{f(x)-g(y)\}\le\sup\{f(x)\}-\inf\{g(y)\}$. Unfortunately I can't prove the other inequality so I ask to do it and if the statement is generally false I ask to show a counterexample and so I ask if it is true when $f=g$. So could someone help me, please?

A: Note that
$$\begin{align}f(x)  \leqslant \sup_{x,y} (f(x) - g(y)) + g(y) &\implies \sup_x f(x) \leqslant \sup_{x,y} (f(x) - g(y)) + g(y) \\&\implies -g(y) \leqslant \sup_{x,y} (f(x) - g(y)) - \sup_x f(x) \\ &\implies -\inf_y g(y) = \sup_y (-g(y)) \leqslant \sup_{x,y} (f(x) - g(y)) - \sup_x f(x)\end{align} $$
Rearranging the final inequality, we get
$$\sup_x f(x)-\inf_y g(y)  \leqslant \sup_{x,y} (f(x) - g(y))  $$

A: Fix $\varepsilon > 0$, and call $A= \sup_x f(x)$ and $B= \inf_y g(y)$.
There exis $x,y$ such that
$$f(x) \ge A - \varepsilon \qquad ; \qquad g(y) \le B + \varepsilon$$
Then
$$f(x) - g(y) \ge A-B- 2 \varepsilon $$
By arbitrarity of $\varepsilon$, this shows that
$$\sup \{ f(x) - g(y) \} \ge A-B$$

A: More generally, let $A, B$ be non-empty sets (not necessarily subsets of $\mathbb{R}^n,$ for any $n$), $f \colon A \to \mathbb{R}$ a function that is bounded above, and $g \colon B \to \mathbb{R}$ a function that is bounded below. Then:
\begin{multline*}
\sup_{x \in A,\ y \in B}(f(x) - g(y)) = \sup\{ f(x) - g(y) : x \in A, \ y \in B \} \\ = \sup(f(A) - g(B)) = \sup(f(A)) - \inf(g(B)) = \sup_{x \in A}f(x) - \inf_{y \in B}g(y),
\end{multline*}
because if $E$ is a non-empty subset of $\mathbb{R}$ that is bounded above, and $F$ is a non-empty subset of $\mathbb{R}$ that is bounded below, then the set $E - F = \{ u - v : u \in E, \ v \in F \}$ is non-empty and bounded above, and:
$$
\sup(E - F) = \sup E - \inf F.
$$
Proof. Let $a = \sup E$ and $b = \inf F.$ Then $u - v \leqslant a - b$ for all $u \in E$ and $v \in F.$ On the other hand, for all $\varepsilon > 0,$ there exist $u \in E$ and $v \in F$ such that $u > a - \frac\varepsilon2$ and $v < b + \frac\varepsilon2,$ whence $u - v > a - b - \varepsilon.$ Therefore $E - F$ is bounded above, with $\sup(E - F) = a - b.$ $\ \square$


text:
Q: Java - Give certain bitpattern positions, a certain value If you have an integer-variable named i, that contains a bitpattern...
How can you make a Java-structure that gives every bit that's in an odd position, 1 as value?

A: How about:
for(int x = 0; x < 32; x+=2) {
    i |= 1 << x;
}

or even:
i |= 0x55555555;

A: You may use a similar method like this to set or unset bits:
public static int setBitOnInt(int i, int bit, boolean set) {
    if (set) {
        return i | (1 << bit);
    } else {
        return i & ~(1 << bit);
    }
}

To set only odd bits you'd have to call:
int myBitMask = 0;
for (int i=0; i<32; i+=2) {
    myBitMask = setBitOnInt(myBitMask, i, true);
}


text:
Q: How can I change a button color without changing all the other buttons color? Let say I have 100 buttons or radio buttons on a grid and some of them are clicked/checked and present a certain color (let say green). How can I change the color of the next button I click on without changing the color of the buttons already checked? Cause, I'm a bit lazy defining a hundred different classes on my .css file for each button... :p
PS: I work on vue.js

A: You can manipulate the css just like in the below approach

var app = new Vue({
 el:"#app",
 methods: {
  setColor(event) {
   console.log(event.target);
   for(let buttonEle of event.currentTarget.children) {
    buttonEle.style.color = 'black';
    buttonEle.style.background = 'white';
    buttonEle.boxShadow = 'none';
    event.target.border = 'black';
   }
   event.target.style.color = 'white';
   event.target.style.background = 'blue';
  }
 }
});

    <button>A</button>
    <button>B</button>
    <button>C</button>
    <button>D</button>


text:
Q: python sqlAlchemy: sqlalchemy.exc.ArgumentError when I change the class location When I use sqlAlchemy to read data from mysql DB, it work when my class and the search code are in the same py file just like this:
class odd_basis(Base):
    __tablename__ = 'odd_basis'

    NO = Column(Integer, primary_key=True)
    LEAGUE = Column(String(20))
    TIME   = Column(String(20))

engine = create_engine("......")
session = sessionmaker(bind=engine)
DBsession = session()
basis_data = DBsession.query(odd_basis).filter(odd_basis.NO=='16039').all()

when I put the class definition in another py file, then use the sys.path.append to import, then it will have this error:
sqlalchemy.exc.ArgumentError: SQL expression object or string expected, got object of type  instead
my main code:
import sys
sys.path.append("~/analysis/table_class.py")
engine = create_engine("......")
session = sessionmaker(bind=engine)
DBsession = session()
basis_data = DBsession.query(odd_basis).filter(odd_basis.NO=='16039').all()

table_class.py:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Numeric, ForeignKey, UniqueConstraint, Index

Base = declarative_base()
class odd_basis(Base):
    __tablename__ = 'odd_basis'

    NO = Column(Integer, primary_key=True)
    LEAGUE = Column(String(20))
    TIME   = Column(String(20))

A: Sys.path.append does not import anything. It just adds to your search path. You need to import your class from there:
from table_class import odd_basis

and so forth.
Hannu


text:
Q: All views look like they're selected I don't know what I did in Xcode, but suddenly all views look like they're selected with those blue borders. How can I disable that?

A: In Editor
  ---->Canvas
Check Show Constraints and
Uncheck Show Bounds Rectangles