text:
Q: Why is NEAR requesting authorization when I call a change method on the contract? I have a change method on my NEAR AssemblyScript Contract, which I'm calling from my front end (browser) code. The user is already signed in and can read the view methods on the contract. It's only after trying to call the change method that the user is prompted with the NEAR Wallet requesting authorization.
How can I call the change method without receiving the prompt to request permission again?

A: I'm answering my own question, because I spent some time trying to figure it out.
When I was calling the function requestSignIn() on the wallet, I also had to specify the contract name.
import {
  connect,
  WalletConnection
} from 'near-api-js';

...

const near = await connect(nearConfig);
const wallet = new WalletConnection(near);
wallet.requestSignIn('dev-xxxx-yyyy'); // Need to pass the correct contract name to be able to call change methods on behalf of the user without requesting permission again

A: You can also see some examples here:

*

*basic github.com/Learn-NEAR/starter--near-api-js

*advanced github.com/Learn-NEAR/starter--near-api-js
There's basically 2 interfaces here:
// pass the contract name (as you did)
wallet.requestSignIn('dev-1634098284641-40067785396400');

// pass an object with contract and empty list of methods
wallet.requestSignIn({
  contractId: 'dev-1634098284641-40067785396400',
  methodNames: []
});

// add a list of methods to constrain what you can call
wallet.requestSignIn({
  contractId: 'dev-1634098284641-40067785396400',
  methodNames: ['write']
});


text:
Q: reading file by pickle module good afternoon!
saving list(dict(),dict(),dict()) struct with pickle module, but when reading I get: <class 'function'>, and <function lesson at 0x00000278BA3A0D30>
what am I doing wrong?
def lesson(user, date):
    with open(user+"_"+date+".data", 'wb') as file:
        pickle.dump(lesson, file)
    file.close()

def read(user, date):
    with open(user+"_"+date+".data", 'rb') as file:
        lesson = pickle.load(file)
    file.close()
    return(lesson)

I am using python 3.10.7

A: "saving list(dict(),dict(),dict()) struct with pickle module". No, you're not. You're saving the lesson function. See line 3 of your code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to transfer the integer values from one Java file to other Java file in Android? I am trying to transfer an integer value from one Java file to other file. I am, however, having difficulties. This is MainActivity.java file:
    package com.e.krishna;
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    public class MainActivity extends Activity
{
    protected static final String KEY = null;
    TextView display1;
    TextView display2;
    Button btn;
           int counter=0;
           int a;
    public void onCreate( Bundle a1) {
        super.onCreate(a1);
        setContentView(R.layout.activity_main);
        display1=(TextView)findViewById(R.id.tView);
        display2=(TextView)findViewById(R.id.tView1);
                btn=(Button)findViewById(R.id.button1);
                btn.setOnClickListener(new View.OnClickListener()
{
                 public void onClick(View v)     {
                         Intent inf=newIntent(MainActivity.this,Images.class);
                                startActivity(inf);
                                                                            }
                Bundle bundle = getIntent().getExtras();
        {
            a = bundle.getInt("a");
            display1.setText("your count is "+a);
        };
    });
}
}

This is Images.java
    package com.e.hare_krishna;
    import android.app.Activity;
    import android.content.Intent;
   import android.os.Bundle;
   import android.view.View;
     import android.widget.Button;
    import android.widget.TextView;
  public class Images extends Activity
{
   private static final String KEY = null;
   Button btn;
   public static int a;
  int i;
  TextView display1;
  public void onCreate(Bundle a1)
 {
    super.onCreate(a1);
    setContentView(R.layout.image);
    display1=(TextView)findViewById(R.id.tView1);
    btn=(Button)findViewById(R.id.btn);
    a=0;
    btn.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
                    a++;
            display1.setText("your count is "+a);

     }
    });

    Intent intent=new Intent(this,MainActivity.class);
    intent.putExtra(KEY,  a);
    startActivity(intent);

}
}

I tried this code but the 'a' value does not get displayed. From the second Java file the value of 'a' should be passed to mainactivity and get displayed.
Thank you in advance.

A: In Main Activity Try this :-
int a = getIntent.getIntExtra(KEY, 0);
Should work..

A: You declare a key private static final String KEY = null; and then you store a value like this intent.putExtra(KEY,  a);
But you have to use the same key like this :
1) store your value
Intent intent=new Intent(this, NewActivity.class);
intent.putExtra("MY_KEY",  a);
startActivity(intent);

2) retrieve your value under NewActivity.class
Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("MY_KEY");
}

A: private static final String KEY = "val";

//Pass like this
Intent intent=new Intent(this,MainActivity.class);
intent.putExtra(KEY,  a);
startActivity(intent);

//Get like this

Intent intent = getIntent();
int a = intent.getIntExtra("val", 0);

A: Your KEY is null, you should give it a String value in both activities (make sure it's the same in both)
for example KEY = "number" or any string you want


text:
Q: Procedure to check for non duplicate rows in table before insert (Oracle) I wrote a procedure in oracle(using guidance from here) to check for any duplicate values in table so that countries with the same countryId should return some error message as countryId is PK in countries table.Here it is:
   CREATE OR REPLACE PROCEDURE add_values4 (c_cntry_id IN OUT COUNTRIES.COUNTRY_ID%TYPE,
                                       c_cntr_name IN COUNTRIES.COUNTRY_NAME%TYPE,
                                       c_rgn_id IN COUNTRIES.REGION_ID%TYPE)
IS
DECLARE
   outputValue CHAR  := 'JJ';
BEGIN
  INSERT INTO countries(COUNTRY_ID, COUNTRY_NAME,REGION_ID)
    values (user_seq.nextval, c_cntr_name,c_rgn_id);
  c_cntry_id := user_seq.currval;
EXCEPTION
  WHEN dup_val_on_index
  THEN
    c_cntry_id := null;
END;
/

However,when I try to create this procedure,it gives me error PLS-00103.Any idea what could be wrong? (Anything in syntax?).I have been trying since 48 hours but with not much success.Appreciate some help here.
Tx in advance

A: You've got a semi-colon after the list of parameters instead of as. Try:
CREATE OR REPLACE PROCEDURE add_vals (c_cntry_id OUT COUNTRIES.COUNTRY_ID%TYPE,
                                       c_cntr_name IN COUNTRIES.COUNTRY_NAME%TYPE,
                                       c_rgn_id IN COUNTRIES.REGION_ID%TYPE)
AS
BEGIN
  INSERT INTO countries(COUNTRY_ID, COUNTRY_NAME,REGION_ID)
    values (user_seq.nextval, c_cntr_name,c_rgn_id)
  Returning country_id into c_cntry_id;
EXCEPTION
  WHEN dup_val_on_index
  THEN
    c_cntry_id := null;
END;
/

Note also that I have used the returning clause to set the value of c_cntry_id.

Looking at your edited code, the issue now is that you have got DECLARE in your procedure between the IS and the BEGIN
Also, since you're using a sequence value to insert rows into the table - and, hopefully, this is the only point at which rows could be inserted - that shouldn't ever result in a dup_val_on_index exception.
I've knocked up a test case that will create the dup_val_on_index due to an additional unique constraint on the country_name column, and also shown you two ways of creating the code - as a procedure and as a function, as well as demonstrating how to call them:
drop table countries;
drop sequence user_seq;
drop procedure add_country_pr;
drop function add_country_fn;

create table countries (country_id integer primary key,
                        country_name varchar2(50) unique not null,
                        region_id integer);

create sequence user_seq
  start with 1
  maxvalue 99999
  minvalue 1
  nocycle
  cache 20
  noorder;

create or replace procedure add_country_pr (c_cntry_id out countries.country_id%type,
                                            c_cntr_name in countries.country_name%type,
                                            c_rgn_id in countries.region_id%type)
is
begin
  insert into countries (country_id, country_name,region_id)
  values (user_seq.nextval, c_cntr_name,c_rgn_id)
  returning country_id into c_cntry_id;
exception
  when dup_val_on_index
  then
    c_cntry_id := null;
end add_country_pr;
/

create or replace function add_country_fn (c_cntr_name in countries.country_name%type,
                                           c_rgn_id in countries.region_id%type)
return integer
is
  v_cntry_id integer;
begin
  insert into countries (country_id, country_name,region_id)
  values (user_seq.nextval, c_cntr_name,c_rgn_id)
  returning country_id into v_cntry_id;

  return v_cntry_id;
exception
  when dup_val_on_index
  then
    return null;
end add_country_fn;
/

set serveroutput on;

-- anonymous block used to call the above procedure/function
declare
  v_cntry_id integer;
begin
  add_country_pr (c_cntry_id => v_cntry_id, -- variable to hold the value of the out parameter
                  c_cntr_name => 'GBR',
                  c_rgn_id => 1);
  commit;

  dbms_output.put_line('add_country_pr 1st call, country_id = "'||v_cntry_id||'"');

  add_country_pr (c_cntry_id => v_cntry_id, -- variable to hold the value of the out parameter
                  c_cntr_name => 'GBR',
                  c_rgn_id => 1);
  commit;

  dbms_output.put_line('add_country_pr 2nd call, country_id = "'||v_cntry_id||'"');

  v_cntry_id := add_country_fn (c_cntr_name => 'USA',
                                c_rgn_id => 2);
  commit;

  dbms_output.put_line('add_country_fn 1st call, country_id = "'||v_cntry_id||'"');

  v_cntry_id := add_country_fn (c_cntr_name => 'USA',
                                c_rgn_id => 2);
  commit;

  dbms_output.put_line('add_country_fn 2nd call, country_id = "'||v_cntry_id||'"');
end;
/

add_country_pr 1st call, country_id = "1"
add_country_pr 2nd call, country_id = ""
add_country_fn 1st call, country_id = "3"
add_country_fn 2nd call, country_id = ""

A: You have a semicolon after your parameter block, and you are missing your IS or AS clause:
CREATE OR REPLACE PROCEDURE add_vals (c_cntry_id OUT COUNTRIES.COUNTRY_ID%TYPE,
                                       c_cntr_name IN COUNTRIES.COUNTRY_NAME%TYPE,
                                       c_rgn_id IN COUNTRIES.REGION_ID%TYPE)
IS
BEGIN
  INSERT INTO countries(COUNTRY_ID, COUNTRY_NAME,REGION_ID)
    values (user_seq.nextval, c_cntr_name,c_rgn_id);
  c_cntry_id := user_seq.currval;
EXCEPTION
  WHEN dup_val_on_index
  THEN
    c_cntry_id := null;
END;
/


text:
Q: Filter DataFrame based on Max value in Column - Pandas Using pandas, I have a DataFrame that looks like this:
Hour            Browser     Metric1   Metric2   Metric3
2013-08-18 00   IE          1000      500       3000
2013-08-19 00   FF          2000      250       6000
2013-08-20 00   Opera       3000      450       9000
2001-03-21 00   Chrome/29   3000      450       9000
2013-08-21 00   Chrome/29   3000      450       9000
2014-01-22 00   Chrome/29   3000      750       9000

I want to create an array of browsers which have a maximum value of Metric1 > 2000.  Is there a best way to do this?  You can see basically what I am trying to do with the code below.
browsers = df[df.Metric1.max() > 2000]['Browser'].unique()

A: You could groupby Browser and take the max:
In [11]: g = df.groupby('Browser')

In [12]: g['Metric1'].max()
Out[12]:
Browser
Chrome/29    3000
FF           2000
IE           1000
Opera        3000
Name: Metric1, dtype: int64

In [13]: over2000 = g['Metric1'].max() > 2000

In [14]: over2000
Out[14]:
Browser
Chrome/29     True
FF           False
IE           False
Opera         True
Name: Metric1, dtype: bool

To get out the array, use this as a boolean mask:
In [15]: over2000[over2000].index.values
Out[15]: array(['Chrome/29', 'Opera'], dtype=object)


text:
Q: Error 310 - when I try to access the Steam market Whenever I try to access the Steam Community Market, it just shows

Error -310 (unknown)

Googling got me nowhere. Has anyone heard of this error/know how to fix it?

A: Steam's errors usually correspond to HTTP status codes. While there are some that may indicate a problem on your end (like a connection failure or expired authentication) this one is a bit special (it's not usually listed with the "standard" HTTP codes) and means "too many redirects". It hints at a server-side problem, for example a programming mistake.

