text:
Q: Allow BottomSheet to slide up after threshold is reached on an area outside I am trying to replicate a behavior that the current Google Maps has which allows the bottom sheet to be revealed when sliding up from the bottom bar.
Notice in the recording below that I first tap on one of the buttons at the bottom bar and then slide up, which in turn reveals the sheet behind it.

I cannot find anywhere explained how something like this can be achieved. I tried exploring the BottomSheetBehavior and customizing it, but nowhere I can find a way to track the initial tap and then let the sheet take over the movement once the touch slop threshold is reached.
How can I achieve this behavior without resorting to libraries? Or are there any official Google/Android views that allow this behavior between two sections (the navigation bar and bottom sheet)?

A: Took some time but I found a solution based on examples and discussion provided by two authors, their contributions can be found here:
https://gist.github.com/davidliu/c246a717f00494a6ad237a592a3cea4f
https://github.com/gavingt/BottomSheetTest
The basic logic is to handle touch events in onInterceptTouchEvent in a custom BottomSheetBehavior and check in a CoordinatorLayout if the given view (from now on named proxy view) is of interest for the rest of the touch delegation in isPointInChildBounds.
This can be adapted to use more than one proxy view if needed, the only change necessary for this is to make a proxy view list and iterate the list instead of using a single proxy view reference.
Below follows the code example of this implementation. Do note that this is only configured to handle vertical movements, if horizontal movements are necessary then adapt the code to your need.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<com.example.tabsheet.CustomCoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/customCoordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@android:color/darker_gray">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:icon="@drawable/ic_launcher_background"
            android:text="Tab 1" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:icon="@drawable/ic_launcher_background"
            android:text="Tab 2" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:icon="@drawable/ic_launcher_background"
            android:text="Tab 3" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:icon="@drawable/ic_launcher_background"
            android:text="Tab 4" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:icon="@drawable/ic_launcher_background"
            android:text="Tab 5" />

    </com.google.android.material.tabs.TabLayout>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/bottomSheet"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#3F51B5"
        android:clipToPadding="false"
        app:behavior_peekHeight="0dp"
        app:layout_behavior=".CustomBottomSheetBehavior" />

</com.example.tabsheet.CustomCoordinatorLayout>

MainActivity.java
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        final CustomCoordinatorLayout customCoordinatorLayout;
        final CoordinatorLayout bottomSheet;
        final TabLayout tabLayout;

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        customCoordinatorLayout = findViewById(R.id.customCoordinatorLayout);
        bottomSheet = findViewById(R.id.bottomSheet);
        tabLayout = findViewById(R.id.tabLayout);

        iniList(bottomSheet);
        customCoordinatorLayout.setProxyView(tabLayout);

    }

    private void iniList(final ViewGroup parent) {

        @ColorInt int backgroundColor;
        final int padding;
        final int maxItems;
        final float density;
        final NestedScrollView nestedScrollView;
        final LinearLayout linearLayout;
        final ColorDrawable dividerDrawable;
        int i;
        TextView textView;
        ViewGroup.LayoutParams layoutParams;

        density = Resources.getSystem().getDisplayMetrics().density;
        padding = (int) (20 * density);
        maxItems = 50;
        backgroundColor = ContextCompat.getColor(this, android.R.color.holo_blue_bright);
        dividerDrawable = new ColorDrawable(Color.WHITE);

        layoutParams = new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        );

        nestedScrollView = new NestedScrollView(this);
        nestedScrollView.setLayoutParams(layoutParams);
        nestedScrollView.setClipToPadding(false);
        nestedScrollView.setBackgroundColor(backgroundColor);

        linearLayout = new LinearLayout(this);
        linearLayout.setLayoutParams(layoutParams);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerDrawable(dividerDrawable);

        for (i = 0; i < maxItems; i++) {

            textView = new TextView(this);
            textView.setText("Item " + (1 + i));
            textView.setPadding(padding, padding, padding, padding);

            linearLayout.addView(textView, layoutParams);

        }

        nestedScrollView.addView(linearLayout);
        parent.addView(nestedScrollView);

    }

}

CustomCoordinatorLayout.java
public class CustomCoordinatorLayout extends CoordinatorLayout {

    private View proxyView;

    public CustomCoordinatorLayout(@NonNull Context context) {
        super(context);
    }

    public CustomCoordinatorLayout(
        @NonNull Context context,
        @Nullable AttributeSet attrs
    ) {
        super(context, attrs);
    }

    public CustomCoordinatorLayout(
        @NonNull Context context,
        @Nullable AttributeSet attrs,
        int defStyleAttr
    ) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean isPointInChildBounds(
        @NonNull View child,
        int x,
        int y
    ) {

        if (super.isPointInChildBounds(child, x, y)) {
            return true;
        }

        // we want to intercept touch events if they are
        // within the proxy view bounds, for this reason
        // we instruct the coordinator layout to check
        // if this is true and let the touch delegation
        // respond to that result
        if (proxyView != null) {
            return super.isPointInChildBounds(proxyView, x, y);
        }

        return false;

    }

    // for this example we are only interested in intercepting
    // touch events for a single view, if more are needed use
    // a List<View> viewList instead and iterate in
    // isPointInChildBounds
    public void setProxyView(View proxyView) {
        this.proxyView = proxyView;
    }

}

CustomBottomSheetBehavior.java
public class CustomBottomSheetBehavior<V extends View> extends BottomSheetBehavior<V> {

    // we'll use the device's touch slop value to find out when a tap
    // becomes a scroll by checking how far the finger moved to be
    // considered a scroll. if the finger moves more than the touch
    // slop then it's a scroll, otherwise it is just a tap and we
    // ignore the touch events
    private int touchSlop;
    private float initialY;
    private boolean ignoreUntilClose;

    public CustomBottomSheetBehavior(
        @NonNull Context context,
        @Nullable AttributeSet attrs
    ) {
        super(context, attrs);
        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    public boolean onInterceptTouchEvent(
        @NonNull CoordinatorLayout parent,
        @NonNull V child,
        @NonNull MotionEvent event
    ) {

        // touch events are ignored if the bottom sheet is already
        // open and we save that state for further processing
        if (getState() == STATE_EXPANDED) {

            ignoreUntilClose = true;
            return super.onInterceptTouchEvent(parent, child, event);

        }

        switch (event.getAction()) {

            // this is the first event we want to begin observing
            // so we set the initial value for further processing
            // as a positive value to make things easier
            case MotionEvent.ACTION_DOWN:
                initialY = Math.abs(event.getRawY());
                return super.onInterceptTouchEvent(parent, child, event);

            // if the last bottom sheet state was not open then
            // we check if the current finger movement has exceed
            // the touch slop in which case we return true to tell
            // the system we are consuming the touch event
            // otherwise we let the default handling behavior
            // since we don't care about the direction of the
            // movement we ensure its difference is a positive
            // integer to simplify the condition check
            case MotionEvent.ACTION_MOVE:
                return !ignoreUntilClose
                    && Math.abs(initialY - Math.abs(event.getRawY())) > touchSlop
                    || super.onInterceptTouchEvent(parent, child, event);

            // once the tap or movement is completed we reset
            // the initial values to restore normal behavior
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                initialY = 0;
                ignoreUntilClose = false;
                return super.onInterceptTouchEvent(parent, child, event);

        }

        return super.onInterceptTouchEvent(parent, child, event);

    }

}

Result with transparent status bar and navigation bar to help visualize the bottom sheet sliding up, but excluded from the code above since it was not relevant for this question.
Note: It is possible you might not even need a custom bottom sheet behavior if your bottom sheet layout contains a certain scrollable view type (NestedScrollView for example) that can be used as is by the CoordinatorLayout, so try without the custom bottom sheet behavior once your layout is ready since it will make this simpler.

A: You could try something like this (It's Pseudocode, hopefully you understand what I'm getting at):
<FrameLayout id="+id/bottomSheet">

    <View id="exploreNearby bottomMargin="buttonContainerHeight/>
    <LinearLayout>
        <Button id="explore"/>
        <Button id="explore"/>
        <Button id="explore"/>
    </LinearLayout>