A: I realise this is an old post but just in case someone finds this thread with the same question:
I've had this happen on two different occasions while browsing the Steam Store on my desktop application and both times I was able to get around it by searching for the game with the Steam Store on my web browser and after you click play/buy now click the option "Yes, I have steam installed" and it opens steam and downloads just fine.


text:
Q: Flex/AIR Mobile: DateSpinner Component Performance Issues I am using FB 4.6/AIR to develop a Mobile App for Android. I have spent the better part of an evening narrowing down why my View is taking so long to load. Low and behold I discovered that it is the DateSpinner component. I have tested it on a Galaxy SII as well as a Galaxy Nexus and both performance is identical.... slow. Additionally, I tweaked/simplified Devgirl's DateSpinner example to see if I would get the same results as I did with my APP and I did. I posted the the project file/FXP here
Thanks, in advance.
Edit: Added Code
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" title="DateSpinner Sample">
<fx:Script>
    <![CDATA[
        import spark.components.calendarClasses.DateSelectorDisplayMode;
    ]]>
</fx:Script>

<s:HGroup verticalAlign="middle">
</s:HGroup>
<s:Label text="{dt.selectedDate}"/>
<s:DateSpinner id="dt" x="81" y="138" displayMode="{rg.selectedValue}"
               maxDate="{new Date(2011,11,31)}" minDate="{new Date(2011,06,01)}"
               minuteStepSize="10" selectedDate="{new Date(2011,11,31)}"/>
</s:View>


text:
Q: How can we validate JWT signature in Angular 6 Need help/steps to validate JWT token in Angular 6.o manually to validate or verify JWT Signature.

A: To verify the Azure AD token, you may refer to the official tutorial: Validating the signature.
First, you need to get the public key. In the header part of jwt token, you can get the kid.
Then you can get public keys from:
https://login.microsoftonline.com/common/discovery/v2.0/keys

or
https://login.microsoftonline.com/{tenant_id}/discovery/v2.0/keys

After that,  you can use the public key to verify the signature.
Specifically, you can use jsonwebtoken or jose in Node.JS to verify the signature.


text:
Q: Python: Prevent decoding of bytearray while printing The following code shows that printing an bytearray makes it decode ASCII characters whenever possible.
>>> a = bytearray([0x0D, 0x48, 0x69])
>>> print(a)
bytearray(b'\rHi')

Is there an easy way to prevent the decoding of bytes and instead produce a result like this?
bytearray(b'\x0d\x48\x69')

A: Here is a solution (but there's gotta be a more organic way of doing this)!
a = bytearray([0x0D, 0x48, 0x69])
print(map(hex, a))

A: I am afraid you have to build it by hand:
def dump(x):
    return ''.join([type(x).__name__, "('",
                    *['\\x'+'{:02x}'.format(i) for i in x], "')"])

You can then do:
>>> a = bytearray('\rHi', 'ascii')
>>> print(dump(a))
bytearray('\x0d\x48\x69')


text:
Q: How do you include multiple external javascript files without increasing http requests I have a website that has multiple external javascript files, I would like to reduce these to increase performance.
Some of the external scripts include typekit, google analytics, linkedin js api, twitter api and some others. With these third party external javascript files what is the best approach to including them without increasing HTTP requests, keep in mind some of these libraries like to be loaded in the head tag ( typekit ).
I have tried downloading, concatenating and hosting them locally but they don't seem to play nice with my minified javascript or with other vendors javascript. Is there a specific approach to this problem.
I have looked into libraries like requirejs but I'm not sure if this would solve this problem.

A: Don't aggregate them!
Actually even if you have more HTTP requests the content is added to the browser cache and stay there as they never change.
Moreover, even when you come on the website the first time, the file could be already in the cache since it could have been loaded from another website.
Finally, keep in mind that your own script is subject to change each time you release a new version, and consequently you will need to evict the script from the browser cache. External scripts won't change each time you release a new version, so you will keep them in the browser cache, which is possible only is they are not aggregated with your own scripts.


text:
Q: What are the manifolds whose Curvature tensor has a globally vanishing $k$th order covariant derivative Let $(M,g)$ be a boundaryless Riemannian manifold whose curvature tensor have the property that there exists $k\geq 2$ such that $\nabla^k R\equiv0$. What is known about such Riemannian manfiolds ? Is there a classification ?
I vaguely remember that I came (a long time ago) across a paper that claims that if $(M,g)$ is also known to be irreducible then we must have $\nabla R\equiv 0$. However, I cant find this paper anymore and I m starting to doubt myself so I decided to ask the question here.

A: In fact, the result is true for any complete Riemannian manifold as I remember. The result was proved by Katsumi Nomizu and Hideki Ozeki Here
Here 2 and  here 3 you may find many related interesting results.


text:
Q: The "end" statement in Ruby I have a if, else, and else if statement, and I'm using the official documentation for Ruby, but I can't figure out where to put my end statements.
Here is the code:
class Menu
  def principal_menu
    user_input = gets
    #On supprime le \n du retour à la ligne
    user_input = user_input.chomp
    if user_input == "3"
      exit
    else if user_input == "1"
      if File.exists?("accounts.txt")
    else
      File::new("accounts.txt","w+")
    end

    else if user_input == "2"
      new_account = account.new
    end
  end
end

The error is: AccountManager.rb:63: syntax error, unexpected end-of-input, expecting keyword_end
Note: Line 63 is the very end of the file.
Could some one help a newbie in Ruby :D
Thanks!

A: Here's your problem:
class Menu
    def principal_menu
        user_input = gets
        #On supprime le \n du retour à la ligne
        user_input = user_input.chomp
        if user_input == "3"
            exit
        else if user_input == "1"
            if File.exists?("accounts.txt")
                # you aren't doing anything here
            else
                File::new("accounts.txt","w+")
            end
        else if user_input == "2"
            new_account = account.new
        end
    end
end

In Ruby, you use elsif instead of else if. This can stump new-to-Ruby people.
This is correct:
class Menu
    def principal_menu
        user_input = gets
        #On supprime le \n du retour à la ligne
        user_input = user_input.chomp
        if user_input == "3"
            exit
        elsif user_input == "1"
            if File.exists?("accounts.txt")

            else
                File::new("accounts.txt","w+")
            end

        else user_input == "2"
            new_account = account.new
        end
    end
end


text:
Q: Azure Function on consumption plan cold start can be up to 30 minutes I have an azure function v3, written in C#, using the class library approach.

*

*The function is triggered by blob storage.

*The function is using a Consumption plan.

The problem is that cold starts can be as long as 30 minutes! I have consulted the documentation from this link
But there is no specific figures with regards to expected cold start timings.
An interesting observation is that if I navigate to the portal, and hit Refresh button:

Then the function gets immediately triggered.

*

*Is this normal, expected behavior?

*Could you please point me to any docs explicitly stating that ~0-30-50mins is OK for cold starts on Consumption Plan?

A: Consumption plan is what azure calls "serverless" model; what it means -

your code reacts to events, effectively scales out to meet whatever load you're seeing, scales down when code isn't running, and you're billed only for what you use.

Cold start is nothing but the

phenomenon that applications which haven't been used take longer to start up.

When you're using the Consumption plan, instances of the Azure Functions host are dynamically added and removed based on the number of incoming events.
If you've a "heavy-weight" code written and deployed on consumption plan which takes lot of memory and resources to get loaded to execute it may take more time such as your case.
When you hit the refresh button from portal - The Functions runtime resets, and any required extensions are loaded onto the worker and gets loaded into the memory. That's why it reduces most of the latency.
To understand more about the cold-start in azure serverless model & how you can minimize that please refer here - Understanding serverless cold start
To reduce it more; you can have a warmup request which will hit based on time interval and you'll have your function always loaded in memory.

A: In general cold starts occur when your function hasn't run in ~20 minutes
To avoid it, if you run your code frequently enough that it stays warm cold starts won't occur (unless if you scale out)
A common way for doing this is making a simple "invoker" helper function which calls your function every 5/10 minutes
if that doesn't fit for your solution and if you're ok to pay slightly more, you can run your Function in the Dedicated plan.
Regarding SLA on Consumption Plan:

"Unavailable Executions" is the total number of executions within
Total Triggered Executions which failed to run. An execution failed to
run when the given Function App history log did not capture any output
five (5) minutes after the trigger is successfully fired.

A: That is not correct, you're referring to a timeout duration - which is not equivalent to a cold start. If your function takes that long, its cause there was an exception/error (I don't mean an exception in code). No where in any documentation (even by microsoft) does it say that cold starts takes 30 mins.
If cold starts are taking too long (>~1 min) and you're sure there arent any startup errors - break your functions down and trigger those functions parallelly (where possible). Application Insights is your friend here.
Lastly, there are no exact figures - its such a per use basis. There are many things that effects execution time - which might lead one to blame cold starts, rather than the responsibilities & dependencies of a function. With Functions/Lambda, its not just "code like any other API", there is also some architectural changes.
What I would definitely like to know is the performance difference (esp cold start) if the code is published to Azure Function as a code vs in a docker (https://learn.microsoft.com/en-us/azure/devops/pipelines/targets/function-app-container?view=azure-devops&tabs=yaml). I'll try to find some time to perform a good experiment on this and report back (no promises).
Further Readings -

*

*Crude Cold Start Timing Study: https://mikhail.io/serverless/coldstarts/azure/ (he has performed the same experiment with AWS Lambda)

*Another good comparative study of Lambda & Functions: https://azurefromthetrenches.com/comparative-performance-of-azure-functions-and-aws-lambda/

*https://azure.microsoft.com/en-in/blog/understanding-serverless-cold-start/
EDIT:
Though this is slightly old Github Issue Thread, the maximum reported cold start time on this thread is about 2 mins; seems the average is somewhere around 20s. Note the Engineering Manager in Microsoft Azure (David Ebbo) at the time mentions that it shouldn't take longer than 10s for trivial functions.
https://github.com/Azure/azure-functions-host/issues/838
EDIT 2: The 30 mins timeout duration is for non-consumption plans (5mins for consumption plan), so I assume you're planning to use non-consumption plans, in which case you're not going to have cold start issues. The other plans keep the functions warm.
Please go through "Overview Of Plans" in the document you linked - https://learn.microsoft.com/en-us/azure/azure-functions/functions-scale#overview-of-plans

A: No this is not normal. A cold start shouldn't take too long. Here  is a recent performance test that should give you your answer.


text:
Q: Hide elements who have one of the selected classes per checkbox (jQuery) I have some checkboxes and want to hide all elements who have the checked class. It's some kind of meals with incredients and I want the user to be able to hide all menus with e.g. "cheese".
I tried with "toggle" but there is a problem with it when I click further elements (thought it would be an easy task):
$(document).ready(function(){
  $('input[type="checkbox"]').click(function(){
    var inputValue = $(this).attr("value");
    $("." + inputValue).toggle();
  });
});

here is a fiddle:
Hide elements who have class

A: What you're looking for is probably something more along the lines of this. (Explanation/comments included in the code)
https://jsfiddle.net/p7Lvo2fd/3/
$(document).ready(function(){
  $('input[type="checkbox"]').click(function(){

    //Show all articles
    $("article").show();

    //Get checked boxes
    var $checkedBoxes = $("input[type=checkbox]:checked");

    //For each checked box, hide the associated articles
    $checkedBoxes.each(function() {
        $("article").filter("." + $(this).val()).hide();
    });

  });
});

Or if you prefer a snippet:

$(document).ready(function() {
  $('input[type="checkbox"]').click(function() {
    $("article").show();
    var $checkedBoxes = $("input[type=checkbox]:checked");
    $checkedBoxes.each(function() {
      $("article").filter("." + $(this).val()).hide();
    })
  });
});
article {
  color: #fff;
  padding: 10px;
  margin-top: 10px;
  font-size: 20px;
  font-family: Roboto;
  background: tomato;
}

  <input type="checkbox" name="incredientsCheckbox" value="dynamite"> dynamite
  <input type="checkbox" name="incredientsCheckbox" value="chocolate"> chocolate
  <input type="checkbox" name="incredientsCheckbox" value="strawberry"> strawberry
  <input type="checkbox" name="incredientsCheckbox" value="cheese"> cheese

classes: dynamite - strawberry

classes: strawberry - chocolate

classes: strawberry

classes: cheese

classes: cheese - dynamite - strawberry

For a more clear implementation, you can also see this example: https://jsfiddle.net/p7Lvo2fd/5/
It changes the background instead of hiding the items, so it's easier to test.

A: Add to CSS these switches
.dynamite_hide {display: none}
.strawberry_hide {display: none}
.chocolate_hide {display: none}
.cheese_hide {display: none}

Change your click handler to this
$(document).ready(function(){
 $('input[type="checkbox"]').click(function(){
    var val = $(this).attr("value")
    if($(this).is(':checked'))
      $("." + val).addClass(val+"_hide")
    else
      $("." + val).removeClass(val+"_hide")
  });
});

A: You are going to want to do this on the change, not the click event - that way if you change via script it works. If you have preset values, you can trigger the change on startup.
$(document).ready(function() {
  $('input[type="checkbox"]').on('change', function() {
    var checks = $('input[type="checkbox"]:checked');
    //show all then hide checked stuff
    $('article').show();
    checks.each(function(index, item) {
      $('article').filter(function() {
        return $(this).hasClass($(item).val());
      }).hide();// hit DOM once, hide them
    });
  }).trigger("change");
});

Smaller filter, but does same thing:
$(document).ready(function() {
  $('input[type="checkbox"]').on('change', function() {
    var checks = $('input[type="checkbox"]:checked');
    //show all then hide checked stuff
    $('article').show();
    checks.each(function(index, item) {
      $('article').filter("."+item.value).hide();
    });
  });
});

Most efficient:
Now that we understand the concept, we can get a class list as a selector list and use that, saving hitting the DOM on each class found checked:
$(document).ready(function() {
  $('input[type="checkbox"]').on('change', function() {
    var classes = $('input[type="checkbox"]:checked').map(function() {
      return "." + this.value;
    }).get().join(",");
    $('article').show().filter(classes).hide();
  }).trigger("change");
});


text:
Q: How to convert Blob back into a file with nodejs? I'm currently working on an application that allows the user to upload a file which gets sent to a express server that then converts that file into a bytearray that I can then store somewhere else.
However, I need to be able to convert this bytearray back into a file and send it back to the user. This is my current code in the express API:
app.post("/upload", async (req, res) => {
  const file = req.files.file;
  const filePath = "divali";

  file.mv(filePath, async (err) => {
    const nfile = fs.readFileSync(filePath);
    let fileData = nfile.toString("hex");
    let result = [];
    for (var i = 0; i < fileData.length; i += 2)
      result.push("0x" + fileData[i] + "" + fileData[i + 1]);

    console.log(result);

    var pfile = new Blob([result], { type: "application/pdf" });
    // var fileURL = URL.createObjectURL(pfile);
    console.log(pfile);

    pfile.lastModifiedDate = new Date();
    pfile.name = "some-name";

    console.log(pfile);
  });
});


text:
Q: what's the difference between return/echo json_encode in php maybe this is a simple and stupid question.
As we know, echo  just print the variable out, and in a php function return statnds for return something to the function invoker.
I notice someone use echo json_encode while others using return json_encode,
I return something to jquery, and using echo/return are both ok.
But when I find that almost everyone using echo json_encode, and why ?
Thanks.

A: return will not give any response in case of using  ajax where as echo will give you the response.If you are using server side scripting only the probably you dont need to echo it.Instead of it you can use return.
Look at this example and the way which the functions are called
function  myFun($value){
  return 'This is the value '.$value;
}

echo myFun(10);//Output This is the value 10
myFun(10);//Will not give you any output

function  myFun($value){
  echo 'This is the value '.$value;
}

myFun(10);//Output This is the value 10
echo myFun(10);//Output This is the value 10

In case of ajax
$.ajax({
        url     :   'mypage.php',
        type    :   "POST",
        success :   function(res){
          alert(res);
        }
 });

In mypage.php
 echo 'Hello';//This will send Hello to the client which is the response

but
return 'Hello';//Will not send anything.So you wont get any response

A: In standard PHP code, the output of echo is captured by the webserver and returned as part of the reponse.
return simply returns the value to the parent function.  The parent function can do whatever it likes with the returned data including echo.
consider:
function return_some_text(){
   return 'this text is returned';
}

function echo_some_text(){
   echo 'this text is echoed';
}

//does nothing
return_some_text();

//'this text is echoed' appears in the response
echo_some_text();

//'this text is returned' appears in the response because the return value is echoed.
echo return_some_text();

Remember, the return value of a function can be used in whatever way the caller sees fit.  This includes echoing if the caller sees fit.
When you see return json_encode(...) that means that the calling function is going to do something with the data before it is output to the server.

A: return will simply return the variable without echoing it, where as echo will echo it out when it is called. If you are using AJAX you are better off with echo

A: It depends the nature of php framework you are using
if you are using ajax and your framework does standard outputting by itself then, you can use return else you have to echo it by yourself


text:
Q: LINQ HAVING with OR condition Totally making this up to resemble something similar to what I'm working with:
Let's say I have a SQL table, which has Name, City, and FavoriteColor. I want to do a LINQ query (I prefer method syntax, where possible) that will group all the records in the table by Name and City. That would, of course, group all the records in the table on those two things by using the .GroupBy(...) LINQ extension method.
But, then I want to filter the resulting set down to some given values (i.e. where Name = Joe and City = Miami), which is done in LINQ by adding a .Where(...) method on a grouped set, resulting in SQL as a HAVING clause.
That's easy enough to do when you only have one value for each to filter on, but let's say the method with this query receives a list of names and cities to filter that result set on. (i.e. filter all those grouped records down to only those named "Joe" in "Miami", "John" in "Tampa Bay", et cetera).
Then, to make it even better, I need to get a count of each Name and City group's favorite color.
In SQL, this would look something like this:
SELECT Name, City, COUNT(FavoriteColor)
FROM People
GROUP BY Name, City
HAVING (Name = "Joe" AND City = "Miami") OR (Name = "John" AND City = Tampa Bay")

Note: that HAVING clause has an OR in between the two, which is what's killing me trying to get to work with LINQ. My LINQ is always stitching AND's together, instead of OR's.
As for the LINQ, what I have is:
public IList<ColorCount> GetFavoriteColorCount(IList<SearchValue> searchValues)
{
    var query = _context.People
                     .GroupBy(p => new
                     {
                         p.Name,
                         p.City
                     })
                     .Select(g => new
                     {
                         Name = g.Key.Name,
                         City = g.Key.City
                     });

    foreach (var searchValue in searchValues)
    {
        query = query.Where(r => r.Name == searchValue.Name && r.City == searchValue.City);
    }

    // TODO: Figure how to get the COUNT for Favorite Color mixed into all this, too.

    var result = query.ToList();
}

However, as mentioned earlier, this results in an AND between the HAVING values, instead of an OR, like I need. I know this because I'm using EF's .LogTo(...) method to output the complete SQL being generated and used. I grabbed that output and ran it against the database and, as expected, got 0 results. I manually changed the AND's to OR's and poof I have the results I expect.
Anyway, if I have a table that has, say, 10 "Joe" and "Miami" record combinations, which 7 have a favorite color of yellow and 3 have green. And, it also has 4 "John" and "Tampa Bay" combinations with 2 blue and 2 red for colors, I believe I would have 4 records in the final list that look something like this:
{ "Joe", "Miami", "Yellow", 7 },
{ "Joe", "Miami", "Green", 3 },
{ "John", "Tampa Bay", "Blue", 2 },
{ "John", "Tampa Bay", "Red", 2 }

The 2 questions:

*

*How do I force an OR in the HAVING clause when iterating over the list of search values that get passed into the method?

*How do I also get a COUNT of the Favorite Colors?


text:
Q: Does the avroserde in hive allow to update or delete records? I have a table in hive which is created using ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.avro.AvroSerDe'.
Trying to update a record but I receive the following error message:
FAILED: SemanticException [Error 10294]: Attempt to do update or delete using transaction manager that does not support these operations. (state=42000,code=10294)

It seems that AvroSerDe does not support ACID transaction but I can't find any info about that.

A: Hive transactions doesn't support Avro file formats as of latest Hive release. And it's currently integrated to work with only ORC file formats.
According to Hive documentation "Only ORC file format is supported in this first release.  The feature has been built such that transactions can be used by any storage format that can determine how updates or deletes apply to base records (basically, that has an explicit or implicit row id), but so far the integration work has only been done for ORC."
You can find more information about Hive transactions here


text:
Q: Android Studio 3 beta 2 ClassNotFound in kotlin unit tests I am using Android Studio 3.0 beta 2, converted an existing project to gradle plugin 3.0.0-beta2
When I try to run an existing unit test written in kotlin I get 'java.lang.NoClassDefFoundError: com/other/domain/CollectionItem'
The test itself is very simple:
import org.junit.Test

import org.junit.Assert.*

class CollectionViewModelTest {
    @Test
    fun getItemsWithManyItemsWillReturnCollectionItemViewModels() {
        val collectionItems = listOf(CollectionItem(42, "Item1", CollectionItemType.COLLECTION, ""), CollectionItem(43, "Item2", CollectionItemType.COLLECTION, ""), CollectionItem(44, "Item3", CollectionItemType.COLLECTION, ""))
        val collection = Collection(45, "Home", "Home collection", collectionItems, 42)
        val collectionViewModel = CollectionViewModel(collection)

        assertTrue(collectionViewModel.items.first().isFirst)
        assertFalse(collectionViewModel.items.first().isLast)

        assertFalse(collectionViewModel.items[1].isFirst)
        assertFalse(collectionViewModel.items[1].isLast)

        assertTrue(collectionViewModel.items.last().isLast)
        assertFalse(collectionViewModel.items.last().isFirst)
    }
}

It works when I run it from the terminal using ./gradlew
Any ideas why this can happen?
Edit:
This seems to happen only when the test requires classes from other library projects.
In this case CollectionItem is part of another library in the same project and it's included in the gradle file via implementation project(':domain')
Edit
It might also be worth mentioning that domain module is pure java
Edit
Figured out the problem is when the library (domain) has classes written in kotlin, those classes will throw NoClassDefFoundError in unit test's only.


text:
Q: ?_method=DELETE not working with Express/Node app? I'm taking Colt Steele's Web development course and I've racked my brain trying to figure this one out.
Here's the error I'm getting when I try to delete a blog post:
Cannot DELETE /blogs/587445324a978708968f451a?_method=DELETE

and here's the code for the app.js:
var bodyParser      =   require("body-parser"),
    methodOverride  =   require("method-override"),
    mongoose        =   require("mongoose"),
    express         =   require("express"),
    app             =   express();

//APP CONFIG
mongoose.connect("mongodb://localhost/restful_blog_app");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride("_method"));

...

// DELETE ROUTE
app.delete("/blog/:id", function(req , res){
    Blog.findByIdAndRemove(req.params.id, function(err){
        if(err){
            res.redirect("/blogs");
        } else {
            res.redirect("/blogs");
        }
    });
});

Here's the code for show.ejs:
<% include ./partials/header %>

<%= blog.title %>

            <img class="ui centered rounded image" src="<%= blog.image %>">

                <%= blog.created.toDateString() %>

<%- blog.body %>

            <form action="/blogs/<%= blog._id %>?_method=DELETE" method="POST">
                <button class="ui red basic button">Delete</button>
            </form>

<% include ./partials/footer %>


text:
Q: How to create customized bins in python I would like to create bins for CUSTOMER_AGE in my data frame using the pandas cut function. I tried using the code below:
bins = [0,20,25, 30, 35, 40,45,50,55, 60,150]
labels = ['0-20yrs', '21-25 yrs', '26-30 yrs', '31-35 yrs','36-40 yrs',
           '41-45 yrs', '46-50 yrs','51-55 yrs', '56-59 yrs', '> 60yrs']
df['BINS'] = pd.cut(df.CUSTOMER_AGE, bins, labels = labels,include_lowest = True)

This is the output i got:
CUSTOMER_AGE               BIN
 20                      0-20 yrs
 38                      36-40 yrs
 58                      56-59 yrs
 60                      56-59 yrs
 60                      56-59 yrs
 72                      > 60 yrs
 61                      > 60 yrs
 60                      56-59 yrs
 80                      > 60 yrs

I would like to know why only customers who are 60 years old fall under the '56-59 yrs' bin instead of '> 60yrs'.
But customers who are older than 60 years old fall in the correct bin which is '>60 yrs'

A: I think you need right=False in cut for change closed='right' to closed='left':

right : bool, default True
Indicates whether bins includes the rightmost edge or not. If right == True (the default), then the bins [1, 2, 3, 4] indicate (1,2], (2,3], (3,4]. This argument is ignored when bins is an IntervalIndex.

df['BINS'] = pd.cut(df.CUSTOMER_AGE, bins, labels = labels,include_lowest = True, right=False)
print (df)
   CUSTOMER_AGE        BIN       BINS
0            20   0-20 yrs  21-25 yrs
1            38  36-40 yrs  36-40 yrs
2            58  56-59 yrs  56-59 yrs
3            60  56-59 yrs    > 60yrs
4            60  56-59 yrs    > 60yrs
5            72   > 60 yrs    > 60yrs
6            61   > 60 yrs    > 60yrs
7            60  56-59 yrs    > 60yrs
8            80   > 60 yrs    > 60yrs

For better understanding is possible check Interval:

A closed interval (in mathematics denoted by square brackets) contains its endpoints, i.e. the closed interval [0, 5] is characterized by the conditions 0 <= x <= 5. This is what closed='both' stands for. An open interval (in mathematics denoted by parentheses) does not contain its endpoints, i.e. the open interval (0, 5) is characterized by the conditions 0 < x < 5. This is what closed='neither' stands for. Intervals can also be half-open or half-closed, i.e. [0, 5) is described by 0 <= x < 5 (closed='left') and (0, 5] is described by 0 < x <= 5 (closed='right').

and also check it without label parameter:
df['BINS_l'] = pd.cut(df.CUSTOMER_AGE, bins, include_lowest = True, right=True)
df['BINS_r'] = pd.cut(df.CUSTOMER_AGE, bins, include_lowest = True, right=False)
print (df)
   CUSTOMER_AGE        BIN          BINS_l     BINS_r
0            20   0-20 yrs  (-0.001, 20.0]   [20, 25)
1            38  36-40 yrs    (35.0, 40.0]   [35, 40)
2            58  56-59 yrs    (55.0, 60.0]   [55, 60)
3            60  56-59 yrs    (55.0, 60.0]  [60, 150)
4            60  56-59 yrs    (55.0, 60.0]  [60, 150)
5            72   > 60 yrs   (60.0, 150.0]  [60, 150)
6            61   > 60 yrs   (60.0, 150.0]  [60, 150)
7            60  56-59 yrs    (55.0, 60.0]  [60, 150)
8            80   > 60 yrs   (60.0, 150.0]  [60, 150)

So if you can see (60.0, 150.0] it means 60.0 < x <= 150.0 (60 values are excluded).
But in second column is [60, 150) it means 60 <= x < 150 (60 values are included).


text:
Q: Solving for a limit with an indeterminate fraction and square root of X I have a test tomorrow and there's one thing I found that I don't understand while reviewing. I've looked all over YouTube and Google and just can't find out how to work this problem:
$$ \lim_{x\to16} \frac{x-16}{4-\sqrt{x}} $$
It's obvious that it's indeterminate but I can't get any further than that.

A: We want to find
$$\lim_{x\to 16}\frac{x-16}{4-\sqrt{x}}.$$
Multiply "top" and "bottom" by $4+\sqrt{x}$. That is perfectly legitimate, we are multiplying our expression by $1$.  Since $(4-\sqrt{x})(4+\sqrt{x})=16-x$,
$$\lim_{x\to 16}\frac{x-16}{4-\sqrt{x}}=\lim_{x\to 16}\frac{(x-16)(4+\sqrt{x})}{(4-\sqrt{x})(4+\sqrt{x})}=\lim_{x\to 16}\frac{(x-16)(4+\sqrt{x})}{16-x}.$$
When $x \ne 16$, our expression simplifies to $-(4+\sqrt{x})$. This is because $x-16=(-1)(16-x)$. So our limit is equal to
$$\lim_{x\to 16} -(4+\sqrt{x}).$$
It is clear that this last limit is $-8$. If we want to mention fine details, $\displaystyle\lim_{x\to 16}\sqrt{x}=4$ because $\sqrt{x}$ is continuous at $x=16$.
Remark: Here is an alternative way of doing the same thing.  Note that for non-negative $x$,
$x-16=(\sqrt{x}-4)(\sqrt{x}+4)$.
Thus we are interested in
$$\lim_{x\to 16}\frac{(\sqrt{x}+4)(\sqrt{x}-4)}{4-\sqrt{x}}.$$
The rest is straightforward.

A: $$
\frac{{x - 16}}{{4 - \sqrt x }} = \frac{{(x - 16)(4 + \sqrt x )}}{{(4 - \sqrt x )(4 + \sqrt x )}} = \frac{{(x - 16)(4 + \sqrt x )}}{{16 - x}} =  - (4 + \sqrt x ) \to  - 8
$$
as $x \to 16$.


text:
Q: Excel Deployment - resizing and other component display issues I have been working on a project in excel for a while and am having problems deploying it to my client. We have (exactly) the same version of excel but when he opens the file the sizing of the components is all wrong. Please see the screenshots below:

When he turns on design mode or clicks and holds the vertical scroll bar, the issue corrects itself for the most part:

But when compared to the original there are still issues, such as the "Rental Start" and "Rental End" labels.

I should also mention that this problem is not isolated to this project. We had some issues with a different one, as well, but never made the connection between design mode and couldn't figure it out. I have tried my IntegralHeight property per a forum post somewhere, as well as double checking that my components are not set to size with cells. Does anyone know why this might be occurring? He has windows 8.1 and I have 7, if that could be the difference.
Note: All controls are ActiveX controls.


text:
Q: Username and password not accepting in jenkins job I am trying to create a jenkins CI pipeline and my code is written using jenkins DSL.Specifically,I am facing issue when  am passing username and password to dsl api for ZAP(zad attack proxy) by parameterized Build.The error getting displayed is:
java.lang.NullPointerException: Cannot invoke method call() on null object
I believe this means that am passing a null object which is not accepted,but i verified that there was no empty data i was passing to the DSL.
When i am creating a job with ZAP config using DSL API referrence,it works fine.
Not sure where is the issue.Hope somebody can help in this issue.Pls let me know if more details are needed on the above issue.

A: I have finally fixed the above error.The error occurred due to multiple times declaration of same variable.So Simple error.


text:
Q: when I use ButterKnife 8.4.0 error: a exception:Error:Could not find com.android.support:support-annotations:24.1.0 When I user ButterKnife 8.4.0 an error occurs:

exception:Error:Could not find com.android.support:support-annotations:24.1.01.

The IDE is Android Studio 2.2, added the apt.
Here is my build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'android-apt'

android {
  compileSdkVersion 24
  buildToolsVersion "23.0.3"

  defaultConfig {
    minSdkVersion 14
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
  }

} dependencies {
  compile fileTree(include: ['*.jar'], dir: 'libs')
  compile 'com.android.support:appcompat-v7:24.0.0-beta1'
  compile 'com.jakewharton:butterknife:8.4.0'
  apt 'com.jakewharton:butterknife-compiler:8.4.0'
}

A: You need to match the version of compile SDK, build tool version, target SDK version, and support library. If you make your app support API 24, you need to change all the value to API 24. Like this:
...

android {
  compileSdkVersion 24 // Using API 24
  buildToolsVersion "24.0.2" // Using API 24

  defaultConfig {
    minSdkVersion 14
    targetSdkVersion 24 // Using API 24
    versionCode 1
    versionName "1.0"
  }

} dependencies {
  ...
  compile 'com.android.support:appcompat-v7:24.2.0' // Using the latest API support 24
  ...
}

A: Remove all butterknife dependencies and add:
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.jakewharton:butterknife:7.0.1'


text:
Q: Node JS Asyncrounous Function Doesn't Return the Right Result Have this module.exports file which returns a function to fetch some profiles using the gender parameter as the body of the request.
Here, the function is asynchronous and waits for the fetch to return a result so it can proceed. I am using all the async js rules but still, it returns undefined.
I know that there isn't any problem in the URL or the API endpoint because I directly console logged it in .then() the promise returned by the fetch, it firstly consoles logs undefined and then it returns the original value.
Here's the code:
// Pre Configuration
const fetch = require('node-fetch')

module.exports = async (req, res, genderCode) => {
  const apiURL = req.apiURL
  const requestURL = `${apiURL}/featured?gender=${genderCode}`
  await fetch(requestURL)
    .then(res => res.json())
    .then(data => {
        return data._embedded.compactProfiles
    })
}

Also where I call the function, I also use await there.
Can anybody tell what's wrong with it?

A: You haven't put a return statement in the anonymous function you export.
You await the value from the second then statement (although I'm at a loss as to why you are using then and async/await), and then do nothing with it.
module.exports = async (req, res, genderCode) => {
  const apiURL = req.apiURL
  const requestURL = `${apiURL}/featured?gender=${genderCode}`
  const res = await fetch(requestURL);
  const data = await res.json();
  return data._embedded.compactProfiles
}


text:
Q: How can i recover MKV file after OBS Crash? I have 7.78 GB 2 hours long video file. I can play it but when i try to seek player crashing. I record it with OBS as a screen capture. My screen flashed and game crashed after that i checked obs and clicked "stop recording". Nothing happened OBS couldn't finish it. I wait 10 mins and kill it from process. Is there any way to repair this mkv ? "Stellar Repair For Video" couldn't repait it. Thanks! (Sorry for my english)

A: I just extract video and all audio tracks with ffmpeg. It's worked for me.
You can find more info in here : https://stackoverflow.com/questions/32922226/extract-every-audio-and-subtitles-from-a-video-with-ffmpeg


text:
Q: Exporting data to predefined excel in ASP.NET MVC I need to export data into user defined excel using MVC. I don't want to use tools like aspose etc.
Please help me in exporting data into user defined excel using MVC

A: Try using openxml or closedxml.
check the following link.
http://www.codeproject.com/Articles/692092/A-free-Export-to-Excel-Csharp-class-using-OpenXML
http://technet.weblineindia.com/web/export-data-to-excel-using-openxml-sdk/
http://www.codeproject.com/Articles/42628/Using-ASP-NET-MVC-and-the-OpenXML-API-to-Stream-Ex


text:
Q: Some questions about SharePoint 2013 provider hosted app I started to study how we can reproduce our project in a SharePoint 2013 app.
I've made some test and I saw that the provider hosted app generates a normal web application that will be hosted outside SharePoint environment.
I have some question about.
How create site pages?
Usually in a farm solution I create a Visual Web Part and the site page using CAML declarative mode with a module and a base layout aspx page.
How can I reproduce it in this new context? Can I to create a client web part and the page as before?
How to get SPContenxt?
I saw that when I start my project Default.aspx opens with SPHostUrl query string that is used to get ClientContext in Page_Load event. So, wherever I need to interact with SharePoint I have to open the page with this query string? Is there some other "more elegant" way to generate this query string instead to hard code it? And I have to refresh it? I saw method to refresh the access token.
Get SPHostUrl in web application
I find that in mark up I can create a link link with href='javascript:location.href="Page.aspx" + location.search' that redirects me to Page.apsx with SPHostUrl query string, is there a way to do it also in server side code?
Web service
Cannot add ISAPI folder anymore, have I to create a custom WCF service and deploy it in the remote web app url?
Thank you for your help.

A: So you are actually trying to translate a farm solution to a O365 friendly solution?
What can a provider-hosted app do?
A lot - BUT
A provider-hosted app isn't a generic replacement for farmsolutions. It's a solution with specific field of use. I like to compare them to custom webparts and application pages. It CAN do more, but likely there are better ways.
How to create elements (pages, webs, lists, etc.)?

*

*Declarative in a NCSS (No Code Sandboxed Solution)

*

*Quite limited but still valuable for most scenarios

*CSOM Provisioning

If you want to provision pages and webs, the answer is CSOM.
It does not really matter if you package that CSOM in a provider-hosted- / sharepoint-hosted-app, a simple console application or something else.
The people behind Office PnP created a awesome provisioning engine that can consume declarative templates https://msdn.microsoft.com/en-us/pnp_articles/pnp-provisioning-engine-and-the-core-library.
How to get the SPContext?
It's ClientContext in CSOM and you will find here all answers https://sharepoint.stackexchange.com/a/134489/10271
Get SPHostUrl in web application
The URL is given via the querystring when the app is called. Create a hello world app and you will see.
Web service
A provider-hosted app is essentially a IIS-hosted website that can make secure connections to sharepoint. You have to create at least that. If you need a webservice you can do so, but it's not necessary for a provider-hosted app.
You have to know that you can't call the webservice directly from SharePoint (cross-origin) but only in your providerhosted-app context.


text:
Q: Why is angular cookies accepting only strings, but not numbers? When I was working with angular cookies, I found out that only strings are accepted by $cookies and stored in browser's cookie when set. i.e
If I set the following cookies
$cookies.id = 12345;
$cookies.name = "Prasad";

Only $cookies.name is set in the browser. So I had to change it to
$cookies.id = "12345";

to make it work.
here is the fiddle link to show the demo.
I've tried to check the angular source code to see why and found that they are deliberately checking for the value to be isString.
Is there any specific reason why they are accepting only string values. Couldn't we just allow integers also and convert to string while adding to browser cookie.
Thanks!

A: The main reason is probably that that the value of a cookie is always stored as a string in the browser. Sure, Angular could allow you to save it as an int when using the service and then just convert it before creating the cookie, the problem is that people would then assume that when they read that cookie later on the value would still be an int (that's how they saved it after all).
It wouldn't, it would be a string.
Angular seems to reason (I personally agree) that it is better to be strict up front. Force input to be the same as output so that people don't misunderstand what they will be getting back when they read the cookie.


text:
Q: How to output the standard error of odds ratio for proc logistic? When I use the proc logistic in SAS, in the output, it return the confidence of interval and p-value of the odds ratio, how can I output the standard error of the odds ratio?
proc logistic data=edu;
model school = age sex income/ clodds=wald orpvalue;
oddsratio age;
run;

The output likes
                 Odds Ratio Estimates and Wald confidence interval

                                      Point          95% Wald
                    Effect         Estimate      Confidence Limits  p-value

                    age              1.21         0.74      2.001   < 0.01

A: *

*Tip: The documentation page Proc Logistic Details -> ODS Table Names lists all the tables the procedure will produce for ODS. The ODDSRATIO ... /CL=WALD ...; statement creates an output table named OddsRatiosWald.

*

*The ODS TRACE ON statement will also log the the table names that a Proc Step produces for ODS output.

*Save the table as an output data set using the ODS OUTPUT statement.

Example:
Code from SAS samples tweaked to save ODS OUTPUT.
* Example 76.4 Nominal Response Data: Generalized Logits Model;

data school;
   length Program $ 9;
   input School Program $ Style $ Count @@;
   datalines;
1 regular   self 10  1 regular   team 17  1 regular   class 26
1 afternoon self  5  1 afternoon team 12  1 afternoon class 50
2 regular   self 21  2 regular   team 17  2 regular   class 26
2 afternoon self 16  2 afternoon team 12  2 afternoon class 36
3 regular   self 15  3 regular   team 15  3 regular   class 16
3 afternoon self 12  3 afternoon team 12  3 afternoon class 20
;

ods trace on;
ods graphics on;

ods html file='logistic.html';

proc logistic data=school;
   freq Count;
   class School Program(ref=first);
   model Style(order=data)=School Program School*Program / link=glogit;
   oddsratio program / cl=wald;

   ods output OddsRatiosWald=or_program;
run;

proc print data=or_program;
  title "Logistic Odds Ratios CL=Wald output data";
run;

ods html close;
ods trace off;
title;

Output data as examined by viewtable in Base SAS


text:
Q: Inspecting COM objects in VS 2017 debugger I'm currently migranting an VBA powerpoint add-in to VSTO.
For weeks I've been struggling with Visual studio degug for COM objescts. AS you can see on the image below, the object types show {system._ComObject} and object inspection becomes a challenge since one must use the dynamic view, which is quite inconvenient in my opinion.

Looking around I've found a recommendation to activate the option "use managed code compatibility mode"  in the general debugging settings, as you can see on Debugging setting
I also followed another the recommendation to set the property "Embed interop Types" on all my office related references to false.
After applying these changes. Voilà! The inspection began do work just as I wished to and as you can see here: Debug working properly
I was almost in heaven. My ecstasy lasted till I tried to change some code during debug and was informed by visual studio that
"managed compatibility mode does not support edit and continue".
Now I'm back in hell. With edit and continue I miss a decent COM object inspection. With COM inspection I cannot change code during debug.
This situation looks awkward and I would expect more from VS 2017.
Does anybody know how can I get decent COM inspection and edit and continue at the same time?

A:
Does anybody know how can I get decent COM inspection and edit and
continue at the same time?

I am afraid that you cannnot get what you want.
Since you just debug a com object which is more like optimized, mixed, or SQL Server common language runtime (CLR) integration code(use ), as the official document said, Edit and Continue function does not support it.
Usually, to debug those mixed codes in VS, you should enable Use Managed Compatibility Mode or enable native code debugging, but those options cannot work well with Edit and Continue as the official document said.
You can check this document to know unsupported changes or supported changes to code.
So for your issue, there is no such option to use both of them.
As a suggestion, you should break the debugging process first, make some changes to your code. Then start Debugging to debug the new changes.
Besides, if you still want this feature, you could suggest a feature on our User Voice Forum. The Team will check your request carefully and hope they will give you a satisfactory reply.


text:
Q: using same class names I created two different header files, each containing a class with same names and each one is included on different cpp files, so the compiler does not complain about redefinition of them
They operate like two different classes, except when they have the same methods, with same name and same arguments, only one of them is called, for example:
//on first cpp:
#include "same1.h"
//...
SameName obj(int_value);
obj.ok(int_value);
obj.not_ok();

//on second cpp
#include "same2.h"
//...
SameName obj(float_value);
obj.ok(float_value);
obj.not_ok();

on both files, not_ok from same1.h is called, and of course it has not been initialized correctly
I know what the problem is and why this happens, I'm also familiar with Name mangling and that they both have the exact same name when compiled.
I just want to know that is it standard behavior of C++ or is it just how my compiler have implemented that, I mean, should all compilers do the same thing on this situation or not?
I should mention that I'm using gcc 4.7.1 on Debian Linux.

A: This is a violation of One Definitlion Rule and undefined behavior.

A: The standard says that if you break this particular rule, then you invoke undefined behaviour. So there is no standard behaviour for your case. But you can expect it not to work. The compiler is following the standard by doing something, because "something" is part of "undefined behaviour".

A: By including two different definitions of the same class in your program you are breaking the rules of C++. Therefore the behaviour of your program is undefined.


text:
Q: $.getJSON with php file Hi guys :) I'm quite new in the programming world, so I really need your help. I tryed to get data from some database tables and unfortunately something goes wrong in my $.getJson() function . If i run the php file it works , and so that with the functions from script.js . My html is also ok so i suppose it is the $get.JSON fault. I don't know so many javascript , so i put all my hopes into you :*
html file:
 <!doctype html>

 <meta charset="utf-8" />
 <title>jQuery Ajax - PHP</title>

script.js file :
$('document').ready( function() {
                                done();
                                }
                    );
function done() {
    setTimeout(function() {
                         updates();
                         done();
                           }
              , 200 );
                 }
function updates(){
   $.getJSON( "read.php", function (data){

      $.each(data.array, function () {
          $("body").append("
Titlu: "+this['title']+"

Descriere: "+this['describtion']+"
");
                                     }
                           );

      $.each(data.array1, function () {
          $("body").append("
Id: "+this['id']+"

Category_Id: "+this['category_id']+"

Titlu: "+this['title']+"

Descriere: "+this['describtion']+"
");
                                        }
             );

    $.each(data.array2, function () {
        $("body").append("
Id: "+this['id']+"

Titlu: "+this['title']+"

Latitudine: "+this['location_latitude']+"

Longitudine:"+this['location_longitude']+"

Numar de telefon: "+this['phone_number']+"

Descriere: "+this['describtion']+"
");
                                     }
          );

    $.each(data.array3, function () {
        $("body").append("
Id: "+this['id']+"

Interest_point_id:"+this['interest_point_id']+"

Pret: "+this['price']+"

Data: "+this['event1_time']+"
");
                                      }
          );
                                          }
                );

              }

And finally the read.php file (Here it shows me what i expect , so i think everything is all right) :
<?php
include_once ('db.php');
$query= "SELECT * FROM category";
$query1= "SELECT * FROM sub_category";
$query2= "SELECT * FROM interest_point";
$query3= "SELECT * FROM event1";
global $connect;
$result =  mysqli_query($connect,$query);
$result1 = mysqli_query($connect,$query1);
$result2 = mysqli_query($connect,$query2);
$result3 = mysqli_query($connect,$query3);
$array = array();
$array1 = array();
$array2 = array();
$array3 = array();

while($row=mysqli_fetch_array($result))
    array_push($array , array( 'id'          => $row[0],
                               'title'       => $row[1],
                               'describtion' => $row[2]
));

while($row1=mysqli_fetch_array($result1))
    array_push($array1 , array( 'id'         => $row1[0],
                               'category_id' => $row1[1],
                               'title'       => $row1[2],
                               'describtion' => $row1[3]

));
while($row2=mysqli_fetch_array($result2))
    array_push($array2 , array('id'                => $row2[0],
                               'title'             => $row2[1],
                               'location_latitude' => $row2[2],
                               'location_longitude'=> $row2[3],
                               'phone_number'      => $row2[4],
                               'describtion'       => $row2[5]

));
while($row3=mysqli_fetch_array($result3))
    array_push($array3 , array(
                               'id'               => $row3[0],
                               'interest_point_id'=> $row3[1],
                               'price'            => $row3[2],
                               'event1_time'      => $row3[3]
));

    echo json_encode(array("array"=>$array)).'
'.'
';
    echo json_encode(array("array1"=>$array1)).'
'.'
';
    echo json_encode(array("array2"=>$array2)).'
'.'
';
    echo json_encode(array("array3"=>$array3)).'
'.'
';

?>

A: You can only echo once when sending json and there can only be one php array containing all the data. You can't print anything outside of this such as the
 tags
try changing
echo json_encode(array("array"=>$array)).'
'.'
';
echo json_encode(array("array1"=>$array1)).'
'.'
';
echo json_encode(array("array2"=>$array2)).'
'.'
';
echo json_encode(array("array3"=>$array3)).'
'.'
';

To
$output = array(
   "array1"=>$array1,
   "array2"=>$array2,
   "array3"=>$array3
);

echo json_encode($output);

Also note that
 is an invalid child of . Use
 or insert into a


text:
Q: How to Create a String From Iterator in Python? How to create a string from an iterator over string in Python?
I am currently just trying to create a reversed copy of a string, I know I could just use slice:
s = 'abcde'
reversed_s = s[::-1]

I could also create a list from the iterator and join the list:
s = 'abcde'
reversed_s_it = reversed(s)
reversed_list = list(reversed_s_it)
reversed_s = ''.join(reversed_list)

But when I try to create a string from the iterator directly, it just gives a string representation of the iterator, if I do this:
s = 'abcde'
reversed_s_it = reversed(s)
reversed_s = str(reversed_s_it)

reversed_s will give a string representation of the iterator instead of iterating the iterator to create a string.
print(reversed_s)

Output
<reversed object at 0x10c3dedf0>

Furthermore
print(reversed_s == 'edcba')

Output
False

Therefore, I just want to know if there is a Pythonic way to create a string from an iterator?

A: ''.join itself only needs an iterable; you don't have to create a list first.
>>> ''.join(reversed(s))
'edcba'

However, there's nothing wrong with s[::-1]; in fact, it's quite a bit faster than using ''.join to concatenated the elements from the reversed object.


text:
Q: Finding out how primes split in a particular cubic extension I'm trying to figure out as precisely as possible how primes split in a cubic extension $\mathbb{Q}(x)$, where $x^3-x-1=0$. This extension has discriminant $-23$. Write $K=\mathbb{Q}(x)$, $L=\mathbb{Q}(\sqrt{-23})$ and $E$ for the splitting field of $X^3-X-1$. Then we have the lattice

E
| \
K  L
| /
Q

The only thing I can figure out precisely is that $23\mathcal{O}_K=\mathfrak{p}^2\mathfrak{q}$, because $$X^3-X-1\equiv (X-a)^3\,(\textrm{mod }p)$$ does not have a solution which is easy to see by expanding the cubic.
Is there any approach for finding out more things explicitly? I know at least the following:

*

*Possible splittings of an unramified prime in $K$ are
$$p=\mathfrak{p},\; p=\mathfrak{p}\mathfrak{q},\; p=\mathfrak{p}_1\mathfrak{p}_2\mathfrak{p}_3.$$

*A prime splits completely in $K$ if and only if it splits completely in $E$, so this would take care of the 3rd type.
Is it even reasonable to expect that there's some nice formula in terms of congruences to figure out the possibly splittings? At least we know that splittings of the first and second type above can both result in a similar splitting in $E$.
Does anyone have any ideas what I could try? The fact that $E/\mathbb{Q}$ is not abelian, seems to make this far more annoying.


text:
Q: Organize multidimensional array using Recursion I have an array that I've build dynamically. It has many nested arrays because of the way it's built, but the depth is useless to me, so I organize it right afterwards. It could look like this:
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => Array
                                (
                                    [index] => -1
                                    [cost] => 0.189956571618
                                )
                        )
                )
        )

    [1] => Array
        (
            [index] => -1
            [cost] => 2.18650011647
        )
)

I want to almost-flatten this array (i.e. access its data using $array[$i]['cost'] on all entries, regardless if they were nested deep before I processed them). So far I've been using SPL recursion, with something along these lines:
function flatten($array) {
    $return = array();
    $it = new RecursiveIteratorIterator(new ParentIterator(new RecursiveArrayIterator($array)), RecursiveIteratorIterator::SELF_FIRST);
    foreach($it as $value) {
        if(isset($value['cost'])) {
            $return[] = $value;
        }
    }
    return $return;
}

It works for the most part, but some of the values in the original array, which do have a 'cost' index in them, fail to be added to the new array because they are passed as nested arrays themselves, like so:
Array
(
    [0] => Array
        (
            [index] => -1
            [cost] => 0.189956571618
        )

    [1] => Array
        (
            [index] => -1
            [cost] => 2.18650011647
        )
)

...instead of just (which most of the time I get):
Array
        (
            [index] => -1
            [cost] => 0.189956571618
        )

I thought the whole point of using a RecursiveIterator was to go deep within the array and fetch the entries which don't have arrays within them (i.e. the 'values' I want). Am I using the wrong tools for this job? If so, what would be more appropriate to loop through an array for which I don't know the depth? If SPL is the way to go, what am I doing wrong?
Thanks in advance.

A: you could use array_walk_recursive
EDIT
function flatten($array) {
    $return = array();
    array_walk_recursive($array, function($value, $key) use (&$return) {
        if(isset($value['cost']) $return[] = $value;
    });
    return $return;
}

on the SPL part EDIT long discussion in the chatroom, check OP's answer


text:
Q: Gradle tomcatRun and eclipse-wtp are using not processed files I have a problem with tasks like tomcatRun, or running application with wtp-plugin. The problem is that both tasks are using not processed webapps, and wtp is using even not processed resources, and we are replacing tokens on processResources and war task depending on profile.
I was thinking on two different solutions:

*

*Change dependencies of those tasks to be run after mentioned before, and change sourcefolders for them to use the generated ones

*Instead of replacing tokens we would replace whole files during processing with the profiled versions. By default the file would be filled with data for some profile. We could create some task to set those files in source folders as well.

Neither of them looks to be a clean one, so is there some better way to do this? Are there some gradle specific guidelines on dealing with profiles?


text:
Q: Entities passed to the choice field must be managed - different on app.php and on app_dev.php Welcome!
I've added a field to a form
    ->add('languageLevel', ChoiceType::class, [
        'choices' => [
            Meme::LEVEL_BEGINNER => Meme::LEVEL_BEGINNER,
            Meme::LEVEL_INTERMEDIATE => Meme::LEVEL_INTERMEDIATE,
            Meme::LEVEL_ADVANCED => Meme::LEVEL_ADVANCED,
            Meme::LEVEL_EXPERT => Meme::LEVEL_EXPERT
        ]
    ])

This form saves entity 'Meme' with the same property
/**
 * @var string
 * @ORM\Column(name="language_level", type="string", length=20)
 */
private $languageLevel;

The prod.log gives me this:
[2017-12-17 23:41:18] request.INFO: Matched route "meme_add". {"route":"meme_add","route_parameters":{"_controller":"AppBundle\\Controller\\MemeController::addAction","_route":"meme_add"},"request_uri":"http://keenweasel.com/meme/add","method":"GET"} []
[2017-12-17 23:41:18] security.DEBUG: Read existing security token from the session. {"key":"_security_main"} []
[2017-12-17 23:41:18] security.DEBUG: User was reloaded from a user provider. {"username":"acid","provider":"FOS\\UserBundle\\Security\\UserProvider"} []
[2017-12-17 23:41:18] php.WARNING: Warning: spl_object_hash() expects parameter 1 to be object, integer given {"exception":"[object] (ErrorException(code: 0): Warning: spl_object_hash() expects parameter 1 to be object, integer given at /var/www/keen/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1239)"} []
[2017-12-17 23:41:18] php.WARNING: Warning: spl_object_hash() expects parameter 1 to be object, integer given {"exception":"[object] (ErrorException(code: 0): Warning: spl_object_hash() expects parameter 1 to be object, integer given at /var/www/keen/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1592)"} []
[2017-12-17 23:41:18] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Form\Exception\RuntimeException: "Entities passed to the choice field must be managed. Maybe persist them in the entity manager?" at /var/www/keen/vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php line 98 {"exception":"[object] (Symfony\\Component\\Form\\Exception\\RuntimeException(code: 0): Entities passed to the choice field must be managed. Maybe persist them in the entity manager? at /var/www/keen/vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php:98)"} []
[2017-12-17 23:41:18] security.DEBUG: Stored the security token in the session. {"key":"_security_main"} []

in dev.log on my dev machine there is nothing like that, and it works fine. On prod I get error 500. Any help please? I tried removing vendor and installing it one more time on both dev and prod servers. Clearing cache multiple time with --env=prod.

EDIT
Ok, got the same problem on dev server (just switched from app_dev.php to app.php in apache config and added app/autoload.php)
/**
 * @Route("/meme/add", name="meme_add")
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 * @internal param Request $request
 */
public function addAction(Request $request)
{
    $user = $this->getUser();
    if (!$user || !$user->hasRole('ROLE_MEME_ADD_AWAITING')) {
        $this->addFlash('notice', 'You need to login');
        return $this->redirectToRoute('fos_user_security_login');
    }

    if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
        throw $this->createAccessDeniedException();
    }

    $meme = new Meme();
    $form = $this->createForm(MemeAddType::class, $meme);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid() ) {
        if ($user->hasRole('ROLE_MEME_ADD_AWAITING')) {
            $meme->setPublishingStatus('awaiting-publishing');
        } else if ($this->getUser()->hasRole('ROLE_MEME_ADD_MAIN')) {
            $meme->setPublishingStatus('published');
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($meme);
        $em->flush();
    }

    return $this->render(
        '@App/memes/add.html.twig',
        [
            'memeAddForm' => $form->createView()
        ]
    );
}

The form:
<?php

namespace AppBundle\Form;

use AppBundle\Entity\Language;
use AppBundle\Entity\Meme;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichImageType;

class MemeAddType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('textOne', TextareaType::class, [
                'label' => 'A phrase or a word',
                'attr' => ['style' => 'width:320px; height: 110px']
            ])
            ->add('textOneLang', EntityType::class , [
                'class' => Language::class,
                'choice_label' => 'language',
                'expanded' => false,
                'multiple' => false,
                'label' => 'Language of the phrase of the word',
                'data' => 2

            ])
            ->add('textTwo', TextareaType::class, [
                'label' => 'Translation, might be with an example',
                'attr' => ['style' => 'width:320px; height: 110px']
            ])
            ->add('textTwoLang', EntityType::class , [
                'class' => Language::class,
                'choice_label' => 'language',
                'expanded' => false,
                'multiple' => false,
                'label' => 'Language of the translation of the phrase of the word',
                'data' => 2
            ])
            ->add('languageLevel', ChoiceType::class, [
                'choices' => [
                    Meme::LEVEL_BEGINNER => Meme::LEVEL_BEGINNER,
                    Meme::LEVEL_INTERMEDIATE => Meme::LEVEL_INTERMEDIATE,
                    Meme::LEVEL_ADVANCED => Meme::LEVEL_ADVANCED,
                    Meme::LEVEL_EXPERT => Meme::LEVEL_EXPERT
                ]
            ])
            ->add('imageFile', VichImageType::class)
            ->add(
                'save',
                SubmitType::class,
                [
                    'attr' => ['class' => 'save']
                ]
            )
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Meme::class
        ]);
    }

    public function getBlockPrefix()
    {
        return 'app_bundle_meme_add';
    }

    public function getName() {
        return 'app_bundle_meme_add';
    }
}