    <View width="match" height="match" id="+id/touchCatcher"

</FrameLayout>

Add a gesture detector on the bottomSheet view on override onTouch(). which uses SimpleOnGestureListener to wait for a "scroll" events - everything but a scroll event you can replicate down through to the view as normal.
On a scroll event you can grow your exploreNearby as a delta (make sure it doesn't recurse or go to high or too low).

A: The Bottom sheet class will already do this for you. Just set it's peek height to 0 and it should already listen for the slide up gesture.
However, I'm not positive it will work with a peek height of 0. So if that doesn't work, simply put a peek height of 20dp and make the top portion of the bottom sheet layout transparent so it is not visible.
That should do the trick for ya, unless I'm misunderstanding your question. If your goal is to simply be able to tap at the bottom and slide upwards bringing up the bottom sheet that should be pretty straight forward.
The one possible issue that you "could" encounter is if the bottom sheet doesn't receive the touch events due to the button already consuming it. If this happens you will need to create a touch handler for the whole screen and return "true" that you are handling it each time, then simply forward the touch events to the underlying view, so when you get above the threshold of your bottom tab bar you start sending the touch events to the bottom sheet layout instead of the tab bar.
It sounds harder than it is. Most classes have an onTouch and you just forward it on. However, only go that route, if it doesn't work for you out of the box the way I described in the first two scenarios.
Lastly, one other option that might work is to create your tab buttons as part of the bottomSheetLayout and make the peek height equivalent of the tab bar. Then make sure the tab bar is constrained to bottomsheet parent bottom, so that when you swipe up it simply stays at the bottom. This would enable you to click the buttons or get the free bottom sheet behavior.
Happy Coding!


text:
Q: Libgdx Ashley Entity Collision I'm attempting to make a game with libgdx and ashley. I have a basic understanding of both and was wondering how to handle a entity collision.
I saw a ContactListener in Box2D, but I am unsure of how to link this with entities in ashley.
I just want to prevent entities from passing through other entities.

A: Here is one approach, that I implement myself:

*

*Define interface CollisionListener:
public interface CollisionListener {
    void onBeginContact(Body bodyA, Body bodyB);
}

*Create CollisionListenerSystem that register itself as world contact listener, and notifies your other systems about collisions:
public class CollisionSystem implements ContactListener {
private final List<CollisionListener> collisionListeners;

public CollisionSystem(World world, List<CollisionListener> collisionListeners) {
    world.setContactListener(this);
    this.collisionListeners = collisionListeners;
}

@Override
public void beginContact(Contact contact) {
    for (CollisionListener collisionListener : collisionListeners)
       collisionListener.onBeginContact(contact.getFixtureA().getBody(), contact.getFixtureB().getBody());

*implement CollisionListener in any system, that should process collisions and pass it in the collisionListener list in CollisionSystem constructor

redpajama_set_name: RedPajamaStackExchange


text:
Q: Track when people drop out of a web form Is there a way that I can track when people drop out of a form. If the form is, say, 10 fields long and they start entering their data and then decide to not submit half way through, is there a way to capture the data they've entered already to give an idea of when and why they didn't submit?
Many thanks

A: One thing to do could be to save their data in a cookie, for their own sake if they leave the site and come back. This could be done using eg. http://code.google.com/p/cacheform/ . This would be to increase usability.
It really takes some coding to collect, aggregate and visualize the data you mention. Time on field, conversion rate, average input length or dropout rate per field etc are all super useful indicators of web form usability and what to keep or remove in a form.
I pitched an external tool for this to a client, which took me five minutes to implement. I used Form Analytics. There is also clicktail.com which might be of use to you.

A: You can run a function on the onunload event handler that serializes the form and makes an AJAX request. No guarantees that this will work with every browser (especially if the user force quits the browser or the computer freezes, etc) but for the most part it would be the easiest way to get the data in the database.

A: Of course, you can use javascript events, and a AJAX call. Works even if user forse quits browser.

A: Ajax the data to the server with an onchange on every text field.

A: Yes. Of course there's a way :)
Essentially you are going to want to, at some point, check the form to see if there is any data to capture. You might do this when the user leaves the page, or even every time they press a key - it's up to you and how detailed you want to get.
What I would do is serialize the form, and pass it (via ajax) to a web service that handles the data appropriately.
This is a realy quick sample of how to serialize and pass the data. In this example, the form I am passing has an ID of "mainForm", and my web service is a local file called "makeList.php" that looks for $_REQUST['j'] to get the passed form data.
function makeList(){
    var r= getXmlObject();
    var json=$.toJSON($('#mainForm').serializeObject());
    var url= 'makeList.php?j=' + encodeURIComponent(json);
    if (r.readyState == 4 || r.readyState == 0) {
            r.open("POST", url, true);
            r.onreadystatechange = function(){
            //do stuff when the ajax request is finished being received.
        }
        r.send(null);
    }
}

function getXmlObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert('Status: Cound not create XmlHttpRequest Object. Consider upgrading your browser.');
    }
}

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


text:
Q: Use a ::std::vector for array creation I want to grow a ::std::vector at runtime, like that:
::std::vector<int> i;
i.push_back(100);
i.push_back(10);

At some point, the vector is finished, and i do not need the extra functionality ::std::vector provides any more, so I want to convert it to a C-Array:
int* v = i.data();

Because I will do that more than once, I want to deallocate all the heap memory ::std::vector reserved, but I want to keep the data, like that (pseudo-code):
free(/*everything from ::std::vector but the list*/);

Can anybody give me a few pointers on that?
Thanks in advance,
Jack

A: In all the implementations I have seen, the allocated part of a vector is... the array itself. If you know that it will no longer grow, you can try to shrink it, to release possibly unused memory:
i.shrink_to_fit();
int* v = i.data();

Of course, nothing guarantees that the implementation will do anything, but the only foolproof alternative would be to allocated a new array, move data from the vector to the array and clear the vector.
int *v = new int[i.size];
memcpy(v, i.data, i.size * sizeof(int));
i.clear();

But I really doubt that you will have a major gain that way...

A: You can use the contents of a std::vector as a C array without the need to copy or release anything. Just make sure that std::vector outlives the need for your pointer to be valid (and that further modifications which could trigger a reallocation are done on the vector itself).
When you obtain a pointer to internal storage through data() you're not actually allocating anything, just referring to the already allocated memory.
The only additional precaution you could use to save memory is to use shrink_to_fit() to release any excess memory used as spare capacity (though it's not guaranteed).

A: You have two options:

*

*Keep data in vector, but call shrink_to_fit. All overhead you'll have - is an extra pointer (to the vector end). It is available since C++ 11

*Copy data to an external array and destroy the vector object:

Here is the example:
std::vector<int> vec;
// fill vector
std::unique_ptr<int[]> arr(new int[vec.size()]);
std::copy(vec.begin(), vec.end(), arr.get());


text:
Q: Upgrade nuget package I am following a microsoft tutorial and it requires me to install SendGrid from the package manager. When I try to install it I get the following error in my package manager
Install-Package : The 'System.Net.Http 4.0.0' package requires NuGet client version '3.0' or above, but the current NuGet version is '2.12.0.817'.
At line:1 char:16

*

*install-package <<<<  sendgrid

*CategoryInfo          : NotSpecified: (:) [Install-Package], NuGetVersionNotSatisfiedException

*FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

Nuget is already installed to its latest version, is there anything that can be done about this? Alternatively, Is there another way to do a code first email confirmation and password reset using individual accounts?

A: In visual studio, goto Tools -> Extensions & Updates -> Updates.
Select Nuget and click Update.

If no further updates are possible, you are required to upgrade Visual Studio.


text:
Q: It's possible to record leads analytics about "Source", "Medium" and "Campaign" on a Custom HTML Form? I know that this question is kinda weird but I have a CRM platform integrated with a MySQL database.
In this way, each new row in the MySQL database is a lead in the CRM system but now I need to track all information related with source, ect... from that lead and seems like a complicated task but don't really know if is possible.
I have hours looking for a solution and still haven't found anything useful.

A: You have to replicate programmatically what Google Analytics do and save value in cookie or database.
For example, when user lands on website with UTM in the URL you can get that values, if there aren't UTM you can check if there is gclid parameter in the URL so it will be google / cpc, if there isn't that parameter you can check document referral, if it is google.com your source and medium will be google / organic, alternatively website / referral.
You save the data the first time and pass it in the form. This is the principle makes use of.


text:
Q: how to, javascript Pop Under not popping in the background i have this simple script of a popunder window:
function loadpopunder(){
win2=window.open(popunder,"",winfeatures)
win2.blur()
window.focus()
}

It works but it looks like the new window doesn't load under the main one. it loads on top.
i've been looking at this from multiple ways and i can't figure it out.
any ideas?
thanks
edit: this code is just a sample, mine actually has all the ; and the http://.. link,
also, i understand that none likes the popunders, i don't like them either, is just one of those things that needs to be done. I hope one day someone will figure a way of blocking those too, but i am here bcause i am looking for a solution

A: Please reconsider your choice. There are about zero people that enjoy pop-unders.
For the sake of answering your question, here is what's considered a better way: http://icant.co.uk/articles/how-to-create-popunders/


text:
Q: error in parsing json data in javascript [
  [
    {
      "Id": 1234,
      "PersonId": 1,
      "Message": "hiii",
      "Image": "5_201309091104109.jpg",
      "Likes": 7,
      "Status": 1,
      "OtherId": 3,
      "Friends": 0
    }
  ],
  [
    {
      "Id": 201309091100159,
      "PersonId": 1,
      "Message": "heyyyyyyyy",
      "Image": "",
      "Likes": 2,
      "Status": 1,
      "OtherId": 3,
      "Friends": 3
    }
  ]
]

I am trying to parse this JSON data in javascript,but its giving an error
"SyntaxError: JSON.parse: unexpected character"
Tell me how to parse or access this json data and how to get numbers of records saved in JSON data.
I am running this on firefox ..Please help me to resolve this problem.Thanks in advance

A: If your msg variable is already a Javascript object literal you can access properties in it directly like you said : msg[0][0].Id
If it is a string you can use JSON.parse() function to obtain a JS object:
Parse JSON in JavaScript?
Fiddle:
http://jsfiddle.net/nilgundag/EdWKv/1/
var msg1 = [
  [
    {
      "Id": 1234,
      "PersonId": 1,
      "Message": "hiii",
      "Image": "5_201309091104109.jpg",
      "Likes": 7,
      "Status": 1,
      "OtherId": 3,
      "Friends": 0
    }
  ],
  [
    {
      "Id": 201309091100159,
      "PersonId": 1,
      "Message": "heyyyyyyyy",
      "Image": "",
      "Likes": 2,
      "Status": 1,
      "OtherId": 3,
      "Friends": 3
    }
  ]
];
$("#first").text(msg1[0][0].Id);

var myJSONString = '[[{"Id": 1234,"PersonId": 1,"Message": "hiii","Image": "5_201309091104109.jpg","Likes": 7,  "Status": 1,     "OtherId": 3,      "Friends": 0    }  ],  [    {      "Id": 201309091100159,      "PersonId": 1,      "Message": "heyyyyyyyy",      "Image": "",      "Likes": 2,      "Status": 1,      "OtherId": 3,      "Friends": 3    }  ]]';
var msg2 = JSON.parse(myJSONString);
$("#second").text(msg2[0][0].Id);

A: I thought that the json str is valid。but when that string isn't in JS enviroment..that's format is invalid.


text:
Q: llamar funcion desde Google map InfoWindows en ionic? Estoy tratado de llamar una funcion desde  un InfoWindows de Google Maps API, pero me muestra el siguiente error:

(index):1 Uncaught ReferenceError: ir is not defined
      at HTMLButtonElement.onclick ((index):1)

Al parecer dice que la función ir() no está definida.
Éste es mi código:
addMarker(position,map,title){
    var marker = new google.maps.Marker({
      position,
      map,
      title
    });

    var infoWindow = new google.maps.InfoWindow({
      content:" "
    });

    marker.addListener('click',function(){
      infoWindow.setContent('
 '+ title +'
' +
          '<button class="mapaboton" onclick="ir()">Ver Detalles</button>');

        infoWindow.open(map,marker);
    });

  }

Función ir()  la cual sí tengo definida:
  ir(){
    console.log("vamos");
  }

Al momento de darle click al botón que creo en el infowindows me muestra el error. Estuve investigando y no encuentro la respuesta.
Basicamente lo que trato de hacer es esto
http://jsfiddle.net/doktormolle/8ZsSp/

A: Finalmente encontré la solución
básicamente es  colocarle un id al botton

   marker.addListener('click',function(){
      infoWindow.setContent('
 '+ title +'
' +
          '<button id="' + id +'"  class="mapaboton" >Ver Detalles</button>');
        infoWindow.open(map,this);
    });

y luego
un evento addListenerOnce

   google.maps.event.addListenerOnce(infoWindow, 'domready', () => {
      document.getElementById(id).addEventListener('click', () => {
               this.navCtrl.push(RestauranteDetallePage,{ codigo : id})
          });
  });

A: Lo que pasa es que ir() no es una función, es un método de tu componente, por eso no escribiste function delante (no es por que sea typescript, javascript tiene la misma sintaxis):

class MiClase {

  constructor() {
    this.atributo="hola";
  }

  ir() {
    console.log(this.atributo);
  }

  addOnClick() {
  console.log('add');  document.getElementById('test').innerHTML='hola';
  }
}

let obj= new MiClase();

obj.ir();
obj.addOnClick();

#test {
height: 100px;
width: 100px;
border: 1px solid black;
}

Por tanto, tienes que definir la función fuera del componente para que sea accesible:

class MiClase {

  constructor() {
    this.atributo="hola";
  }

  ir() {
    console.log(this.atributo);
  }

  addOnClick() {
  console.log('add');  document.getElementById('test').innerHTML='hola';
  }
}

let obj= new MiClase();
let ir= obj.ir.bind(obj);
obj.addOnClick();
#test {
height: 100px;
width: 100px;
border: 1px solid black;
}


text:
Q: Transforming $\tan{\phi} = c_1 \tan{\phi_1}+ c_2 \tan{\phi_2}$ into the form $\phi = d_1 \phi_1 + d_2 \phi_2$ my problem is that I am trying to transform this trigonometric expression:
$$\tan{\phi} = c_1 \tan{\phi_1}+ c_2 \tan{\phi_2}$$
to the form: $$\phi = d_1 \phi_1 + d_2 \phi_2$$
Note: Here $c_1$ = $\frac{\beta_1}{\beta_1+\beta_2}$ and $c_2$ = $\frac{\beta_2}{\beta_1+\beta_2}$
My basic aim is to represent $c_1$ as $f_1(d_1,d_2, \phi_1, \phi_2, \phi)$ and $c_2$ as $f_2(d_1,d_2, \phi_1, \phi_2, \phi)$ by comparing the coefficients. But the final form is necessary meaning that the comparison of coefficients is done only after the given form $d_1 \phi_1 + d_2 \phi_2$ is attained on the RHS.
I would be really grateful if someone could help me out with this. Also if someone could suggest someother method for this function estimation, that could also be of great help. Thanks in advance.

A: If i understand right, you can write
$$\frac{\tan(\phi_1)}{c_1^2+c_2^2}+\frac{c_2}{c_1^2+c_2^2}\tan(\phi_2)$$

A: To simplify the notation, let's write
$$
\tan z = a\tan x + b\tan y
$$
Then, for $-\pi / 2 < x,y < \pi/2$ we want to express $z$ as
$$
z(x,y) = \arctan (a\tan x + b\tan y) = f(x,y)x + g(x,y)y
$$
(we omit to indicate $a$ and $b$ among the variables of the functions).
As a first step, we have that
$$
\left\{ \matrix{
  z(0,0) = 0 \hfill \cr
  z(x,0) = \arctan (a\tan x) = f(x,0)x \hfill \cr
  z(0,y) = \arctan (b\tan y) = g(0,y)y \hfill \cr}  \right.
$$
Expanding into series
$$
\eqalign{
  & f(x,0)x = z(x,0) = \arctan (a\tan x) =   \cr
  &  = ax - {a \over 3}\left( {a^{\,2}  - 1} \right)x^{\,3}  + O\left( {a^{\,5} x^{\,5} } \right)\quad  \Rightarrow   \cr
  &  \Rightarrow \quad f(x,0) = a - {a \over 3}\left( {a^{\,2}  - 1} \right)x^{\,2}  + O\left( {a^{\,5} x^{\,4} } \right)  \cr
  &  \Rightarrow \quad g(0,y) = b - {b \over 3}\left( {b^{\,2}  - 1} \right)y^{\,2}  + O\left( {b^{\,5} y^{\,4} } \right) \cr}
$$
That hints to the fact that we can write
$$
\eqalign{
  & z(x,y) = \arctan (a\tan x + b\tan y) =   \cr
  &  = ax + by + \left( {{{\arctan (a\tan x + b\tan y) - ax - by} \over {x + y}}} \right)\left( {x + y} \right) =   \cr
  &  = \left( {{{\arctan (a\tan x + b\tan y) + \left( {a - b} \right)y} \over {x + y}}} \right)x +   \cr
  &  + \left( {{{\arctan (a\tan x + b\tan y) + \left( {b - a} \right)x} \over {x + y}}} \right)y \cr}
$$


text:
Q: RJAGS unable to find appropriate sampler when constraining covariance matrix I am using RJAGS to make inference on mean and covariance matrix from some data and I noticed that whenever I put a constraint in the precision matrix I receive the following error message

Error in jags.model(file = "model.tmp", data = data) : Error in node
  B Unable to find appropriate sampler

Here is a minimal example where I multiply mean and precision matrix by a constant vector.
Note that the error message appears only when the precision matrix is rescaled. For some reason RJAGS is fine with rescaling the mean only.
In this simple case obviously I could have rescaled the data by A0 first, however I want to be able to do it when A0 is not known in advance. Any ideas?
model="model {

     for(i in 1:N){
         X[i,1:3] ~ dmnorm(An,Bn)
     }

     B ~ dwish(B0,3)

     for(i in 1:3){
         An[i]=A[i]*A0[i]
         for(j in 1:3){
             Bn[i,j]=B[i,j]*A0[i]
         }
     }

     for(i in 1:3){
         for(j in 1:3){
             B0[i,j]=equals(i,j)*1e-3
         }
     }

     A ~ dmnorm(c(0,0,0),B0)

}"

X=matrix(rnorm(300,0,1),ncol=3)

data=list(X=X,N=nrow(X),A0=c(1,2,2));

varnames=c("A","B","S")

burn_in=100;
steps=10000;
thin=1;

fileConn=file("model.tmp")
writeLines(model,fileConn);
close(fileConn)

m=jags.model(file="model.tmp",data=data);
update(m,burn_in)
draw=jags.samples(m,steps,thin=thin,variable.names=varnames)


text:
Q: Java creating histogram method can someone help me to understand this code? public class Library {

    public static int[] histogram(int a[],int M) {
        int[] newArr = new int[M];

        //Fill the new array
        try {
        if(a.length<M)
            System.out.println("Array lenght should be "
                    + "bigger than the number");
        else

            for(int i = 0; i < a.length; i++){
                int count = a[i];

                newArr[count] ++;
            }

        }
        catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.getMessage());
        }