A: Try this in your formType
<?php

namespace AppBundle\Form;

use AppBundle\Entity\Language;
use AppBundle\Entity\Meme;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichImageType;

class MemeAddType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('textOne', TextareaType::class, [
                'label' => 'A phrase or a word',
                'attr' => ['style' => 'width:320px; height: 110px']
            ])
            ->add('textOneLang', EntityType::class , [
                'class' => Language::class,
                'choice_label' => 'language',
                'expanded' => false,
                'multiple' => false,
                'label' => 'Language of the phrase of the word',
                'data' => 2

            ])
            ->add('textTwo', TextareaType::class, [
                'label' => 'Translation, might be with an example',
                'attr' => ['style' => 'width:320px; height: 110px']
            ])
            ->add('textTwoLang', EntityType::class , [
                'class' => Language::class,
                'choice_label' => 'language',
                'expanded' => false,
                'multiple' => false,
                'label' => 'Language of the translation of the phrase of the word',
                'data' => 2
            ])
            ->add('languageLevel', ChoiceType::class, [
                'choices' => [
                    Meme::LEVEL_BEGINNER => Meme::LEVEL_BEGINNER,
                    Meme::LEVEL_INTERMEDIATE => Meme::LEVEL_INTERMEDIATE,
                    Meme::LEVEL_ADVANCED => Meme::LEVEL_ADVANCED,
                    Meme::LEVEL_EXPERT => Meme::LEVEL_EXPERT
                ]
            ])
            ->add('imageFile', VichImageType::class)
            ->add(
                'save',
                SubmitType::class,
                [
                    'attr' => ['class' => 'save']
                ]
            )
        ;
        $builder->get('languageLevel')->resetViewTransformers();
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Meme::class
        ]);
    }

    public function getBlockPrefix()
    {
        return 'app_bundle_meme_add';
    }
}