        //return the array
        return newArr;
    }

    public void printArray(int s[]) {
        int position = 0;
        for (int i = 0; i < s.length; i++) {
            System.out.print(position+" ");
            position++;
        }
        System.out.println();

        for (int i = 0; i < s.length; i++) {
            System.out.print(s[i]+" ");
        }
    }

    public static void main(String[] args) {

        Library l1 = new Library();

        int J = 5;
        int[] w = {1,2,0,1,2,3};

        l1.printArray(histogram(w,J));

    }
}

I wrote this and some of the parts I looked at from google and other sources but I couldn't understand the else part in public static int[] histogram
        else

            for(int i = 0; i < a.length; i++){
                int count = a[i];

                newArr[count] ++;
            }

How does this newArr[count] ++; works can someone explain to me, please

A:
` How does this newArr[count] ++; works can someone explain to me, please

Two thins are happening on this one line.

*

*We get the reference to value in position count from newArr array.

*We increment it by 1.

Therefore if you have array newArr = [1,2,3] calling newArr[0]++ would result in you having the following state of newArr as [2,2,3].
If something is still unclear, respond with a comment to this answer.


text:
Q: Using Materialize Cards Conflict with Modal View I am trying to use Materialize Cards along with a separate button next to it to show a modal view. Everything seems to works fine, but when I click the modal, the modal content doesn't show in the prescribed values in the CSS, such as the height of the modal view and the associated darkened backdrop shade when the modal view is activated(it stop half way on the page). When I disable <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> it works but then the Materialize content fails. Is there a way to make everything work both the Materialize content and the modal view height and darkened background shade?
HTML:

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

      <button id="myBtn">Open Modal</button>

                  ×
                    <form id="msform">
                      <fieldset>

Create Discount

Step 1

                        <input type="button" name="next" class="next action-button" value="Next" />
                      </fieldset>
                    </form>

CSS:
/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 1000%; /* Full height */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
  /* background-color: #fefefe; */
  background: linear-gradient(-45deg, #89f7fe 0%, #66a6ff 60%, #23A6D5, #23D5AB);
  margin:auto;
  padding: 20px;
  border: 1px solid #888;
  width: 500px;
  height: 500px

}

A: I was able to figure it out-I just had to make the height to "max-height" in .modal; having just height caused the problem but having just "height" worked before the importation of <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">


text:
Q: Iterate pages and crawler HTML tables in Python I try to crawler the tables from this link, I have get position of table content by using F12 inspect.

I have use the follow code, but I get None result, someone could help? Thanks.
import requests
import json
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup

url = 'http://bjjs.zjw.beijing.gov.cn/eportal/ui?pageId=308894'

website_url = requests.get(url).text
soup = BeautifulSoup(website_url, 'lxml')
table = soup.find('table', {'class': 'gridview'})
#table = soup.find('table', {'class': 'criteria'})

print(table)

Please also check this reference, in fact, I want do the similar things here, but the web structure seems different.
Updated:
The following code works for one page, but I need to loop other pages as well.
import requests
import json
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup

url = 'http://bjjs.zjw.beijing.gov.cn/eportal/ui?pageId=308894'

website_url = requests.get(url).text
soup = BeautifulSoup(website_url, 'lxml')
table = soup.find('table', {'class': 'gridview'})
#https://stackoverflow.com/questions/51090632/python-excel-export
df = pd.read_html(str(table))[0]
df.to_excel('test.xlsx', index = False)

Output:
   序号  ...      竣工备案日期
0   1  ...  2020-01-22
1   2  ...  2020-01-22
2   3  ...  2020-01-22
3   4  ...  2020-01-22
4   5  ...  2020-01-22

[5 rows x 9 columns]

Reference related:
https://medium.com/analytics-vidhya/web-scraping-wiki-tables-using-beautifulsoup-and-python-6b9ea26d8722

A: You can get elements in <tr>... </tr> tags like :
table = soup.find_all('table', {'class': 'gridview'})

for elements in table:
    inner_elements = elements.findAll('tr')[1:]

    for text_for_elements in inner_elements:
        print(text_for_elements.text)

OUTPUT :
1
朝阳区东三环北路38号院4号楼3层301室内局部装修工程
威沃克办公服务(北京)有限公司
袁永懿
上海东园建筑装饰有限公司
陈振华
0065朝竣2020(装)0053号
北京市朝阳区住房和城乡建设委员会
2020-01-22
2
北京市朝阳区新源南路3号14层04单元A1704室内装修工程
重庆金融资产交易所有限责任公司
罗珊珊
深圳安星建设集团有限公司
张惠富
0066朝竣2020(装)0054号
北京市朝阳区住房和城乡建设委员会
2020-01-22
......


text:
Q: AngularJs: Node is undefined Using Angular JS on IE11 is causing "Node is undefined" error. This is the script.

    <title>Show Fruit</title>
    <link href="include/styles.css" rel="stylesheet">

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=11" />

Actors' Favorite Fruits

{{navTitle}}

            {{f.name}}

Works fine on Firefox and Chrome. Checked everywhere for IE11 related problems with Angular JS. Any help is appreciated.
Thankx
Complete index.jsp

    <title>Show Fruit</title>
    <link href="include/styles.css" rel="stylesheet">

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <meta name="viewport" content="width=device-width, initial-scale=1">

Actors' Favorite Fruits

{{navTitle}}

            {{a.name}}

        <image src="{{actor.image}}" width="220">

        <form>

                    <input type="text" ng-model="searchName" size="30">
                    <button type="button" ng-click="searchActor(searchName)" class="btn btn-primary btn-sm">
                     Search </button>
                    <button ng-click="addNew()" class="btn btn-primary btn-sm">
                     Add New </button>
                    <button ng-click="resetSearch()"  class="btn btn-info btn-sm">
                     Reset Search </button>

        </form>

        <form id="main">

                    ID:

                    <input id="id" type="text" ng-model="actor.id" size="4">

                    Fruit:

                    <input type="text" ng-model="actor.name" size="30">

                    Favorite Fruit Of:

                    <input type="text" ng-model="actor.birthName" size="40">

                    Birth Date:

                    <input type="text" ng-model="actor.birthDate" size="20">

                    Email:

                    <input type="text" ng-model="actor.email" size="30">

                    Image:

                    <input type="text" ng-model="actor.image" size="80">

                    IsActive:

                    <input type="text" ng-model="actor.active" size="10">

                          <button ng-click="saveActor(actor.id)" class="btn btn-success btn-sm" title="Save actor's details..." ng-disabled="isSaveDisabled">
                           Save </button>
                          <button ng-click="deleteActor(actor.id)" class="btn btn-danger btn-sm" ng-disabled="isDeleteDisabled">
                           Delete </button>

        </form>

AngularJS Demo

Complete app.js
(function() {

var app = angular.module("app", ['ngRoute']);
app.config(function($routeProvider) {
    $routeProvider
        .when('/home', {
            templateUrl: 'index.jsp',
            controller: 'HttpCtrl'
        })
        .otherwise({
            redirectTo: '/homev'
        });
});

app.controller("HttpCtrl", function($scope, $http) {
    var app = this;
    $scope.navTitle = 'All Stars';
    $scope.operation="";
    $scope.isSaveDisabled = true;
    $scope.isDeleteDisabled = true;

    var response = $http.get('/AngularWs/rest/actors/');
    response.success(function(data) {
        $scope.actors = data;
        console.log("[main] # of items: " + data.length)
        angular.forEach(data, function(element) {
            console.log("[main] actor: " + element.name);
        });
    })
    response.error(function(data, status, headers, config) {
        alert("AJAX failed to get data, status=" + status);
    })

    $scope.getActor = function(id) {
        var response = $http.get('/AngularWs/rest/actors/'+ id );

        response.success(function(data) {
            $scope.actor = data;
            $scope.operation="update";
            $scope.isSaveDisabled = false;
            $scope.isDeleteDisabled = false;
        })

        response.error(function(data, status, headers, config) {
            alert("AJAX failed to get data, status=" + status);
        })
    };

    $scope.searchActor = function(name) {
        var app = this;
        $scope.navTitle = 'Search Criteria';

        var response = $http.get('/AngularWs/rest/actors/search/' + name);
        response.success(function(data) {
            $scope.actors = data;
            $scope.$apply();

            console.log("[searchActor] # of items: " + data.length)
            angular.forEach(data, function(element) {
                console.log("[searchActor] actor: " + element.name);
            });

        });

        response.error(function(data, status, headers, config) {
            alert("AJAX failed to get data, status=" + status);
        })
    };

    $scope.clearForm = function() {
        $scope.actor = {
                id:'',
                name:'',
                birthName:'',
                birthDate:'',
                email:'',
                image:'',
                active:''
        };
    }

    $scope.addNew = function(element) {
        $scope.operation="create";
        $scope.clearForm();
        main.id.focus();
        $scope.isSaveDisabled = false;
        $scope.isDeleteDisabled = true;
    }

    $scope.saveActor = function(id) {
        $scope.jsonObj = angular.toJson($scope.actor, false);
        console.log("[update] data: " + $scope.jsonObj);

        if ($scope.operation == "update") {
            var response = $http.put('/AngularWs/rest/actors/' + id, $scope.jsonObj);
            response.success(function(data, status, headers, config) {
                $scope.resetSearch();
            });

            response.error(function(data, status, headers, config) {
                alert("AJAX failed to get data, status=" + status);
            })
        } else if ($scope.operation == "create") {
            var response = $http.post('/AngularWs/rest/actors/add', $scope.jsonObj);
            response.success(function(data, status, headers, config) {
                $scope.resetSearch();
            });

            response.error(function(data, status, headers, config) {
                alert("AJAX failed to get data, status=" + status);
            })
        }
    };

    $scope.deleteActor = function(id) {
        var response = $http.delete('/AngularWs/rest/actors/' + id);
        response.success(function(data, status, headers, config) {
            $scope.resetSearch();
        });

        response.error(function(data, status, headers, config) {
            alert("AJAX failed to get data, status=" + status);
        })
    };

    $scope.resetSearch = function(name) {
        var app = this;
        $scope.operation="";
        $scope.clearForm();
        $scope.isSaveDisabled = true;
        $scope.isDeleteDisabled = true;
        $scope.navTitle = 'All Stars';
        $scope.searchName = '';

        var response = $http.get('/AngularWs/rest/actors/');
        response.success(function(data) {
            $scope.actors = data;
            $scope.$apply();
            console.log("[resetSearch] # of items: " + data.length)
        });

        response.error(function(data, status, headers, config) {
            alert("AJAX failed to get data, status=" + status);
        })
    };

});
})();

A: I had the same problem and found a solution. In my case I was testing with my app running from a local (intranet) server, and IE11 was set to run intranet sites in "compatibility view" mode. Changing that made the problem go away.
To do this just click on the gear icon, and then select "Compatibility View settings" from the menu. In the dialog that comes up make sure "Display intranet sites in Compatibility View" is unchecked and close it.


text:
Q: How do I force my package to be loaded right after open the IDE or a project? Code's like below, similar to the built-in Custom Tool Window code template.
To load the package I have to find the ToolWindow button (Command) and press it. When I open up a folder this package is not loaded.
However this extension depends on evnets provided by some services (IVsFileChangeEx, .etc), and they needed to be loaded by AsyncPackage.GetServiceAsync. What should I do?
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(Guids.packageGuidStr)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideToolWindow(typeof(ToolWindow))]
public sealed class ExuedPackage : AsyncPackage
{
    protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
    {
        await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

        "Init Package".Log();

        .... Get some services and store them ...
        .... Register callbacks to them ....

        await ToolWindowCommand.InitializeAsync(this);
    }
}


text:
Q: Implement stack's push method in a static array, but the program should also work if number of pushes > initial array size This is my first time doing Java as a part of college assignment where I have to implement Stack data structure, but the challenge is to make the code work for pushes greater than the initial array size. I am not allowed to work with ArrayList in this assignment. I can only use static array and resize when needed by copying contents to a new array and reassigning the old array as new array.
I try to achieve this using if condition which determines if the counter (which initially is 0, increases as the number of push increases) is greater than the initially defined size of the array.
Then I created a new method called stackextender where I put exceeding values in a new array called extensionstack. Then on a method mystackmodifier, I create a temparray and put contents of original stack and extensionstack in the temparray. At last i do mystack = temparray to copy the contents to my original stack. I think the code is having problem in this function (mystackmodifier),where I am modifying the contents of initial stack. The code is posted below:
public class StackOperations{
    int mystack[];
    int global_size;
    int counter = 0;
    int newcounter = 0;
    int extensionstack[] = new int[counter*2];

    public StackOperations(int size){
        this.mystack = new int[size]; //create a stack of size as mentioned while creating object
        this.global_size = size; //update the global variable
    }
    //the below method will allow us to calculate the number of

    public void push(int value){
        if (counter<global_size){
        mystack[counter] = value;
        counter += 1;//we have to do this unless counter < stacksize
        }
        else{
            /*so if I have to make my code work for user input greater than my initial stack size,
            I am creating a new method called stackextender where I put new value in a new array called
            extension stack. Then on the method, mystackmodifier I create a temparray and put contents of
            original stack and extensionstack in the temparray. At last i do mystack = temparray to
            copy the contents to my original stack*/

            stackextender(value);
            counter ++;

        }

    }
    //This method puts exceeding values to a new stack called extension stack
    public void stackextender(int value){
        extensionstack[newcounter] = value;
        newcounter ++;
        }
    //This method modifies the contents of original stack
    public void mystackmodifier(){
        int temparray[] = new int[(global_size+newcounter)*2];

        if(extensionstack.length>0){
            int key;
            for ( key = 0; key<mystack.length; key++){
                temparray[key] = mystack[key];
            }
        for (int i = 0; i<newcounter; i++){
            temparray[key+i] = extensionstack[i];
            }
        mystack = temparray;
        }

    }

Below is my main method
import java.util.*;

public class ArrayStack{
public static void main(String args[]){
    StackOperations mystack = new StackOperations(100);
    System.out.println(mystack.toString());
    /*Although the stack size is instantiated as 10, the code works for insertion for as many
    number of items as demonstrated below*/
    for (int i = 0; i<150; i+=1){
        mystack.push(i);
    }

    int stacksize = mystack.getSize();
    if (stacksize == 0) {
        try{
            throw new NoSuchElementException();
        }catch (NoSuchElementException exc){
            exc.printStackTrace();
        }
    }
    System.out.println(mystack.toString());

}

Any help will be highly appereciated


text:
Q: Grunt Connect Prism Mock Server not recording requests My goals is to use grunt-connect-prism (as described here) to catch server requests from my AngularJS app to then use as mock data for protractor E2E tests.
Alternatively, I'm looking for suggestions for better server mock data libraries for Grunt.
This project is still in its infancy, however I thought I'd post my issue anyways: I can't get the mock data saving. When I start my grunt server, I can see the prism running, but it still doesn't save. I read from the comments in the authors post that people were trying to run the 'context' variable as the root which is where my server api runs from. So I tried only recording from the /campaigns endpoint, but with no luck.

$ grunt server
Running "server" task
...
Running "prism" task Prism created for: /campaigns/ to localhost:8888
...

Help!?!?
// Gruntfile.js

grunt.initConfig({
  connect: {
    server: {
      options: {
        keepalive: true,
        hostname: '*',
        port: 8888,
        base: '.tmp',

        middleware: function(connect, options) {
          return [
            require('grunt-connect-prism/middleware'), // will

            modRewrite(['!\\.?(js|css|html|eot|svg|ttf|woff|otf|css|png|jpg|gif|ico) / [L]']),
            mountFolder(connect, '.tmp'),
          ];
        }
      }
    }
  },

  prism: {
    options: {
      mode: 'record',
      mocksPath: './mocks',
      // server
      host: 'localhost',
      port: 8888,
      https: false,
      // client
      context: '/campaigns/',
    }
  },

  // more stuff I removed

});

// development
grunt.registerTask('server', function() {
  grunt.task.run([
    'stuff ...'
    'prism',
    'stuff ...',
  ]);
});

// more stuff I removed

grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-connect-prism');

A: Solved my problem: first of all, I needed to whitelist another port in my Vagrant file...
Secondly I needed to start another grunt connect server to act as a proxy for my serverside calls to run through, separate from my clientside which runs on a different port.
Thirdly, I needed to add Access-Control headers to the server side proxy
// Adding the middleware
connect: {
  // clientside server
  server: {
    options: {
      keepalive: true,
      hostname: '*',
      port: 8888,
      base: 'public/',
      middleware: function(connect, options) {
        return [
          // ... dish static files
        ]
      }
    }
  },

  // serverside proxy
  proxy: {
    options: {
      hostname: '*',
      port: 9000,
      middleware: function(connect, options, middlewares) {
        middlewares.unshift(require('grunt-connect-prism/middleware'));

            // add REST stuff
            middlewares.unshift(function (req, res, next) {
              console.log('proxy', req.url);

              res.setHeader('Access-Control-Allow-Credentials', 'true');
              res.setHeader('Access-Control-Allow-Headers', 'accept, x-version, content-type, authorization');
              res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
              res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
              res.setHeader('Access-Control-Expose-Headers', 'X-Version, X-Maintenance-Mode');
              res.setHeader('Access-Control-Max-Age', '1728000');

              next();
            });
        return middlewares;
      }
    }
  }
},

// Adding prism configuration.
prism: {
  options: {
    mode: 'record',
    mocksPath: 'mocks',
    host: 'localhost',
    port: 3000,
    https: false,
    context: '/',
  }
},

// Running prism
grunt.registerTask('server', [
// ...

'connect:proxy', // proxy server that will log calls to mock
'prism:proxy', // initiates prism library
'connect:server' // client connect server to dish out client files
]);


text:
Q: Extending an object and overriding a procedure without being deferred in Fortran I have a code with lots of different features and methods. Some methods are all for the same feature, i.e. only one among a selection can be selected.
Furthermore, depending on a feature I might need to do modify subroutines elsewhere. So in a loop in routine inject I might have a small if statement asking if I have used feature A, then do a few extra operations.
This is very frustating since different features seems to be connected with others routines very arbirarirly, and can be difficult to maintain.
I have decided to do following to avoid this:
I define an object t_inject with the purpose to execture routine inject.  I rewrite my routine inject such that it contains only the code that is common for all different scenarios.
 type t_inject

 contains

 procedure,nopass :: inject => inject_default
 end type

Now I have another object to handle my feature A in case it is selected.
 type,extends(t_inject) :: t_inject_a

 contains

 procedure, nopass :: inject => inject_a
 end type

My subroutines inject_a and inject have same interface. E.g.
 subroutine inject_a( part )
  type(t_part) , intent(inout) :: part % an external data type
 call inject(part)
 ! do the extra bit of stuff you need to do

 end subroutine

 subroutine inject( part)
   type(t_part) , intent(inout) :: part % an external data type

  ! carry out the default stuff
 end subroutine

Now in my main program
class(t_inject) :: inj

allocate(inj :: t_inject_a)

call inj% inject ( part)

Is that the way you would do it and is it valid?
I initially thought of doing an abstract declared type with a deferred inject procedure  where I then could extent.
But for a very trivial problem I might not need that - I am also wondering whether my call call inj% inject(part) is sufficient for the compiler to know to where to go. Sometimes I see codes which need the class is condition before making the call.

A: I think three points should be modified:

*

*The type-bound procedures need to refer to actual procedure names (via =>). So, I have changed the name of a module procedure inject() to inject_default(). (But please see test2.f90 also).

*We need to attach allocatable to a class variable (e.g., inj2) to allocate it with a concrete type (e.g., t_inject_a).

*In the allocate statement, the name of a concrete type should appear before ::, such that allocate( t_inject_a :: inj2 ).

The modified code may look like this:
!! test.f90
module test_mod
    implicit none

    type t_inject
    contains
        procedure, nopass :: inject => inject_default
    endtype

    type, extends(t_inject) :: t_inject_a
    contains
        procedure, nopass :: inject => inject_a
    endtype

    type t_part    !! some other type
        integer :: x = 100, y = 200
    endtype

contains
    subroutine inject_default( part )
        type(t_part), intent(inout) :: part

        print *, "x = ", part % x
    endsubroutine

    subroutine inject_a( part )
        type(t_part), intent(inout) :: part

        call inject_default( part )
        print *, "y = ", part % y
    endsubroutine
end

program main
    use test_mod
    implicit none
    class( t_inject ), allocatable :: inj1, inj2
    type( t_part ) :: part

    !! Polymorphic allocation with concrete types.
    allocate( t_inject   :: inj1 )
    allocate( t_inject_a :: inj2 )

    print *, "inj1:"
    call inj1 % inject( part )

    print *, "inj2:"
    call inj2 % inject( part )
end

"gfortran-8 test.90 && ./a.out" gives
 inj1:
 x =          100
 inj2:
 x =          100
 y =          200

We can also use a module procedure inject() (rather than  inject_default()) by using procedure, nopass :: inject, for example:
!! test2.f90
module test_mod
    implicit none

    type t_inject
    contains
        procedure, nopass :: inject
        ! procedure, nopass :: inject => inject  !! this also works
    endtype

    type, extends(t_inject) :: t_inject_a
    contains
        procedure, nopass :: inject => inject_a
    endtype

    type t_part    !! some other type
        integer :: x = 100, y = 200
    endtype

contains
    subroutine inject( part )
        type(t_part), intent(inout) :: part

        print *, "x = ", part % x
    endsubroutine

    subroutine inject_a( part )
        type(t_part), intent(inout) :: part

        call inject( part )
        print *, "y = ", part % y
    endsubroutine
end

!! The remaining part (and the result) is the same...

In addition, one can also separate actual procedures like inject() in a different file and use them to define new types like t_inject (see mylib.f90 and test3.f90 below). This might be useful to reuse routines in some library file.
!! mylib.f90
module mylib
    implicit none

    type t_part    !! some other type
        integer :: x = 100, y = 200
    endtype

contains

    subroutine inject( part )
        type(t_part), intent(inout) :: part

        print *, "x = ", part % x
    end
    subroutine inject_a( part )
        type(t_part), intent(inout) :: part

        call inject( part )
        print *, "y = ", part % y
    end
end

!! test3.f90
module test_mod
    use mylib
    implicit none

    type t_inject
    contains
        procedure, nopass :: inject
    endtype

    type, extends(t_inject) :: t_inject_a
    contains
        procedure, nopass :: inject => inject_a
    endtype
end

!! The main program is the same as test.f90.
!! compile: gfortran-8 mylib.f90 test3.f90


text:
Q: Cannot change region because cannot delete payment method because have active subscriptions You are my only hope as I am desperate!
I have moved to a new country, so my old country bank card is now closed. To this card my AppleID is still linked but now it indicates that I must update payment method information. Naturally, the card is closed so a new one has to be given to Apple.
That's what I thought when leaving for a new place: I will add a new card, so Apple could see I have a new land/region card and phone number, once it is accepted, I will be able to change my land/region in the AppleID account settings, and after that I thought, I would be able to safely delete the obsolete old card and all my subscriptions and purchases would seamlessly be transferred to a new card, so any new monthly/yearly subscriptions would be charged from the new card. That was the plan, since that is the only natural way of things I could imagine!
Yet Apple decided to do it painfully. I discovered that I only can add a new card from the same old land/region to which my old card also assigned. It won't allow me to add a card from any other land/region! So, I first need to delete the old card. But I cannot do it either, as there is no "None" option in the list of the payment options. I was notified that I only can do that if there is no active AppleTV subscriptions, iTunes subscriptions etc., unpaid debts,pending charges, etc.
Looks reasonable, I thought, so no one could escape old land/region with Apple money. So I had two pending payments: one from AppleMusic, one from iCloud disk extra storage service. I could not fulfill the charges from my old card, so I purchased AppleGift card from the same old region/land and used it to charge up my AppleID.
A remarkably wonderful detail: Apple took the money for these two payments when I manually pressed "Pay" it attempted to charge my old card, was rejected naturally, pop-up error message box, but after that decided that to take money from AppleID is better than not to take at all)))
So, it took my money from AppleID, but ... IT DID NOT UPDATE THE SERVICES! It did not add a month to Apple Music and it still on free (5Gb) plan for my Apple Storage which is normally 200 Gb (although it shows it is 200 Gb, only 3 Gb is available with 47Gb used... I don't know how to interpret this!)
I cannot upload big files to iCloud storage so I concluded that it did not update the service plan; andirons complains every time I open AppleMusic that a problem is occurred with payment method, so I assume that none of the two services were updated, but money was charged!
Okay, forget it Apple. I manually cancelled regularly occurring subscription payments on the list, including the two services. But AppleTV will be active albeit not automatically renewed, for a month, and some other yearly subscriptions will only expire in a just below a whole year!
On the Apple support page they say that I will be able to remove the payment method when eventually all active subscription will expire, including AppleTV, AppleMusic and any iTunes staff.
Now, that's a long time to wait! Does that really means what it sound? I am so desperate that I am okay to deny my active subscriptions all together, just to set it free and be able to delete the obsolete payment method and add a new payment method according to my new land/region.
Maybe you know some exotic way to make it happen without waiting for every single subscription to expire?
Thank you for every your thought and suggestion,
Take care!
UPD1: Actually Apple says explicitly here that AppleID credit may be used to pay for iCloud storage and Apple Music, App,eTV+ and other Apple services:
https://support.apple.com/lt-lt/HT201209
OBS: NO REGIONAL RESTRICTIONS ARE MENTIONED!
In my observation, however, this only is allowed for iTunes Films, Music, and one-time purchases from AppStore. No subscriptions, Albeith for Apple services, or third-party in-app purchases, are possible in this setup (when the primary payment method is failing).
Thus, if one wants to use any services or app on subscription, one might do either of two things: 1) restore access to the old payment method (impossible in my case) 2) delete the old payment method (also impossible, until every active subscription is expired which would take a year for me).
So does that mean that for a year my iDevices are jailed on quarantine together with me, and there is nothing I can do, no way to forcedly deny active subscriptions, to interrupt them immediately, even at cost of loosing services, just to set the AppleID free at last and make it happen?!
Sergio


text:
Q: Search for a value and add formula to the cell I have a excel sheet as below ( just an  example, i have many rows in actual file)
123
gl_date
334
inv_date
abc

I need to search for 'date' value in all cells and replace the sheet like below
123
to_char(gl_date,'yyyy-dd-mm')
334
to_char(inv_date,'yyyy-dd-mm')
abc

I really appreciate your inputs. Thanks!

A: Populate a helper column with:
=IF(ISERROR(FIND("date",A1)),A1,"to_char("&A1&",'yyyy-dd-mm')")

then copy that column and Paste Special, Values over the top of your source (assumed ColumnA).


text:
Q: Links do not work when the public folder name is underscore, e.g. public_html Problem with links when the folder in the name contains the underscore "_". Why? and how to improve it, because my hosting of the main "public" folder is called "public_html" I changed the name of the directory and below in the code, but then the links do not work for to css and subpages. If I change the name to any other name without underlining, everything works. Unfortunately, I have to use "public_htnl"
<?php
  define("PRIVATE_PATH", dirname(__FILE__));
  define("PROJECT_PATH", dirname(PRIVATE_PATH));
  define("PUBLIC_PATH", PROJECT_PATH . '/public_html');
  define("SHARED_PATH", PRIVATE_PATH . '/shared');

  $public_end = strpos($_SERVER['SCRIPT_NAME'], '/public_html') + 7;
  $doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
  define("WWW_ROOT", $doc_root);

  require_once('functions.php');
?>

functions.php
<?php
function url_for($script_path) {
  // add the leading '/' if not present
  if($script_path[0] != '/') {
    $script_path = "/" . $script_path;
  }
  return WWW_ROOT . $script_path;
}
?>

One of my links
<a href="<?php echo url_for('/home/index.php'); ?>">Home


text:
Q: dig OK but dig @192.168.1.1 NOT why dig works OK, but dig my NetGear router directly doesn't (while first goes to it too, because it is my DNS, NetGear itself has 8.8.8.8 set as prim dns). My NetGear has IP 192.168.1.1 on LAN. Here I attached complete scenario. My analysis of frames shows IMO both requests come to router NetGear 192.168.1.1 on port 53 on top of UDP. Don't differ in anything else, or do they? please help.
only difference apart from different frame numbers and other obvious differences, observable for me is
[Coloring Rule Name: UDP]
[Coloring Rule String: udp]

present in OK frame and lack of it in failed packet (failed - I mean no response at all from 192.168.1.1)
dig cf16.eu

; <<>> DiG 9.9.2-P2 <<>> cf16.eu
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 24482
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;cf16.eu.           IN  A

;; ANSWER SECTION:
cf16.eu.        3600    IN  A   89.75.41.50

;; Query time: 10 msec
;; SERVER: 127.0.1.1#53(127.0.1.1)
;; WHEN: Wed May  8 17:47:05 2013
;; MSG SIZE  rcvd: 52

but:
dig @192.168.1.1 cf16.eu

; <<>> DiG 9.9.2-P2 <<>> @192.168.1.1 cf16.eu
; (1 server found)
;; global options: +cmd
;; connection timed out; no servers could be reached

Wireshark packets:
dig cf16.eu [OK]
No.     Time           Source                Destination           Protocol Length Info
    340 4.775113000    192.168.1.3           192.168.1.1           DNS      78     Standard query 0x5fa2  A cf16.eu

Frame 340: 78 bytes on wire (624 bits), 78 bytes captured (624 bits) on interface 0
    Interface id: 0
    WTAP_ENCAP: 1
    Arrival Time: May  8, 2013 17:47:04.131360000 CEST
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1368028024.131360000 seconds
    [Time delta from previous captured frame: 0.005265000 seconds]
    [Time delta from previous displayed frame: 0.005265000 seconds]
    [Time since reference or first frame: 4.775113000 seconds]
    Frame Number: 340
    Frame Length: 78 bytes (624 bits)
    Capture Length: 78 bytes (624 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ip:udp:dns]
    [Coloring Rule Name: UDP]
    [Coloring Rule String: udp]
Ethernet II, Src: Micro-St_4b:47:dc (d4:3d:7e:4b:47:dc), Dst: Netgear_bb:b7:2c (00:1b:2f:bb:b7:2c)
    Destination: Netgear_bb:b7:2c (00:1b:2f:bb:b7:2c)
        Address: Netgear_bb:b7:2c (00:1b:2f:bb:b7:2c)
        .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)
        .... ...0 .... .... .... .... = IG bit: Individual address (unicast)
    Source: Micro-St_4b:47:dc (d4:3d:7e:4b:47:dc)
        Address: Micro-St_4b:47:dc (d4:3d:7e:4b:47:dc)
        .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)
        .... ...0 .... .... .... .... = IG bit: Individual address (unicast)
    Type: IP (0x0800)
Internet Protocol Version 4, Src: 192.168.1.3 (192.168.1.3), Dst: 192.168.1.1 (192.168.1.1)
    Version: 4
    Header length: 20 bytes
    Differentiated Services Field: 0x00 (DSCP 0x00: Default; ECN: 0x00: Not-ECT (Not ECN-Capable Transport))
        0000 00.. = Differentiated Services Codepoint: Default (0x00)
        .... ..00 = Explicit Congestion Notification: Not-ECT (Not ECN-Capable Transport) (0x00)
    Total Length: 64
    Identification: 0xf650 (63056)
    Flags: 0x00
        0... .... = Reserved bit: Not set
        .0.. .... = Don't fragment: Not set
        ..0. .... = More fragments: Not set
    Fragment offset: 0
    Time to live: 64
    Protocol: UDP (17)
    Header checksum: 0x0108 [correct]
        [Good: True]
        [Bad: False]
    Source: 192.168.1.3 (192.168.1.3)
    Destination: 192.168.1.1 (192.168.1.1)
    [Source GeoIP: Unknown]
    [Destination GeoIP: Unknown]
User Datagram Protocol, Src Port: 47841 (47841), Dst Port: domain (53)
    Source port: 47841 (47841)
    Destination port: domain (53)
    Length: 44
    Checksum: 0x4831 [validation disabled]
        [Good Checksum: False]
        [Bad Checksum: False]
Domain Name System (query)
    Transaction ID: 0x5fa2
    Flags: 0x0120 Standard query
        0... .... .... .... = Response: Message is a query
        .000 0... .... .... = Opcode: Standard query (0)
        .... ..0. .... .... = Truncated: Message is not truncated
        .... ...1 .... .... = Recursion desired: Do query recursively
        .... .... .0.. .... = Z: reserved (0)
        .... .... ..1. .... = AD bit: Set
            [Expert Info (Warn/Security): AD bit set in DNS Query]
                [Message: AD bit set in DNS Query]
                [Severity level: Warn]
                [Group: Security]
        .... .... ...0 .... = Non-authenticated data: Unacceptable
    Questions: 1
    Answer RRs: 0
    Authority RRs: 0
    Additional RRs: 1
    Queries
        cf16.eu: type A, class IN
            Name: cf16.eu
            Type: A (Host address)
            Class: IN (0x0001)
    Additional records
        <Root>: type OPT
            Name: <Root>
            Type: OPT (EDNS0 option)
            UDP payload size: 4096
            Higher bits in extended RCODE: 0x0
            EDNS0 version: 0
            Z: 0x0
            Data length: 0

dig 192.168.1.1 cf16.eu [fail]
No.     Time           Source                Destination           Protocol Length Info
    603 7.972662000    192.168.1.3           192.168.1.1           DNS      78     Standard query 0xc755  A cf16.eu

Frame 603: 78 bytes on wire (624 bits), 78 bytes captured (624 bits) on interface 0
    Interface id: 0
    WTAP_ENCAP: 1
    Arrival Time: May  8, 2013 17:49:36.816366000 CEST
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1368028176.816366000 seconds
    [Time delta from previous captured frame: 0.402535000 seconds]
    [Time delta from previous displayed frame: 0.402535000 seconds]
    [Time since reference or first frame: 7.972662000 seconds]
    Frame Number: 603
    Frame Length: 78 bytes (624 bits)
    Capture Length: 78 bytes (624 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: eth:ip:udp:dns]
Ethernet II, Src: Micro-St_4b:47:dc (d4:3d:7e:4b:47:dc), Dst: Netgear_bb:b7:2c (00:1b:2f:bb:b7:2c)
    Destination: Netgear_bb:b7:2c (00:1b:2f:bb:b7:2c)
        Address: Netgear_bb:b7:2c (00:1b:2f:bb:b7:2c)
        .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)
        .... ...0 .... .... .... .... = IG bit: Individual address (unicast)
    Source: Micro-St_4b:47:dc (d4:3d:7e:4b:47:dc)
        Address: Micro-St_4b:47:dc (d4:3d:7e:4b:47:dc)
        .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)
        .... ...0 .... .... .... .... = IG bit: Individual address (unicast)
    Type: IP (0x0800)
Internet Protocol Version 4, Src: 192.168.1.3 (192.168.1.3), Dst: 192.168.1.1 (192.168.1.1)
    Version: 4
    Header length: 20 bytes
    Differentiated Services Field: 0x00 (DSCP 0x00: Default; ECN: 0x00: Not-ECT (Not ECN-Capable Transport))
        0000 00.. = Differentiated Services Codepoint: Default (0x00)
        .... ..00 = Explicit Congestion Notification: Not-ECT (Not ECN-Capable Transport) (0x00)
    Total Length: 64
    Identification: 0xf651 (63057)
    Flags: 0x00
        0... .... = Reserved bit: Not set
        .0.. .... = Don't fragment: Not set
        ..0. .... = More fragments: Not set
    Fragment offset: 0
    Time to live: 64
    Protocol: UDP (17)
    Header checksum: 0x0107 [correct]
        [Good: True]
        [Bad: False]
    Source: 192.168.1.3 (192.168.1.3)
    Destination: 192.168.1.1 (192.168.1.1)
    [Source GeoIP: Unknown]
    [Destination GeoIP: Unknown]
User Datagram Protocol, Src Port: 37226 (37226), Dst Port: domain (53)
    Source port: 37226 (37226)
    Destination port: domain (53)
    Length: 44
    Checksum: 0x09f5 [validation disabled]
        [Good Checksum: False]
        [Bad Checksum: False]
Domain Name System (query)
    Transaction ID: 0xc755
    Flags: 0x0120 Standard query
        0... .... .... .... = Response: Message is a query
        .000 0... .... .... = Opcode: Standard query (0)
        .... ..0. .... .... = Truncated: Message is not truncated
        .... ...1 .... .... = Recursion desired: Do query recursively
        .... .... .0.. .... = Z: reserved (0)
        .... .... ..1. .... = AD bit: Set
            [Expert Info (Warn/Security): AD bit set in DNS Query]
                [Message: AD bit set in DNS Query]
                [Severity level: Warn]
                [Group: Security]
        .... .... ...0 .... = Non-authenticated data: Unacceptable
    Questions: 1
    Answer RRs: 0
    Authority RRs: 0
    Additional RRs: 1
    Queries
        cf16.eu: type A, class IN
            Name: cf16.eu
            Type: A (Host address)
            Class: IN (0x0001)
    Additional records
        <Root>: type OPT
            Name: <Root>
            Type: OPT (EDNS0 option)
            UDP payload size: 4096
            Higher bits in extended RCODE: 0x0
            EDNS0 version: 0
            Z: 0x0
            Data length: 0

A: in this scenario, your router is acting as a DNS server for local requests and acts as a forwarder for unknown addresses, making the query on the 8.8.8.8 server, processing the response, and then sending back a packet indicating the result. if you use dig without a server reference, it uses the root zone to resolve, and you router will forward the lookup on to the root servers for resolution.
When you specify a server in dig, you are usually attempting to determine if the zone you have just created/imported is working fine on this server, so forwarding cannot be allowed to occur or it would hide a potential failure on the server you are specifically attempting to test. you are not saying "give me info about this domain", but instead "give me the info this specific server has about this domain".
since the domain in questions does not reside in a zone that actually exists on the router, you get no response.
See more info here:
http://en.wikipedia.org/wiki/Dig_%28command%29

When a specific name server is not specified in the command
  invocation, it will use the operating systems default resolver,
  usually configured via the resolv.conf file. Without any arguments it
  queries the DNS root zone.


text:
Q: Symfony5 fixtures with order - getOrder() doesn't work When I added new fixtures file
/**
 * {@inheritdoc}
 */
public function load(ObjectManager $manager): void
{
    // get user fixtures
    $user = $this->getReference(LoadUserData::USER_REFERENCE);
    $userSecond = $this->getReference(LoadUserData::USER_TWO_REFERENCE);

    $productFirst = Product::create($user, 'title1', 'title1', 'description3', null, null);
    $manager->persist($productFirst);

    $productSecond = Product::create($user, 'title2', 'title2', 'description2', null, null);
    $manager->persist($productSecond);

    $productThird = Product::create($userSecond, 'title3', 'title3', 'description3', null, null);
    $manager->persist($productThird);

    $manager->flush();
}

/**
 * @return array
 */
public static function getGroups(): array
{
    return ['demo', 'default'];
}

I caught error

purging database

loading DataFixtures\LoadUserData

In ReferenceRepository.php line 154:

Reference to "ROLE_USER" does not exist

Class LoadRoleData has method getOrder(), but it doesn't work.
public function getOrder()
{
    return 1; // the order in which fixtures will be loaded
}

Earlier all were done.

purging database

loading DataFixtures\LoadRoleData

loading DataFixtures\LoadUserData

...

UPDATE:
Class LoadUserData has
    /**
     * {@inheritdoc}
     */
     public function getDependencies()
     {
        return [
            LoadRoleData::class
        ];
     }

But it doesn't work too ((
How can I set order for Role Fixtures in Symfony5?

A: Instead of you deciding on the order of inserting fixtures, you should let Symfony decide.
To do that, your fixture classes should implement DependentFixtureInterface and override method getDependencies(). In your case, it should look like this:
<?php

namespace App\DataFixtures;

class LoadUserData extends Fixture implements DependentFixtureInterface
{

    public function getDependencies()
    {
        return [
            LoadRoleData::class,
        ];
    }

}

Now, Symfony will know that it needs to insert LoadRoleData first.
Using DependentFixtureInterface, you should never worry about the order of inserting if you have set up dependencies correctly.


text:
Q: Odd Inode/Ram cache drops happening in CentOS I run a CentOS 5.7 machine (64bit) with 24GB ram and 4x SAS drives in RAID10 setup.
This machine runs nginx/1.0.10, php-fpm & xcache. About a month back the RAM usage of this machine has changed.
About every few hours the 'CACHE' is flushed from the RAM, this happens exactly when the 'Inode table usage' drops. I'm pretty sure these drops are related. (see the 2 attached images).

This server hosts quite a lot of small files (20M all a few KB big). Not many files are deleted (maybe 100 per hour (total size a few MB max)), not enough to account for the huge Inode table drops.
I also have no crons running which could cause these drops.
Sar -r output: http://pastebin.com/C4D0B79i
My question: Why are these huge RAM/Inode usage drops happening? How can I get Nginx/PHP to use all of my servers RAM?


text:
Q: Parse Json in Umbraco razor How can i parse this Json:
[{
"value": "",
"date": {
  "value": "17/04/2015"
},
"hour": {
  "value": "21:00"
},
"venue": {
  "value": "some stadium."
}},  {
"value": "",
"date": {
  "value": "18/04/2015"
},
"hour": {
  "value": "20:30"
},
"venue": {
  "value": "some stadium"
}}]

I tried this code:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

foreach (var item in serializer.Serialize(item.dates))
{
   @* item == "34 ''" *@
}

but its return string "34 ''" instead what i want.
can someone help me to understand what i missed?
Thanks

A: You should use the DeserializeObject-Method instead of the Serialize-Method.
It returns an object[] which contains Dictionary<string, object>-Elements (your data)
To get the values from the array, cast the current Item to a Dictonary<string, object> (represents a json object) and access the value with the indexer.
Example:
var v = new JavaScriptSerializer();
        var arr = (object[]) v.DeserializeObject(File.ReadAllText("json.txt"));
for (var i = 0; i < arr.Length; i++)
{
    Console.WriteLine(((Dictionary<string, object>)arr[i])["value"]);
}

Example 2 - Access the value inside of the date object:
var v = new JavaScriptSerializer();
var arr = (object[])v.DeserializeObject(File.ReadAllText("json.txt"));
for (var i = 0; i < arr.Length; i++)
{
    // The current object
    var c = (Dictionary<string, object>) arr[i];
    // Getting the date object
    var date = (Dictionary<string, object>) c["date"];
    // Printing the value inside of the date object
    Console.WriteLine(date["value"]);

    // OUTPUT:
    // 17/04/2015
    // 18/04/2015
}


text:
Q: Sum cells from a workbook and paste in another workbook I have 2 workbooks and I need to copy the sum of 2 cells in a cell of another workbook. I'm copying values normaly, but in one case I need to copy the sum of 2 cells. I'm trying with this code, but it doesn't work:
Sub Excel_Excel()
Dim x As ThisWorkbook
Dim y As Workbook
Dim Total As Double

Application.ScreenUpdating = False
Application.DisplayAlerts = False

''allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
''make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
''determine what choice the user made
If intChoice <> 0 Then
''get the file path selected by the user
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)

End If

'## Open workbook:
Set y = Workbooks.Open(strPath)

'Now, copy what you want from y:
y.Sheets("Deducciones").Range("F70:F86").Copy
'Now, paste to ThisWorksheet x:
ThisWorkbook.Sheets("Deducciones").Range("rngdeducciónID").PasteSpecial    xlPasteValues

'Define range that you need to sum, sum it and copy:
range1 = y.Sheets("Deducciones").Range("F87:F88")
Total = WorksheetFunction.Sum(Range(range1))
y.Sheets("Deducciones").Total.Copy
'Now, paste to ThisWorksheet x:
ThisWorkbook.Sheets("Deducciones").D86.PasteSpecial

'Close y:
y.Close

End Sub

This code is not working: Total = WorksheetFunction.Sum(Range(range1))

A: How about doing it like below:
Sub Excel_Excel()
Dim x As ThisWorkbook
Dim y As Workbook
Dim Total As Double

Application.ScreenUpdating = False
Application.DisplayAlerts = False

''allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
''make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
''determine what choice the user made
If intChoice <> 0 Then
''get the file path selected by the user
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)

End If

'## Open workbook:
Set y = Workbooks.Open(strPath)

'Now, copy what you want from y:
y.Sheets("Deducciones").Range("F70:F86").Copy
'Now, paste to ThisWorksheet x:
ThisWorkbook.Sheets("Deducciones").Range("rngdeducciónID").PasteSpecial xlPasteValues

'Define range that you need to sum, sum it and add to variable Total:
Total = WorksheetFunction.Sum(y.Sheets("Deducciones").Range("F87:F88"))
'Now, pass the value of Total to ThisWorksheet x:
ThisWorkbook.Sheets("Deducciones").Range("D86").Value = Total

'Close y:
y.Close
End Sub


text:
Q: How does this transformation happen? $$
ax^2+2hxy+by^2 = a\left(x+ \frac{h}{a}y \right)^2 + \frac{ab-h^2}{a}y^2
$$
How do I go from the equation on the LHS to the equation on the right hand side? My study material mentions "completing the square", which I know but I can't understand how it applies to this particular equation.

A: *

*Factor out $a$, this will leave $a(x^2+2(h/a)xy + (b/a)y^2)$

*To make a perfect square $(x+v)^2=x^2+2xv+v^2$ so $2xv$ must match your middle term $2hxy/a$ so let $v=hy/a$ and add and subtract $v^2$. You get $$a\left(x + \frac{h}{a}y\right)^2 - (hy/a)^2 + (b/a)y^2.$$

Can you now finish it?

A: Remember the following identity. $$ a^2+2ab+b^2 =(a+b)^2$$
The process is called completing  the square.
first we divide by $a$ to get $$ ax^2+2hxy+by^2 =a(x^2+2(h/a)xy + (b/a)y^2)$$
Then we add and subtract $$    (h/a)^2y^2$$ to the first two terms to make a perfect square.$$ a(x^2+2(h/a)xy +(h/a)^2y^2 -(h/a)^2y^2 + (b/a)y^2)=$$
$$ a[(x + (h/a)y)^2 -(h/a)^2y^2 + (b/a)y^2)]=$$
$$a\left(a+ \frac{h}{a}y \right)^2 + \frac{ab-h^2}{a}y^2$$

A: For completing the square the coefficient of $\,x^2$ should be one ,so factor out $\,a$ then complete the square as normal with the coefficient of $\,y$ being $\,\frac{2hx}{a}$
ie.
$\,ax^2+2hxy+by^2 $
$= a(x^2+\frac{2hxy}{a}+\frac{by^2}{a}) $
$= a(x^2+\frac{2hxy}{a}+\frac{by^2}{a}+(\frac{hy}{a})^2-(\frac{hy}{a})^2)$
$ = a\big((x +\frac{h}{a}y)^2 -\frac{h^2y^2}{a^2} + \frac{by^2}{a})$
$ = a\big((x +\frac{h}{a}y)^2 + \frac{bay^2-h^2y^2}{a^2})$
$ = a(x +\frac{h}{a}y)^2 + y^2\frac{ba-h^2}{a}$


text:
Q: Bug in MPI code I am trying to do LU decomposition using MPI.
Below is the snapshot of my code:
if(rank == 0)
{
   //Send to each processor the row it owns
    for(p=0;p<n;p++)
    {
       if(map[p]!=0)
       {
         MPI_Send(&LU[p*n],n,MPI_DOUBLE,map[p],1,MPI_COMM_WORLD);
         printf("Sending row %d to %d  itr = %d\n",p,map[p],i);
       }
    }
}
else
{
  printf("in else rank = %d\n",rank);

  for(l=0;l<n;l++)
  {
    if(map[l] == rank)
    {
      printf("in loop itr = %d, rank = %d l = %d  n = %d\n",i,rank,l,n);
      MPI_Recv(&LU[l*n],n,MPI_DOUBLE,0,1,MPI_COMM_WORLD,&st);
      printf("Recv row %d at %d count = %d itr = %d\n",l,rank,count,i);
    }
  }
}

In this, if rank is zero, I am sending the row to each processor which will be the owner of this row and will perform the computation.
Otherwise, it will receive the rows corresponding to it. The loop is for multiple rows belonging to the same processor. Also map is a array private to each processor and stores the mapping information of each row.
However, after running my program for a 10*10 matrix for 4 instances,
execution gets blocked
It works fine for 1st iteration of i (all the code is inside this loop) but not for successive iterations.
EDIT:
The above code is a part of  the code of LU decomposition.
 We are  trying to achieve the following through the snapshot code
Consider 4 processors P0,P1,P2,P3 and a 10*10 matrix .
map will contain 0,1,2,3,0,1,2,3,0,1 which contains which processor is the owner of which row of the matrix . Through the send it is sending each row of the matrix to be worked on by each processor , i.e. P0 would send rows 1,5,9 to P1 , rows 2,6 to P2 and rows 3,7 to P3.
Each processor would in turn will receive the rows meant for it, through receive in the else part.
However my execution is getting blocked if I run this code.

A: It looks like your sends and receives aren't matching up.
Remember that the way MPI works is that each time you send a message, there must be a matching receive call on the other end (and vice versa). In your case, you're sending one message from rank 0 to each other process (n sends), and each other process is posting n receives from rank 0. If you count these up, this means you are n-1 sends short on the side of rank 0.
Visually:
0: Send(1)[MATCHED] - Send(2)[MATCHED] - Send(3)[MATCHED]
1: Recv(0)[MATCHED] -     Recv(0)      -     Recv(0)
2: Recv(0)[MATCHED] -     Recv(0)      -     Recv(0)

More than likely, you only need to have one receive call posted by all of the ranks other than 0.
Alternatively, if your model is that you're having rank 0 send a bunch of data to each other rank, a better match for your program would probably be to use MPI_SCATTER. This call will take a large array of data from the root rank (in your case, rank 0), break it up, and send it to all of the other ranks in the communicator. That's probably what you need.

A: Thanks for your help
The reason for blocking was not this loop , but another recv waiting for send.


text:
Q: Metric tensor and imaginary time I just started a re-reading of the Conformal Field Theory yellow book by Di Francesco et al. In chapter two, after defining imaginary time $\tau$ as $t=-i\tau$, the authors state that the metric tensor, being in real time, e.g., $g_R=\mbox{diag}(1,-1,-1,-1)$, becomes in imaginary time $g_I=\mbox{diag}(1,1,1,1)$.
How can this statement be proven? I know it is a maybe stupid question, but I can't figure it out. For instance, if I consider the covariant four-vector $x^\mu_R=(t,x_0,x_1,x_2)$, the contravariant vector becomes, by application of $g_R$, $x_{R,\mu}=(t,-x_0,-x_1,-x_2)$. Performing Wick rotation, they become $x^\mu_I=(-i\tau,x_0,x_1,x_2)$ and $x_{I,\mu}=(-i\tau,-x_0,-x_1,-x_2)$, that are not transformed into each other by $g_I$! Where does my argument breaks?

A: *

*By standard convention the Euclidean signature is $(+,+,+,+)$, not $(-,-,-,-)$.

*From a pedagogical perspective, it is therefore easier to explain the Wick rotation using the $(-,+,+,+)$ Minkowski signature convention.

*The opposite Minkowski signature convention $(+,-,-,-)$ is in principle also possible, but it's likely to confuse the h... out of everyone because somewhere along the line a not-so-natural-looking convention choice must be made.

*Related Phys.SE post: Transferring from vectors and tensors in $(-+++)$ signature to $(+---)$ signature?

A: For convenience, the Euclidean metric in this case must be $(----) $. Moreover, $x^{\mu}_I \equiv (\tau ,\vec x) $


text:
Q: Question about output of a function I'm pretty new to programming in Mathematica and have a question. I wrote this function to factorise large numbers. The outputs are almost as expected, but I don't understand where the null's come from. How do I get rid of those? The first example should output 1229, the second should output nothing. Any help appreciated.
In[87]:= pollardrho[n_] := Module[{x, y, d},
x = 2;
y = 2;
d = 1;
g[x_] := Mod[x^2 + 1, n];
While[d == 1,
    x = g[x];
    y = g[g[y]];
    d = GCD[Abs[x - y], n];
If[d == n, , d]]

In[88]:= pollardrho[2896753]

Out[88]= 1229 Null

In[89]:= pollardrho[17]

Out[89]= Null^2

A: Although achieving the desired output requires only minor modifications to the Module,
I provide it here in a modestly more compact form:
pollardrho[n_] := Module[{x = 2, y = 2, d = 1}, g[x_] := Mod[x^2 + 1, n];
  While[d == 1, x = g[x]; y = g[g[y]]; d = GCD[Abs[x - y], n]];
  If[d == n, "Null", d]]

pollardrho[2896753]
(* 1229 *)

pollardrho[17]
(* Null *)


text:
Q: How to import .txt file into python I have a text file with many values like
2.81,5.62
7.14,8.00
2.72,5.44
3.87,7.74
1.90,3.80
7.82,8.00
7.02,8.00
5.50,8.00
9.15,8.00
4.87,8.00
8.08,8.00
5.58,8.00
9.13,8.00

Now I need to read these values as I want to put the first value into an array array1 and then the second value in an array array2.

A: You can use readlines() to read all the lines, and then split each line by the , character:
f = open('numbers.txt', 'r')
list1, list2 = zip(*[x.split(',') for x in f.readlines()])

A: You just have to:

*

*open() file in read-only mode

*read() each line

*for each line in file

*split() each line at ,

*append() first part to array1 and second part to array2

*done

Code:
array1 = []
array2 = []

with open('filename.txt', 'r') as f:
    for line in f.readlines():
        l = line.strip().split(',')
        array1 = l[0]
        array2 = l[1]

A: You could use numpy:
my_data = np.loadtxt('poo.txt', delimiter=",", unpack=True)
list1, list2 = my_data[::] #unpack your array


text:
Q: HTML5 / JS - check that application is offline I'm testing HTML5 offline application. To do that, I'm stopping my local web server (IIS) and open application. It's loaded fine, but it failed as soon as it request server side API method.
I want to prevent that and instead of $.get('/api/method') read data from my local storage. But I can found any facility to understand my application is offline.
if (/* online */) {
  // fire ajax
} else {
  // ask localstorage
}

I tried to use navigation.onLine but it seems to be always true (at least I can see that in Chrome).
Do you have any suggestions?
EDIT: taking into account current answers. Application is clearly understand that it's offline, since it takes resources according to cache.manifest. It's ridiculous to me, that client need to do any kind of tricks and pings. I assume there should be a easy way to check current mode.

A: online state could be also checked doing an ajax HEAD request with a timeout and when timeout is reached (or the call returns an error status) you can assume you're working offline (no network capabitlities) and you have to use localstorage instead
In fact, for the sake of state consistency, localstorage should be used as a fallback not only when you're offline, but also when you're online and the specific ajax resource is not temporarily available (e.g. site overload). Of course you will need to make a continuos polling to that resource with regular (or incremental) timeout until it becomes available again.

A: One easy way to check is to add a fallback section in your manifest like this:
FALLBACK
/online.js /offline.js

Then in online.js you set a global variable to true, in offline.js you set it to false and you just request online.js by Ajax whenever you plan to do some networking and do whatever processing you need conditionally in the callback.  In the meantime, maintain all your app data client side.
An alternative approach is a blocking polyfill for navigator.onLine as suggested by Remy Sharp.

A: I was needing the same functionality and after much searching found this function:
http://louisremi.com/2011/04/22/navigator-online-alternative-serverreachable/
Here is the code from the article, just in case the link goes down:
function serverReachable() {
  // IE vs. standard XHR creation
  var x = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" ),
     s;
  x.open(
      // requesting the headers is faster, and just enough
      "HEAD",
      // append a random string to the current hostname,
      // to make sure we're not hitting the cache
      window.location.href.split("?")[0] + "?" + Math.random(),
      // make a synchronous request
      false
  );
  try {
      x.send();
      s = x.status;
      // Make sure the server is reachable
      return ( s >= 200 && s < 300 || s === 304 );
  }
  // catch network & other problems
  catch (e) {
     return false;
  }
}

Note that the code above includes a fix by Scott Jehl for working with localhost which is posted lower down in the comments. And here is a link to a jQuery version of the same function:
https://gist.github.com/scottjehl/947084
And the code from that link:
function serverReachable() {
    var s = $.ajax({
           type: "HEAD",
           url: window.location.href.split("?")[0] + "?" + Math.random(),
           async: false
       }).status;
    return s >= 200 && s < 300 || s === 304;
};

I have found this technique to be really effective. Because the request is only for header information it is reasonably fast and it works across all browsers. Great success! :)
I hope other find this as helpful as I did. :)

A: How about doing some error handling. Like a Try Catch loop.
 try {
    //Run some code here
    }
 catch(err) {
    //Handle errors here
    }

A: Is it an option to ask localstorage when ajax call fails with a specific error (operation timeout)?
Or since the page (at least partially) is generated with server script you can include a request timestamp (or unique id) on your page with server-side script and put it to localstorage. Then you can see if the page is loaded from cache by checking stored id against the rendered one.

A: The best option might be to use the error event of the jQuery $.get() function to query localStorage rather than your webserver. This has the benefit of falling back if your server becomes unreachable as well as if the users entire internet is unreachable.
$.get({
  success: //deal with postback from ajax call,
  error: //Whoops no access to server deal with it in a local way
})

A: Seems like now the navigator.onLine is working and could be used.


text:
Q: Grep cURL output When I run
curl https://example.com -o example.html 2>&1 | grep -P "\d.*\d"

I get this output (in red):
100  1270  100  1270    0     0    318      0  0:00:04  0:00:04 0:00:00   318

What I want is just to show the last line of cURL's progress bar as it updates (I actually only want certain columns to be shown, but showing the whole line is fine)

Wanted output (at time t = 1 sec):
user@comp:~/Desktop/$ curl https://example.com -o example.html 2>&1 | grep -P "\d.*\d"
25  1270  25  318    0     0    318      0  0:00:01  0:00:01 0:00:03   318

Wanted output (at time t = 2 sec):
user@comp:~/Desktop/$ curl https://example.com -o example.html 2>&1 | grep -P "\d.*\d"
50  1270  50  636    0     0    318      0  0:00:02  0:00:02 0:00:02   318

Wanted output (at time t = 3 sec):
user@comp:~/Desktop/$ curl https://example.com -o example.html 2>&1 | grep -P "\d.*\d"
75  1270  75  954    0     0    318      0  0:00:03  0:00:03 0:00:01   318

Wanted output (at time t = 4 sec):
user@comp:~/Desktop/$ curl https://example.com -o example.html 2>&1 | grep -P "\d.*\d"
100  1270  100 1270    0     0    317      0  0:00:04  0:00:04 0:00:00   0

I've tried using watch with cURL and grep, but it still doesn't work (no output)
watch --no-title --interval 1 "curl http://example.com -o test2.html" | grep -P '\d.*\d'

A: You cannot directly | grep the output of curl progress because of pipe buffering. Some great insights on this issue is available in this previous question: Turn off buffering in pipe
As for a solution, using stdbuf and tr:
curl https://example.com -o example.html 2>&1 | stdbuf -oL tr -s '\r' '\n' | while read i; do echo -en "\r$i  "; done

With:

*

*stdbuf -oL: stdout of tr will be line buffered for proper processing by the while loop

*tr -s '\r' '\n': replace carriage return with newline from curl output

*while read i; do echo -en "\r$i  "; done: simple bash solution for a progress line