A: Actually, what was going on was that I had
 'data' => 2

in the textOneLang  form element, so it was failing when it was given to  spl_object_hash() function which only accepts objects, not integers. Data transformer was not used for that. But this 'data' parameter wasn't supposed to be there in the first place, don't know how it ended up there. Probably, when trying to debug it. Lesson learned, have all the options figured out and also, just dump what you have as parameter in spl_object_hash().
The difference between app_dev.php and app.php didn't have anything to do with it. It was probably cached somehow in app_dev.php and worked on some older version.


text:
Q: Nova instance throws an error on launch - "failed to perform requested operation on instance" Nova instance throws an error on launch - "failed to perform requested operation on instance….the server has either erred or is incapable of performing the requested operation (HTTP 500)". See screenshot below.
InstanceCraetion Error
Surprisingly it works well when attaching volume separately after instance launch. You need set "Create New Volume" to "No" during creation of instance.
We restarted cinder service, but it did not solve the issue.
From the API logs we figured out that there is HTTP 500 error during API interactions in service endpoints (Nova & Cinder).  Logs pasted below.
Can someone help to resolve this issue ?
Thanks in advance.
Openstack - Details
It is 3 Node System .one Controller +2 Compute .
Controller has Centos7 and Openstack Ocata Release
Cinder Version 1.11.0 and Nova Version 7.1.2
List of Nova and Cinder RPM's
==> api.log <==
2019-01-30 04:16:28.785 275098 ERROR cinder.api.middleware.fault [req-634abf81-df79-42b5-b8f4-8f19488c0bba a1c4c0232896400ba6fddf1cbcb54dd8 2db5c111414e4d2bbc14645e6f0931db - default default] Caught error: <class 'oslo_messaging.exceptions.MessagingTimeout'> Timed out waiting for a reply to message ID bf2f80590a754b59a720405cd0bc1ffb
2019-01-30 04:16:28.785 275098 ERROR cinder.api.middleware.fault Traceback (most recent call last):
2019-01-30 04:16:28.785 275098 ERROR cinder.api.middleware.fault   File "/usr/lib/python2.7/site-packages/cinder/api/middleware/fault.py", line 79, in __call__
2019-01-30 04:16:28.785 275098 ERROR cinder.api.middleware.fault     return req.get_response(self.application)
2019-01-30 04:16:28.785 275098 ERROR cinder.api.middleware.fault   File "/usr/lib/python2.7/site-packages/webob/request.py", line 1299, in send
2019-01-30 04:16:28.793 275098 INFO cinder.api.middleware.fault [req-634abf81-df79-42b5-b8f4-8f19488c0bba a1c4c0232896400ba6fddf1cbcb54dd8 2db5c111414e4d2bbc14645e6f0931db - default default] http://10.110.77.2:8776/v2/2db5c111414e4d2bbc14645e6f0931db/volumes/301f71f0-8fb5-4429-a67c-473d42ff9def/action returned with HTTP 500
2019-01-30 04:16:28.794 275098 INFO eventlet.wsgi.server [req-634abf81-df79-42b5-b8f4-8f19488c0bba a1c4c0232896400ba6fddf1cbcb54dd8 2db5c111414e4d2bbc14645e6f0931db - default default] 10.110.77.4 "POST /v2/2db5c111414e4d2bbc14645e6f0931db/volumes/301f71f0-8fb5-4429-a67c-473d42ff9def/action HTTP/1.1" status: 500  len: 425 time: 60.0791931
2019-01-30 04:16:28.813 275098 INFO cinder.api.openstack.wsgi [req-53d149ac-6e60-4ddd-9ace-216d12122790 a1c4c0232896400ba6fddf1cbcb54dd8 2db5c111414e4d2bbc14645e6f0931db - default default] POST http://10.110.77.2:8776/v2/2db5c111414e4d2bbc14645e6f0931db/volumes/301f71f0-8fb5-4429-a67c-473d42ff9def/action
2019-01-30 04:16:28.852 275098 INFO cinder.volume.api [req-53d149ac-6e60-4ddd-9ace-216d12122790 a1c4c0232896400ba6fddf1cbcb54dd8 2db5c111414e4d2bbc14645e6f0931db - default default] Volume info retrieved successfully.

Nova Logs :
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [req-a4b94c35-2532-4e82-864c-ff33b972a3b2 a1c4c0232896400ba6fddf1cbcb54dd8 2db5c111414e4d2bbc14645e6f0931db - - -] [instance: aba62cf8-0880-4bf7-8201-3365861c8079] Instance failed block device setup
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079] Traceback (most recent call last):
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/nova/compute/manager.py", line 1588, in _prep_block_device
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     wait_func=self._await_block_device_map_created)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/nova/virt/block_device.py", line 512, in attach_block_devices
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     _log_and_attach(device)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/nova/virt/block_device.py", line 509, in _log_and_attach
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     bdm.attach(*attach_args, **attach_kwargs)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/nova/virt/block_device.py", line 408, in attach
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     do_check_attach=do_check_attach)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/nova/virt/block_device.py", line 48, in wrapped
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     ret_val = method(obj, context, *args, **kwargs)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/nova/virt/block_device.py", line 258, in attach
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     connector)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/nova/volume/cinder.py", line 168, in wrapper
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     res = method(self, ctx, *args, **kwargs)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/nova/volume/cinder.py", line 190, in wrapper
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     res = method(self, ctx, volume_id, *args, **kwargs)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/nova/volume/cinder.py", line 391, in initialize_connection
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     exc.code if hasattr(exc, 'code') else None)})
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/oslo_utils/excutils.py", line 220, in __exit__
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     self.force_reraise()
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/oslo_utils/excutils.py", line 196, in force_reraise
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     six.reraise(self.type_, self.value, self.tb)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/nova/volume/cinder.py", line 365, in initialize_connection
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     context).volumes.initialize_connection(volume_id, connector)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/cinderclient/v2/volumes.py", line 404, in initialize_connection
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     {'connector': connector})
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/cinderclient/v2/volumes.py", line 334, in _action
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     resp, body = self.api.client.post(url, body=body)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/cinderclient/client.py", line 167, in post
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     return self._cs_request(url, 'POST', **kwargs)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/cinderclient/client.py", line 155, in _cs_request
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     return self.request(url, method, **kwargs)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]   File "/usr/lib/python2.7/site-packages/cinderclient/client.py", line 144, in request
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]     raise exceptions.from_response(resp, body)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079] ClientException: The server has either erred or is incapable of performing the requested operation. (HTTP 500) (Request-ID: req-dcd4a981-8b22-4c3d-9ba7-25fafe80b8f5)
2019-01-30 03:58:04.808 5642 ERROR nova.compute.manager [instance: aba62cf8-0880-4bf7-8201-3365861c8079]
2019-01-30 03:58:04.811 5642 DEBUG nova.compute.claims [req-a4b94c35-2532-4e82-864c-ff33b972a3b2 a1c4c0232896400ba6fddf1cbcb54dd8 2db5c111414e4d2bbc14645e6f0931db - - -] [instance: aba62cf8-0880-4bf7-8201-3365861c8079] Aborting claim: [Claim: 4096 MB memory, 40 GB disk] abort /usr/lib/python2.7/site-packages/nova/compute/claims.py:124
2019-01-30 03:58:04.812 5642 DEBUG oslo_concurrency.lockutils [req-a4b94c35-2532-4e82-864c-ff33b972a3b2 a1c4c0232896400ba6fddf1cbcb54dd8 2db5c111414e4d2bbc14645e6f0931db - - -] Lock "compute_resources" acquired by "nova.compute.resource_tracker.abort_instance_claim" :: waited 0.000s inner /usr/lib/python2.7/site-packages/oslo_concurrency/lockutils.py:270
2019-01-30 03:58:04.844 5642 INFO nova.scheduler.client.report [req-a4b94c35-2532-4e82-864c-ff33b972a3b2 a1c4c0232896400ba6fddf1cbcb54dd8 2db5c111414e4d2bbc14645e6f0931db - - -] Deleted allocation for instance aba62cf8-0880-4bf7-8201-3365861c8079

Output of some hygiene commands from openstack :
[root@controller ~(keystone_admin)]# cinder service-list
+------------------+----------------+------+---------+-------+----------------------------+-----------------+
| Binary           | Host           | Zone | Status  | State | Updated_at                 | Disabled Reason |
+------------------+----------------+------+---------+-------+----------------------------+-----------------+
| cinder-backup    | controller     | nova | enabled | up    | 2019-01-31T10:27:20.000000 | -               |
| cinder-scheduler | controller     | nova | enabled | up    | 2019-01-31T10:27:13.000000 | -               |
| cinder-volume    | controller@lvm | nova | enabled | up    | 2019-01-31T10:27:12.000000 | -               |
+------------------+----------------+------+---------+-------+----------------------------+-----------------+

[root@controller yum.repos.d]# rpm -qa | grep cinder
openstack-cinder-10.0.5-1.el7.noarch
puppet-cinder-10.4.0-1.el7.noarch
python-cinder-10.0.5-1.el7.noarch
python2-cinderclient-1.11.0-1.el7.noarch
[root@controller yum.repos.d]# rpm -qa | grep nova
openstack-nova-conductor-15.1.0-1.el7.noarch
openstack-nova-novncproxy-15.1.0-1.el7.noarch
openstack-nova-compute-15.1.0-1.el7.noarch
openstack-nova-cert-15.1.0-1.el7.noarch
openstack-nova-api-15.1.0-1.el7.noarch
openstack-nova-console-15.1.0-1.el7.noarch
openstack-nova-common-15.1.0-1.el7.noarch
openstack-nova-placement-api-15.1.0-1.el7.noarch
python-nova-15.1.0-1.el7.noarch
python2-novaclient-7.1.2-1.el7.noarch
openstack-nova-scheduler-15.1.0-1.el7.noarch
puppet-nova-10.5.0-1.el7.noarch
[root@controller yum.repos.d]#

[root@controller yum.repos.d]# rpm -qa | grep ocata
centos-release-openstack-ocata-1-2.el7.noarch
[root@controller yum.repos.d]# uname -a
Linux controller 3.10.0-862.2.3.el7.x86_64 #1 SMP Wed May 9 18:05:47 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
[root@controller yum.repos.d]#
centos-release-openstack-ocata-1-2.el7.noarch

[root@controller yum.repos.d]# cinder --version
1.11.0
[root@controller yum.repos.d]# nova --version
7.1.2
[root@controller yum.repos.d]#

A: I got the fix for this issue.
I have observed there were few projects in Openstack where volume deletion stuck in error state with "Error deleting". I changed the volume state explicitly from cinder db using the "cinder reset-state --state available volume-id".
This allowed me to delete the volume successfully. I restarted the cinder service then after and everything stated working as usual


text:
Q: Box refresh token expiry on user in-activity? We have a system in which the administrators of different box accounts give our app the permission to access their company accounts. In Box API documents, we see that the refresh tokens expires
- Till used
- 60 days of inactivity

I want to know about this 2nd limit of 60 days of inactivity. Does this means 60 days of activity on our application part? or on the actual user(administrator) part.. What if the administrator does not log in to her account for 60 days(meanwhile our app is till running).. Will the refresh token expire in that case also?

A: Any given refresh token expires 60 days from when it was issued, in the same way that an access token expires ~1 hour from when it was issued. It is not a sliding window; the activity of your application or users has no effect.
Either the user will need to reauthorize your application if they haven't logged in for 60+ days or you'll need to write some background service to periodically refresh any access token(s) whose refresh token is nearing expiration.


text:
Q: Need to change the `signin` name in header links in Magento 2 I am building a custom theme and I need to change the signin link name which is not contained in the layout file nor in the phtml file but only in the block class file.
So should I build a module in the app/code directory or could I put this block class into the app/design directory?

A: override vendor/magento/module-customer/i18n/en_US.csv In your theme
and put
"Sign In","test in"
What you need
if above not working then override authorization.phtml in your theme like this and put code as below:

app/design/frontend/Test/testnew/Magento_Customer/templates/account/link/authorization.phtml

<?php
    /**
     * Copyright © Magento, Inc. All rights reserved.
     * See COPYING.txt for license details.
     */

    // @codingStandardsIgnoreFile

    /** @var \Magento\Customer\Block\Account\AuthorizationLink $block */

    $dataPostParam = '';
    if ($block->isLoggedIn()) {
        $dataPostParam = sprintf(" data-post='%s'", $block->getPostParams());
    }
    ?>
    <?php if (!$block->isLoggedIn()) :?>

    <li class="authorization-link" data-label="<?= $block->escapeHtmlAttr(__('or')) ?>">
        <a href="<?php echo $this->getUrl('customer/account/login'); ?>">
            <?php //= $block->escapeHtml($block->getLabel()) ?>
            <?php echo __('Login'); ?>

    <?php endif;?>