text:
Q: Adding Facebook Application to a page through API I am trying to add my Facebook application through an api. I used http://www.facebook.com/add.php?api_key=xxx&pages=1&page=xxx
This adds the app as a tab in the page successfully and it works. However my doubts are
1) is it supposed to be a documented feature? For i couldn't find any formal documentation (or am i missing something?)
2) is this the only method or is there any other means? For, the above one requires an active login. Something through a graph api etc. through oauth_token to be used in an external application.
3) What else can i do with this other than adding? Like say making it as a landing tab, etc.
Thanks a lot.

A: Here is how to use the Graph API
https://graph.facebook.com/<page_id>/tabs?app_id=<your_app_id>&method=post&access_token=<previously_fetched_access_token_for_page_id>

First you need to request access with the scope including 'manage_pages' within the request. Then, you can get the user's pages using '/me/accounts?access_token='
Once you get the list of pages, each page should come with an access token to use with the tabs API call.
Here are some references -
http://forum.developers.facebook.net/viewtopic.php?pid=361995
https://developers.facebook.com/docs/reference/api/

A: Regarding #3, I believe with the latest upgrade FB will be eliminating the option of selecting a custom landing tab.


text:
Q: Showing my current position in sencha touch I am working on a small sencha progect. I am trying to add tow maps. the second map should show my position. at the second map i am trying to show my position with out -
useCurrentLocation: true,

This is my code. it doesn't show me my current position. the first map works well...
what do i do wrong?
Ext.define('WhatsUnderMe.view.Main', {
extend: 'Ext.tab.Panel',
xtype: 'main',
requires: [
'Ext.TitleBar',
'Ext.Video',
'Ext.Map',
'Ext.util.GeoLocation',
],
config: {
    tabBarPosition: 'bottom',
    items: [
    {
        xtype: 'map',
        useCurrentLocation: true,
        title: 'My Position',
        iconCls: 'home',
        mapOptions:{
            zoom: 16,
            mapTypeId: google.maps.MapTypeId.SATELLITE
        },
    },
    {
        xtype: 'map',
        title: 'Under Me',
        iconCls: 'star',
        mapOptions:{
            zoom: 15,
            center: new google.maps.LatLng(lat, lng),
            mapTypeId: google.maps.MapTypeId.SATELLITE
        },
    }
    ]
  },

});

var lat, lng;
var position;
var geoLocationOptions = { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };
navigator.geolocation.getCurrentPosition(geoLocationSuccess,geoLocationError,geoLocationOptions);

function geoLocationSuccess(position) {
    lat = position.coords.latitude;
    lng = position.coords.longitude;
}

function geoLocationError() {
 Ext.Msg.alert('Error','Error while getting location');
}

A: Something like this should work.  Just make sure to change yourMapInstance in the code to the variable for your google map.
Ext.device.Geolocation.getCurrentPosition({
    allowHighAccuracy: true,
    maximumAge: 0,
    success: function(position) {

        var lat = position.coords.latitude,
            lon = position.coords.longitude;

        var userLocation = new google.maps.LatLng(lat,lon);

        var userLocationMarker = new google.maps.Marker({
            position: userLocation,
            map: yourMapInstance,
            clickable: false
        });

        yourMapInstance.setCenter(userLocation);

    },
    failure: function() {

        Ext.Msg.alert('Argh','Can\'t Find You!');

    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handling external class dialog button in main activity I am trying to create a custom dialog where the button clicks could be handled by the main activity that instantiates it, something like how the AlertDialog.Builder assigns the listeners via its setPositiveButton() and setNegativeButton() methods.
This is what I've done:
// THE MAIN ACTIVITY

public class main_code extends AppCompatActivity {

  private commonModule comMod;

  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      comMod = new commonModule(this);
  }

  private void showDialog() {
    DialogInterface.OnClickListener dialogHandler =
      new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        // process "PROCEED" button
      }
    };

    commonModule.myDialog customDialog = comMod.new myDialog();
    customDialog.inputBox(this, "Submit Results",
      "Your results will be submitted.", dialogHandler);
  }
}

// THE COMMON MODULE CLASS

public class commonModule {

  public commonModule(Context context){
    this.context = context;
    this.activity = (Activity) context;
  }

  public class myDialog {

    public void showDialog(Activity activity, String title, String message,
                           DialogInterface.OnClickListener dialogHandler) {

      final Dialog panel = new Dialog(activity);
      panel.requestWindowFeature(Window.FEATURE_NO_TITLE);
      panel.setContentView(R.id.customLayout);
      panel.setCancelable(false);

      TextView panelTitle = (TextView) panel.findViewById(R.id.title);
      panelTitle.setTypeface(fontRes(PlayRegular));
      panelTitle.setText(title);

      TextView msgboxText = (TextView) panel.findViewById(R.id.content);
      msgboxText.setTypeface(fontRes(PlayRegular));
      msgboxText.setText(message);

      Button button1 = (Button) panel.findViewById(R.id.button1);
      button1.setTypeface(fontRes(PlayRegular));
      button1.setText("ABORT");
      button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          panel.dismiss();
        }
      });

      Button button2 = (Button) panel.findViewById(R.id.button2);
      button2.setTypeface(fontRes(PlayRegular));
      button2.setText("PROCEED");

      button2.setOnClickListener(dialogHandler);
      // error: View.OnClickListener cannot be applied to Dialog.OnClickListener

      panel.show();
    }
  }
}

I tried using View.OnClickListener() as well, but to no success.  I would like the dialog builder to be common and generic, and as such, the click listener should be unique for each dialog.
Any suggestion would be really appreciated.
TIA.

A: Change your dialogHandler to View.OnClickListener instead of DialogInterface.OnClickListener :
private void showDialog() {
    View.OnClickListener dialogHandler =
      new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        // process "PROCEED" button
      }
    };

    commonModule.myDialog customDialog = comMod.new myDialog();
    customDialog.inputBox(this, "Submit Results",
      "Your results will be submitted.", dialogHandler);
  }

and in the common module:
public void showDialog(Activity activity, String title, String message,
                           View.OnClickListener dialogHandler) {
   ...
   button2.setOnClickListener(dialogHandler);
   panel.show();
}


text:
Q: WebSEAL - WAS 7 - Session Invalidation Fails to Clear WAS Session Cache I have a web app deployed on WAS 7 behind TAM WebSEAL 6.1, uses TAI, LTPA2 single sign-on
User login and SSO is working perfectly.
At logout, HTTPSession.invalidate() is invoked and https://<webseal url>/pkmslogout  is called.
Problem is:
After logout, WebSEAL session seems to clear, but the WebSphere JSESSIONID cookies stays. Also the session cache on the WAS has the old user information when logged in with new user.
Does anyone know, If I'm doing correct logout implementation?
Is there any other configuration in SSO settings that protects this session cache to be deleted when session is invalidated?
Implementation of the log out code:
logOutURL in the code below is the WebSEAL pkmslogout link
public void logout(ActionEvent event ){
    String logOutURL = (String) event.getComponent().getAttributes().get(ATTRIBUTE_NAME_LOGOUT_URL);
    getSession().invalidate();
    try {
        FacesContext c = FacesContext.getCurrentInstance();
        if( c!= null )
        {
            c.getExternalContext().redirect(logOutURL);
        }
    } catch (IOException e) {
        log.error( "Exception while processing logout redirect.", e );
    }
}

Thank you.

A: Learnt form some other forum that "ibm_security_logout" from the WebSphere would help revoke the session.
Details: http://www-01.ibm.com/support/docview.wss?uid=swg21254556
I'm yet to try this, I'll keep the forum posted.

A: On WebSphere 8.5.5 (maybe in older versions, too) you can set custom property.
Security -> Global Security -> Custom properties
com.ibm.ws.security.web.logoutOnHTTPSessionExpire=true


text:
Q: Ideals in $C[0,1]$ which are not finitely generated (From Atiyah- Macdonald ) I'm trying to solve the following problem from Atiyah-Macdonald:

Is the ring of continuous function on $[0,1]$ Noetherian ?

Certainly not, here are two non terminating ascending chain of ideals:
$ 1.$ $\langle x^{1/2} \rangle \subset \langle x^{1/4} \rangle \subset \langle x^{1/8} \rangle \subset \langle x^{1/16} \rangle \subset \cdots$, which is clearly ascending and non terminating.
$2.$ Clearly, $I_{ab}=\{f\in R\mid f([a,b])=\{0\}\}$ is an ideal of $C[0,1]$ and for any subinterval $[a,b]$ of $[0,1]$. Notice that if $[c,d]\subseteq [a,b]$, then $I_{cd}\supseteq I_{ab}$. Also, if $[c,d]$ is properly inside $[a,b]$ then the associated ideals are properly contained too because given any closed set, lets say $A$ there always exists a continuous function which exactly vanishes on $A$, hence using this we get a ascending and non terminating chain of ideals of $C[0,1]$
So, my question is:

What are other "interesting" non terminating chains of ideals in $C[0,1]$ or in other words what are all ideals in $C[0,1]$ which are not finitely generated?

As $[0,1]$ is compact, it's well known that all the maximal ideals in $C[0,1]$ are of the following form, $M_a =\{ f\in C[0,1] \mid f(a)=0 \}$ for $a$ $\in$ $[0,1]$, which are not finitely generated. But I don't have any idea of non maximal ideals which are not finitely generated. Any ideas?

A: The vast majority of ideals in $C[0,1]$ are not finitely generated.  For instance, if you take a point $p$, and just "randomly" write down some infinite collection of functions which all vanish at $p$, the ideal generated by those functions will very rarely be finitely generated.  There is really no hope to classify all possible non-finitely generated ideals.
As a very small taste of the sheer vastness of the different ideals there are in $C[0,1]$, this answer of mine shows that for any point $p\in[0,1]$, there is a chain (in fact, many different chains) of prime ideals which is order-isomorphic to $\mathbb{R}$ and is contained in the ideal of all functions that vanish at $p$.
Some other examples of ideals that may be illuminating: for any closed set $A$ (not just intervals), there is an ideal of functions that vanish on $A$, and this ideal is only finitely generated if $A=[0,1]$ or $A=\emptyset$ (the proof is basically the same as what you did for intervals, except instead of larger intervals you use small neighborhoods of $A$).  The set of functions $f$ such that $f(x)/x^n$ approaches $0$ as $x\to 0$ for all $n\in\mathbb{N}$ is an ideal (which is not finitely generated, or even countably generated, though the proof is fairly complicated).  For any nonnegative function $f\in C[0,1]$ which vanishes somewhere and does not vanish identically, the ideal $(f,f^{1/2},f^{1/4},f^{1/8},\dots)$ is not finitely generated.


text:
Q: WHERE coulmn.name=null doesn't return rows when left join When I do this selcect:
SELECT tabuoj.id, tabuoj.tabuo, montritaj_tabuoj.id, montritaj_tabuoj.id_de_tabuo
    FROM tabuoj LEFT JOIN montritaj_tabuoj
    ON (tabuoj.id=montritaj_tabuoj.id_de_tabuo)

I get:
id | tabuo    | id   | id_de_tabuo |
 1 | dom      | 2    |     1       |
 2 | samochód | null |    null     |
 3 | okno     | 1    |     3       |

but if I add where in which I compare id_de_tabuo column to null I dont't get any result.
SELECT tabuoj.id, tabuoj.tabuo, montritaj_tabuoj.id, montritaj_tabuoj.id_de_tabuo
FROM tabuoj LEFT JOIN montritaj_tabuoj
ON (tabuoj.id=montritaj_tabuoj.id_de_tabuo)
WHERE montritaj_tabuoj.id_de_tabuo=null

If I compare for example 1 like this:
SELECT tabuoj.id, tabuoj.tabuo, montritaj_tabuoj.id, montritaj_tabuoj.id_de_tabuo
FROM tabuoj LEFT JOIN montritaj_tabuoj
ON (tabuoj.id=montritaj_tabuoj.id_de_tabuo)
WHERE montritaj_tabuoj.id_de_tabuo=1

I get correct:
id | tabuo    | id   | id_de_tabuo |
 1 | dom      | 2    |     1       |

But I need rows with null in id_de_tabuo column. What I do wrong?

A: Try with IS NULL instead of = null like this
SELECT tabuoj.id, tabuoj.tabuo, montritaj_tabuoj.id, montritaj_tabuoj.id_de_tabuo
FROM tabuoj LEFT JOIN montritaj_tabuoj
ON (tabuoj.id=montritaj_tabuoj.id_de_tabuo)
WHERE montritaj_tabuoj.id_de_tabuo is null

Reason: Actually
montritaj_tabuoj.id_de_tabuo is null checks that the value is null. whereas
montritaj_tabuoj.id_de_tabuo = null checks that the value is equal to NULL which is never true.
Even NULL is not equal to NULL. You can check using this.
if(null = null)
  print 'equal'
else
  print 'not equal'

it will print not equal. Now try this
if(null is null)
  print 'equal'
else
  print 'not equal'

it will print equal.

A: When you filter on a left joined table in the where clause, the join becomes an inner join.  To solve the problem, filter in the from clause, like this:
FROM tabuoj LEFT JOIN montritaj_tabuoj
ON (tabuoj.id=montritaj_tabuoj.id_de_tabuo)
and montritaj_tabuoj.id_de_tabuo is null

where clause starts here

A: Try just two simple select like
select * where id = null

and
select * where id != null

It's a common misconception about null.
Think null as the english word "whatever" in a opposition to "nothing" and you ill start to understand it better.
As sachim answered use
IS NULL
on your predicates.


text:
Q: Why IMultiValueConverter doesn't get updated ObservableCollection as a parameter? I have an ItemsControl that was set like this:
<ItemsControl ItemsSource="{Binding GameObjects}"
                          AlternationCount="{Binding GameObjects.Count}"
                          Grid.RowSpan="10"
                          Grid.ColumnSpan="10">

<DataTemplate>
    <Grid>
        <Grid.DataContext>
            <vm:MainWindowViewModel/>
        </Grid.DataContext>
        <TextBlock Text="{Binding Path=(ItemsControl.AlternationIndex),
                         RelativeSource={RelativeSource TemplatedParent}}"/>
        <Image>
            <Image.Source>
                <MultiBinding Converter="{StaticResource
                    ObservableCollectionItemByAlternationIndex}">
                    <Binding Path="Textures"/>
                    <Binding Path="GameObjects"/>
                    <Binding Path="(ItemsControl.AlternationIndex)"
                        RelativeSource="{RelativeSource TemplatedParent}"/>
                </MultiBinding>
            </Image.Source>
        </Image>
    </Grid>
</DataTemplate>

The converter looks like this:
public override object Convert(object[] v, Type t, object p, CultureInfo c)
    {
        var value1 = (ObservableCollection<string>)v[0];
        var value2 = (ObservableCollection<GameObject>)v[1];
        var value3 = (int)v[2];

        foreach(var tex in value1)
        {
            if ("/Maelstrom;component//Data/Resources/Textures/" + value2[value3].GetType().Name + ".png" == tex)
            {
                return new BitmapImage(new Uri("pack://application:,,," + tex));
            }
        }

        return new BitmapImage(new Uri("pack://application:,,," + value1[0]));
    }

The issue here is that when I update GameObjects, converter doesn't gets updated version of GameObjects, instead of it, value1 will contain all elements that were inside GameObjects when program started. ItemsControl updates normally (items that were removed from GameObjects also were removed from the UI).

A: The problem is that you are are confusing INotifyPropertyChanged with INotifyCollectionChanged.
A multi-binding is only updated if one of the properties in one of the bindings issues an INotifyPropertyChanged.PropertyChanged event.  In other words, if the entire collection underlying Textures or GameObjects was completely replaced with a brand new instance of ObservableCollection
But that's not what happens when you add/remove items to/from an ObservableCollection.  In that case, the property that returns that collection object does not change at all;  The very same ObservableCollection object remains.  But the collection itself raises the INotifyCollectionChanged.CollectionChanged event.
The only way that WPF can react to this is if some object is monitoring that specific ObservableCollection object for INotifyCollectionChanged.  And that cannot possibly happen when you use it in a MultiBinding because the ObservableCollection gets lost in the conversion.  The MultiBinding returns one single value and whatever that value is, it's not any object that implements INotifyCollectionChanged.
You might want instead to look into the CompositeCollection class.  That might be a better approach


text:
Q: How to filter rows of a pandas df using the columns value as the key to a dictionary based on its returned value I have a dataframe which I need to filter rows out when the value returned by a dictionary using the value of the specific column is used as a dictionary key to return the keys value.
I have been able to filter the rows based on the columns value but when i try to use the columns value in a dictionary in a similar fashion iit returns an error.
TypeError: 'Series' objects are mutable, thus they cannot be hashed

indexNames = df[ accounting_type_dict[df['fund_id']] == 'ETFs' ].index
df.drop(indexNames , inplace=True)

A: Using map then filter
newdf=df[df['fund_id'].map(accounting_type_dict) == 'ETFs'].copy()

A: You could try replacing the column with the corresponding values from the dict. (You may need to use map instead of replace depending on how large the DataFrame is.)
indexNames = df[ df['fund_id'].replace(accounting_type_dict) == 'ETFs' ].index
df.drop(indexNames , inplace=True)


text:
Q: "'this' is a reserved keyword" in React app, why? import React, { Component } from "react";
import Item from "./components/Item";
import items from "./items.json";
import "./App.css";

class App extends Component {

  state = {
    items
  };

  render() {
    return (
          {this.state.items.map(item => (
          <Item
            id={item.id}
            key={item.id}
            name={item.name}
            image={item.image}

          />
      ))}
    );
  }
}

export default App;

When I run this code I get the following error: App.js: this is a reserved word (17:11).  What can I do to fix this?


text:
Q: AOP Separating Cross-cutting Concerns I'm trying to start taking advantage of Aspect-Oriented programming for repetitive tasks.  I'm not sure how to go about separating concerns.  I'm using C# and for AOP I'm using Castle.DynamicProxy (using Autofac's InterceptedBy feature), but I'm hoping an answer to this question can be general enough advice to apply to other AOP solutions as well (maybe you can convince me to switch to a different AOP solution).
For example, I have something like the following interceptor that intercepts all method calls to a class.  It currently has two concerns: when a method is called, (1) measure how long the call took, and (2) log the name of the method before and after it is called.
public class TimeLoggingInterceptor : IInterceptor
{
    private ILog m_Log;
    public TimeLoggingInterceptor(ILog log)
    {
        m_Log = log;
    }
    public void Intercept(IInvocation invocation)
    {
        // Logging concerns
        string fullMethodName = invocation.TargetType.Name + "." + invocation.MethodInvocationTarget.Name;
        m_Log.Debug(fullMethodName + " started.");

        // Timing concerns
        DateTime beforeStamp = DateTime.UtcNow;

        // Call method
        invocation.Proceed();

        // Timing concerns
        DateTime afterStamp = DateTime.UtcNow;
        TimeSpan callTime = afterStamp - beforeStamp;

        // Logging concerns
        m_Log.Debug(fullMethodName + " finished. Took " + callTime.TotalMilliseconds + "ms.");
    }
}

I have an overwhelming feeling that the timing concerns here (measuring how long the method call took) should be separated from the logging concerns (writing to the log file) because...well, they're separate concerns.  I'm thinking of doing something like this, but I'm not sure how to approach ordering or where to put the callTime variable:
public class TimingInterceptor : IInterceptor
{
    private static ThreadLocal<TimeSpan> callTime = new ThreadLocal<TimeSpan>();
    public static TimeSpan CallTime
    {
        get
        {
            if (!callTime.IsValueCreated) throw new InvalidOperationException("callTime was never set");
            return callTime.Value;
        }
    }

    public void Intercept(IInvocation invocation)
    {
        // Timing concerns
        DateTime beforeStamp = DateTime.UtcNow;

        // Call method
        invocation.Proceed();

        // Timing concerns
        DateTime afterStamp = DateTime.UtcNow;
        callTime.Value = afterStamp - beforeStamp;
    }
}
public class LoggingInterceptor : IInterceptor
{
    private ILog m_Log;
    public LoggingInterceptor(ILog log)
    {
        m_Log = log;
    }

    public void Intercept(IInvocation invocation)
    {
        // Logging concerns
        string fullMethodName = invocation.TargetType.Name + "." + invocation.MethodInvocationTarget.Name;
        m_Log.Debug(fullMethodName + " started.");

        // Call method
        invocation.Proceed();

        // Logging concerns
        m_Log.Debug(fullMethodName + " finished. Took " + TimingInterceptor.CallTime.TotalMilliseconds + "ms.");
    }
}

Basically what I'm thinking needs to happen here is that, somehow, TimingInterceptor needs to directly intercept the methods, and then LoggingInterceptor needs to wrap around that.
What approaches do people use to make sure these concerns will happen in the correct order?  Do I chain the interceptors, having LoggingInterceptor intercept TimingInterceptor's Intercept method? Or do I put some kind of [InterceptOrder(1|2|3|...)] attribute on the interceptor classes? Or can I put something like [InterceptAfter(typeof(TimingInterceptor))] on LoggingInterceptor?
And is there a better alternative to using a thread-local variable to keep track of the call time? Yes, I'd like this to be thread safe. I'm thinking keeping this variable on the stack might be preferred, but I'm not sure how LoggingInterceptor could get a handle to TimingInterceptor without introducing too much coupling (would be nice to be able to switch out the TimingInterceptor implementation without recompiling LoggingInterceptor).

A: Have you tried just adding both Interceptors to your proxy and running your code? My understanding is that if a proxy has multiple Interceptors, calling Proceed() in the first interceptor in the chain will actually call the next interceptor, rather than actually performing the invocation.

A: It is good to try separate concerns in your applications. But concerns cannot have a dependency to another.
It may stay confusions about terminology used in IOC/AOP and global coupling domain.
Indeed, concerns in AOP paradigm means an independant code/treatment.
In your case, I can identify "logging concern/aspect" and dependency beetween time measurment/calculator (Start+Stop) and logger.
Your AOP framework should inject only a Logging Aspect/Advice that can depend on logger + time calculator (like a business/domain/functional Stopwath) to work. Ideally, logger and time calculator are behind interfaces and logging aspect should use an IOC container to instantiate logging advice with injected (please by constructor) logger and time calculator.
In this way, logging advice, logging aspect, logger module and time calculator module can be unit test and develop by different team in different projects.
Using a threadlocal/threadstatic or callcontext is often a bad idea and can reflect a design issue.
not : if you use threadstatic/threadlocal, take care about memoryleak/long retention object, threadpool management, asynchronous call (Task), bug hard to detect due to coherent and random style results.


text:
Q: Segmentation fault : 11, with pointers a problem that I am not able to resolve...
I have a segmentation fault when I call the new_col() function.
Structs are OK, function not.
typedef struct {
    int jour;
    int mois;
    int annee;
} date;

typedef struct {
    date** tab;
    int size;
} col_dates;

// Fonction B1.c
col_dates* new_col(int size) {

   int i;
   col_dates* cd;

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

       cd->tab[i] = NULL;

   }

   cd->size = i;

   return cd;

}

Thanks! :)

A: col_dates *cd; is a pointer which doesn't point to anything. It doesn't have any memory to point to and thus, no data to point to. So you can't just do cd->data;, because data is not there (you're trying to access nothing and getting a segfault).
You have to allocate memory first:
col_dates *cd = malloc(sizeof(col_dates));

// access cd and return it

After you allocate cd, allocate cd->tab as well:
cd->tab = malloc(size * sizeof(date *));

Don't forget to free the pointer returned after you don't need it anymore.


text:
Q: Changing the JSESSIONID cookie name to something else with Spring Boot Security I would like to change the name of the JSESSIONID cookie to something else to make it more difficult for potential attackers to guess what technology my application is using.
Is this possible in Spring Boot with Spring Security? I've been able to find solutions for Spring Boot with Spring Session but none that would work without the Session extension (which I'm not using).

A: You can configure it in your web.xml like so:
<session-config>
    <cookie-config>
        <name>cookie name</name>
    </cookie-config>
</session-config>

A: You can change cookie name in your application.yml
Like this :
server:
  servlet:
    session:
      cookie:
        name: TEST_JSESSIONID

or
@Bean
public CookieSerializer cookieSerializer() {
    DefaultCookieSerializer serializer = new DefaultCookieSerializer();
    serializer.setCookieName("TEST_JSESSIONID");
    serializer.setCookiePath("/");
    serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
    return serializer;
}

https://docs.spring.io/spring-session/docs/current/reference/html5/guides/java-custom-cookie.html


text:
Q: Make button stay fixed when swiping a viewPager Basically, I want a button that appears on a certain page on my viewPager to stay on position on swipe (for design purposes). I have read the closely similar question here but I didn't understand how the OP implemented it. My button and viewPager are defined separately on my layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

     <Button
         android:id="@+id/button_register"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_above="@+id/indicator"
         android:layout_centerHorizontal="true"
         android:layout_marginBottom="96dp"
         android:text="Register"
         android:visibility="gone"/>

</RelativeLayout>

I detect page swipes with OnPageChangeListener. Here is a graphic example of what I want to implement:

Thank you!
EDIT
Here is the file imageview.xml, which is defined for each page in the viewPager. I included the button here as advised by @attels (it was previously defined in the main activity layout), but now my app crashes.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >

<ImageView
    android:id="@+id/ivImageView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:contentDescription="@string/welcome1"
    android:scaleType="fitXY"/>

<include layout="@layout/imageview_page"/>

<Button
     android:id="@+id/button_register"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_above="@+id/indicator"
     android:layout_centerHorizontal="true"
     android:layout_marginBottom="96dp"
     android:text="Register"
     android:visibility="gone"/>

</RelativeLayout>

FINAL EDIT
So in order for any Button or Text or whatever that you want to keep fixed in a viewPager's page, you need to define said element in the page's layout (NOT in the main activity's layout) and also instantiate the button inside the fragment. Thanks!

A: From documentation - http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html
This method in FragmentPagerAdapter shows each screen.
 @Override
        public Fragment getItem(int position) {
            return ArrayListFragment.newInstance(position);
        }

So that means that you need to add the button in ArrayListFragments layout here:
@Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
            // Here is the layout that the fragment is going to show.
            //some code
            return v;
        }

And here is the fragment_pager_list layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="146dp"
        android:text="Button" />

</RelativeLayout>

So now the button is going to follow the screen.


text:
Q: Activiti Process Updated Variable value is not getting persisted in DB I'm trying to update a Process Variable after starting a Process
When starting that activiti, I pass a random string value for the variable but I need to update the variable value afterwards.
System.out.println(runtimeService.getVariables(executionId));
runtimeService.setVariable(executionId, varName, varValue);
System.out.println(runtimeService.getVariables(executionId));

and output is
variableOne : "randomValue"
 variableOne : "UpdatedValue"
But when I get documentation of the task whose documentation is
the variable value is ${variableOne}
I get output as
the variable value is randomValue
instead of
the variable value is UpdatedValue

A: The problem is that the execution id is not always the same as the process instance id.
You need to update the variable against the process instance id rather than the execution id.
CHeers,
Greg


text:
Q: Mavericks Login Screen Mirrored on 2nd Monitor I recently had to erase and restore my mac as it developed a terrible hard drive failure, and ever since I've had odd behaviour (already posted one other question today). For some reason the Login screen is mirrored on both my monitors and annoyingly this changes the resolution and aspect ratio shown on the MacBook, I really don't like it, and it's never done this before. It also creates a strange animation as the screen logs in which I fins even more annoying. Before the second monitor would show the background of the login screen but certainly would not effect the resolution of the main screen or be mirrored. What's going on there?
Thanks,
Mike
Two screenshots, one of the displays and a profile error which I can't help but feel is also a side effect of the issue I had.

A: Pressing ⌘+F1 is the shortcut for switching between mirrored (same thing on both displays) and extended desktop (each display is independent) modes.
Pressing that while at the login screen should sort your problem.


text:
Q: How to work smart on Stack Overflow I have to admit that I work rather "primitively" most of the time, but I realize now that in order to increase my productivity I have to work smarter. Thus, I'm looking for guidance from the top users of Stack Overflow: how do you work efficiently? How do you work smart?
Automation

*

*How can I auto-link to, say, Java API? What do I need to do so that if I type java.util.Set, String.split, etc., it automatically generates the links?

*How can I auto-insert, say, canned footers? Many regular expressions questions, for example, can benefit from a references section to, say, regular-expressions.info. What do I need to do so that I can enable some sort of macro replacement or whatever, e.g., type "re-info", "bloch-cloneisbroken", etc. and have that be automatically replaced with predetermined texts?

*What do I need to do so that I can pretty much drag and drop links into my question, instead of typing it as text?

Searching into your own body of work

*

*Sometimes you want to pull parts of your own answers from the past, but this can be hard to find, e.g. if you forgot the question title, etc. How can I "Google" my own archive of answers?

An external editor?
I'd imagine the most effective way may involve an external editor that enables all these things, and then either copy/pasting it to Stack Overflow, or have it post to Stack Overflow through some sort of plug-in? I've heard some awesome stuff about TextMate, so perhaps this is what I need?
Then maybe I can somehow "import" all my past answers and build my own local searchable index or something? Then use Google Desktop or something?

A: Well, as for "Searching into your own body of work" see https://meta.stackoverflow.com/search specifically the user:me operator.
I also highly recommend installing and using a clipboard stack buffer tool, as documented here:
http://www.codinghorror.com/blog/2008/01/reinventing-the-clipboard.html


text:
Q: Don't know which OpenId I used I'm trying to log into SO after a hiatus of a few months. Unfortunately, I've no idea which OpenID I used to sign myself up.
I've got various email accounts with associated OpenIDs, plus one I run on my personal domain; but I've tried all the ones I can think of, and none of them seem to be the right one.
Is there some way I can retrieve my account, or find out which openid is associated with it?

A: I have found your account; I will e-mail details to the e-mail address listed (done).

A: Send an email to team@stackoverflow.com with whatever information you can remember. Like what username you had here etc.


text:
Q: TraceListener call does not block, leads to crash when calling twice My setup: simple implementation of TraceListener that is instantiated once and keeps one instance of a "MessageBox" implementation.
It's purpose is to listen for binding errors, as it is added to PresentationTraceSources.DataBindingSource.Listeners
My test case opens a window that has exactly two binding errors, so what I expect is, the tracer kicks in and shows the "MessageBox" window via ShowDialog(). The user clicks ok, the window is NOT closed, but hidden and the second binding error should came up.
Instead I get a crash:

An unhandled exception of type 'System.InvalidOperationException'
  occurred in PresentationFramework.dll

"ShowDialog" can only be called on hidden windows

Why the heck does this happen? Here is the exact implementation of the trace listener:
public class DummyListener : TraceListener
{
    private readonly MessageBoxView _window = new MessageBoxView();

    public DummyListener()
    {
        _window.HideOnClose = true;
        _window.DataContext = _window;
    }

    public override void Write( string message )
    {
    }

    public override void WriteLine( string message )
    {
        lock ( _window )
        {
            if ( _window.IsActive )
            {
                // !!! WHY IS THIS CODE EXECUTED
                System.Diagnostics.Debugger.Break();
            }
            _window.Message = message;
            _window.ShowDialog();

            throw new NotImplementedException("This line is never reached");
        }
    }

}

I've added a lock just for testing. The _window.ShowDialog is called twice, for each binding error and then crashes. The NotImplementedException is also a test, it never gets called. So first binding error calls _window.ShowDialog(), this seems to block but the trace listener source calls WriteLine a second time, on the same thread, it ignores the lock and enters my Break() call, if I continue, it calls _window.ShowDialog() before the first dialog got hidden.
If I replace _window.ShowDialog with a MessageBox.Show, it does really block.
Why does ShowDialog() behaves this way? It does block, as the NIE exception after it is not thrown but why does the System.Diagnostics.TraceListener.TraceEvent re-enter the locked section?
For clarification: I want to pool the window, I do not want to spawn multiple message box window but show them in order.
I've checked the threads, everything happens on the main thread, but nothing blocks the way I would expect.
Here is a Minimal, Complete, and Verifiable example (sorry it is quite verbose as I could not reduce it more):
It opens a window directly, it throws the above exception because of _window.ShowDialog();
App.xaml (remove the startup uri)
<Application x:Class="WpfApplicationTracerIssue2.App"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             >
    <Application.Resources>

    </Application.Resources>
</Application>

App.xaml.cs
using System;
using System.Diagnostics;
using System.Windows;

namespace WpfApplicationTracerIssue2
{
    public class DummyListener : TraceListener
    {
        private readonly MessageBoxView _window = new MessageBoxView();

        public DummyListener()
        {
            _window.HideOnClose = true;
            _window.DataContext = _window;
        }

        public override void Write( string message )
        {
        }

        public override void WriteLine( string message )
        {
            lock ( _window )
            {
                if ( _window.IsActive )
                {
                    // !!! WHY IS THIS CODE EXECUTED
                    System.Diagnostics.Debugger.Break();
                }
                _window.Title = "Log entry occurred";
                _window.Message = message;
                _window.ShowDialog();

                throw new NotImplementedException("This line is never reached");
            }
        }

    }

    public partial class App : Application
    {
        private DummyListener dl = new DummyListener();

        protected override void OnStartup( StartupEventArgs e )
        {
            base.OnStartup( e );
            Current.ShutdownMode = ShutdownMode.OnMainWindowClose;

            PresentationTraceSources.DataBindingSource.Listeners.Add( dl );

            var d = new MainWindow();

            d.DataContext = d;
            MainWindow = d;
            d.Show();
        }
    }
}

MainWindow.xaml (cs is default)
<Window x:Class="WpfApplicationTracerIssue2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>

    </StackPanel>
</Window>

Finally the dummy messagebox view:
MessageBoxView.xaml
<Window x:Class="WpfApplicationTracerIssue2.MessageBoxView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MessageBoxView" Height="300" Width="300">
    <StackPanel>

        <Button Click="ButtonBase_OnClick">Ok</Button>
    </StackPanel>
</Window>

MessageBoxView.xaml.cs
using System.Windows;

namespace WpfApplicationTracerIssue2
{

    public partial class MessageBoxView : Window
    {
        public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof ( string ), typeof ( MessageBoxView ), new PropertyMetadata( default( string ) ) );

        public string Message{ get { return ( string ) GetValue( MessageProperty ); } set { SetValue( MessageProperty, value ); }}

        public MessageBoxView(){InitializeComponent();}

        public bool HideOnClose { get; set; }

        private void ButtonBase_OnClick( object sender, RoutedEventArgs e )
        {
            if ( HideOnClose ){ Hide(); }
            else{ Close(); }
        }
    }
}

A: First, this doesn't appear to have anything to do with multithreading. It's really about re-entrancy in a single thread.
The issue is that the ShowDialog() method necessarily includes a message pump for the thread messages. The thread message queue is used by the listener framework to deliver events to the listener. So while you are displaying the window for the first message, that message pump in the ShowDialog() method goes ahead and delivers the second message, before the window for the first message has been dismissed.
One way to fix this would be to change the listener code so that it queued the messages itself, and displayed them on at a time. That might look something like this:
public class DummyListener : TraceListener
{
    private readonly MessageBoxView _window = new MessageBoxView();
    private readonly BlockingCollection<string> _messages = new BlockingCollection<string>();

    public DummyListener()
    {
        _window.HideOnClose = true;
        _window.DataContext = _window;

        PresentMessages();
    }

    private async void PresentMessages()
    {
        IEnumerator<string> enumerator = _messages.GetConsumingEnumerable().GetEnumerator();

        while (await Task.Factory.StartNew(() => enumerator.MoveNext(), TaskCreationOptions.LongRunning))
        {
            _window.Title = "Log entry occurred";
            _window.Message = enumerator.Current;
            _window.ShowDialog();
        }
    }

    public override void Write(string message)
    {
    }

    public override void WriteLine(string message)
    {
        _messages.Add(message);
    }

    protected override void Dispose(bool disposing)
    {
        _messages.CompleteAdding();
        base.Dispose(disposing);
    }
}

The above uses a BlockingCollection<string> to queue up each message as it comes in. Also, in the constructor it calls an async method that handles the actual presentation of the window.
That PresentMessages() method uses an asynchronous task to wait for a message to be available to present. When that task completes, the method is resumed in the original thread to present the window.
NOTE: for the above to work, you need to ensure that the listener class instance itself is created in the UI thread, so that the continuation in the PresentMessages() method is in fact executed in the UI thread too. To ensure that, I changed your App code so it looks like this instead:
public partial class App : Application
{
    private DummyListener dl;

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        Current.ShutdownMode = ShutdownMode.OnMainWindowClose;

        dl = new DummyListener();
        PresentationTraceSources.DataBindingSource.Listeners.Add(dl);

        var d = new MainWindow();

        d.DataContext = d;
        MainWindow = d;
        d.Show();
    }
}

Also note that I use Task.Factory.StartNew() to create the task, rather than the more concise Task.Run(). This allows me to pass TaskCreationOptions.LongRunning, so that the Task class knows this operation could take a long time. That way it can avoid tying up a thread pool thread on a blocking operation that could potentially take a long time to complete.
An even better approach would be to implement an asynchronously-completing MoveNext() method (i.e. an asynchronous version of IEnumerable<T>). I leave that as an exercise for the reader. :)


text:
Q: pushing a pandas df together idx = pd.date_range('2000-01-11', periods=6)
df = pd.DataFrame({'A':['XLE','XLE',5,'XLE','XLE','XLE'],
                   'B':[5,5,'XLI','XLI','XLI','XLI'],
                   'C':['XLV','XLV','XLV','XLV',5,'XLV'],
                  'D':['XLY','XLY','XLY',5,'XLV',5]}, index=idx)

print (df)

              A    B    C    D
2000-01-11  XLE    5  XLV  XLY
2000-01-12  XLE    5  XLV  XLY
2000-01-13    5  XLI  XLV  XLY
2000-01-14  XLE  XLI  XLV    5
2000-01-15  XLE  XLI    5  XLV
2000-01-16  XLE  XLI  XLV    5

I have data in a pandas df, how can I create a new 4 column dataframe without any of the 5's?  Basically push the dataframe in for lack of better words.

A: You can use apply with boolean indexing:
df = df.apply(lambda x: pd.Series(x[x != 5].values, index=['col1', 'col2', 'col3']), axis=1)
print (df)
           col1 col2 col3
2000-01-11  XLE  XLV  XLY
2000-01-12  XLE  XLV  XLY
2000-01-13  XLI  XLV  XLY
2000-01-14  XLE  XLI  XLV
2000-01-15  XLE  XLI  XLV
2000-01-16  XLE  XLI  XLV

Another solution with numpy.sort and selecting by iloc:
df = pd.DataFrame(np.sort(df[df != 5].astype(str), axis=1),
                  index=df.index,
                  columns = list('abcd')).iloc[:, :3]
print (df)
              a    b    c
2000-01-11  XLE  XLV  XLY
2000-01-12  XLE  XLV  XLY
2000-01-13  XLI  XLV  XLY
2000-01-14  XLE  XLI  XLV
2000-01-15  XLE  XLI  XLV
2000-01-16  XLE  XLI  XLV


text:
Q: Decrypt android AES example on iOS i have an Android example of AES encryption/decription.
https://github.com/itog/CryptoSample/blob/master/src/com/pigmal/android/ex/crypto/Crypto.java#L35
I want to decrypt this on iOS. It looks allmost impossible. I've found this to make it more easy, but failed:
https://github.com/Gurpartap/AESCrypt-ObjC
I even don't get a good response back from the base64 decoding. Here's my code:
NSData *encryptedData = [NSData base64DataFromString:encrypted];
// returns null
NSData *decryptedData = [encryptedData decryptedAES128DataUsingKey:[[CRYPT_SEED dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash] error:&error];
NSString* result = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];

A: First of all AES is symmetric cipher algorithm which needs to use exactly the same key for message encryption and also for message decryption.
I have examined your example codes and these are the things that really bother me:

*

*different keys: Android example does not provide any getter or setter for AES key that should be used. Without that you are unable to use the same AES key on Android and iOS.

*different key sizes: Android example seems to be using AES-128 but iOS example seems to be using AES-256

*different cipher modes: iOS example uses CBC cipher mode so you will need to exchange also IV (initialization vector) between your devices. However I don't see any interface to provide/acquire IV in Android example.

I believe these are the main reasons why you are unable to get it working. If you want to use AES then you will need to modify your code to use the same key on both devices, use the same cipher mode on both devices and also use the same padding on both devices.

A: Tips:

*

*You could use a third-party library to do this. Depending on the library, it may be cross-platform so same calls on different platforms will return back same results.

Secure Black Box:
https://www.eldos.com/sbb/platforms.php#product
Crypto++
http://www.cryptopp.com

*

*You could compile the test AES routine to ensure both AES encrypt and decrypt routine on Android and iOS give the same results.

*You could check the Base64 if it is encoding and decoding correctly. Sometimes it could be Unicode (UTF16) iOS and non-Unicode (UTF8) Android problem. That happened to me when I was doing this.

A: Well this might be because the public keys are different.
There are two things those are stored encrypted. First one is, username/password and second one is the message itself. When you enter your password correctly, the message is decrypted using your pasword and the public key.
The reason we call it as public key is, for the same crypting methods, the keys are the same.
Therefore, what I think is, maybe you should look for a procedure that sets the public key to a string of your choice.
Or you may use a simpler method, such as fairplay.

A: What the other answers have noted is true, it could down to different is key size/mode/padding. There can also be issues with the type of BASE64 encoding. On Android there's a couple of different flags that can produce subtly different outputs. I found Base64.NO_WRAPto work.
I also had the similar issue with AESCrypt-ObjC by default it uses a blank IV and on Android/Java it seems if you don't specify one a random one is generated.
Here's how I specified a blank IV so that iOS could decrypt:
private static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

cipherText = cipher.doFinal(stuffIWantSafe.getBytes("UTF-8"));

String encodedCipherText = Base64.encodeToString(cipherText, Base64.NO_WRAP);

Disclaimer: I'm not recommending a blank IV from security point of view for better to have a IV that changes with each message
*Update: Just released Android version of AESCrypt


text:
Q: Vue JS - injecting default value to custom radio group So i tried to inject a default value to custom radio component that i wrote
Here's the code:
<template>

  {{value}}

    <input type="radio" :value="item.value" name=item.name @click=onSelected(item.value) >
    {{item.label}}
    </input>

And here's how i called it:
<CustomRadioButton :value=RadioFieldData  @clicked="isRadioButtonSelection" isDefault='yellow'></CustomRadioButton>

And here's the Json Data that goes with it
RadioFieldData:[
  {label:'Fire', value:'red', name:'colour' },
  {label:'Sun', value:'yellow', name:'colour',isDefault:'yellow'},
  {label:'Water', value:'blue', name:'colour'}
]

My question is what is the best way to pass the value "yellow" to the radio buttons group?

A: Your issue is that props need to be represented in their kebab-case format when used in your template. To set isDefault to "yellow", you need to use
is-default="yellow"

See https://v2.vuejs.org/v2/guide/components.html#camelCase-vs-kebab-case
Once you're able to read that property correctly, you can use
:checked="item.value == isDefault"

Here's an example.

Vue.component('custom-radio-button', {
  template: `

  Default: {{isDefault}}

    <input type="radio" :value="item.value" name="item.name" @click="onSelected(item.value)" :checked="item.value == isDefault" />
    {{item.label}}

`,
  props: ['value', 'isDefault'],
  methods: {
    onSelected(value) {
      this.$emit('clicked', value)
    }
  }
})

new Vue({
  el: '#app',
  methods: {
    isRadioButtonSelection (val) {
      console.log('isRadioButtonSelection', val)
    }
  },
  data: {
    RadioFieldData: [{"label":"Fire","value":"red","name":"colour"},{"label":"Sun","value":"yellow","name":"colour","isDefault":"yellow"},{"label":"Water","value":"blue","name":"colour"}]
  }
})

  <custom-radio-button :value="RadioFieldData"
                       @clicked="isRadioButtonSelection"
                       is-default="yellow">
  </custom-radio-button>


text:
Q: Javascript Date object issue in safari browser I have a JavaScript code which is breaking in safari browser only. Here is the code..
var dateString = seldateCom.getFullYear()+"-"+month+"-"+seldateCom.getDate()+" "+$(this).val();
console.log("dateString = "+ dateString);
var date = new Date(Date.parse(dateString, "yyyy-MM-dd HH:mm:ss"));
console.log(date);

this is showing below error in safari browser console
while in Chrome it is working perfectly, here is a screenshot of Chrome browser.
What adjustment need to be done in order to work in both browsers?

A: Using Date.parse will not work in safari. To get around with this you can change the code to avoid the use of it:

var dateString = "2019-3-6 05:30 pm";
var splitDate = dateString.split(/[^0-9]/);
var date = new Date(
splitDate[0],
splitDate[1]-1,
splitDate[2],
splitDate[3],
splitDate[4]
);
console.log('dateString', dateString);
console.log('date', date);


text:
Q: Entity Framework Core : insert error (Serialization and deserialization of 'System.Action' instances are not supported. Path: $.MoveNextAction.) I am trying to preform a insert action using Entity Framework Core 6.0.11 with identity framework as the base, with Postgres as the database.
I am getting the following error when trying to preform an insert operation:

Serialization and deserialization of 'System.Action' instances are not supported. Path: $.MoveNextAction

This is the code of my insert:
public async Task<CampaignDetialDto> CreateCampaign(BaseCampaignDto campaignDto)
{
    var userCampaign = new UserCampaign
    {
        UserId = UserId,
        Campaign = _mapper.Map<Campaign>(campaignDto),
        CampaignRole = CampaignRoleEnum.Player
    };

    await _userCampaignRepo.AddAsync(userCampaign);
    return _mapper.Map<CampaignDetialDto>(userCampaign.Campaign);
}

The userCampaignRepo:
public class UserCampaignRepository : GenericRepository<UserCampaign>, IUserCampaignRepository
{
    private readonly PostGresContext _context;
    private readonly IMapper _mapper;

    public UserCampaignRepository(PostGresContext context, IMapper mapper) : base(context, mapper)
    {
        _context = context;
        _mapper = mapper;
    }
}

The base repo preforming the action:
public async Task<T> AddAsync(T entity)
{
    await _context.AddAsync(entity);
    await _context.SaveChangesAsync();
    return entity;
}

The context and models:
public class PostGresContext : IdentityDbContext<User>
{
    public PostGresContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<Campaign> Campaigns { get; set; }
    public DbSet<UserCampaign> UserCampaigns { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfiguration(new RoleConfiguration());

        modelBuilder.Entity<UserCampaign>().HasKey(x => new
        {
            x.UserId,
            x.CampaignId
        });
    }
}

public class UserCampaign
{
    [Key, Column(Order = 0)]
    public string UserId { get; set; }
    public virtual User User { get; set; }

    [Key, Column(Order = 1)]
    public int CampaignId { get; set; }
    public virtual Campaign Campaign { get; set; }

    public CampaignRoleEnum CampaignRole { get; set; } = CampaignRoleEnum.Player;
}

public class Campaign
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public DateTime CreateDate { get; set; } = DateTime.UtcNow;
    public ActiveStateEnum Active { get; set; } = ActiveStateEnum.Active;

    public virtual ICollection<UserCampaign> UserCampaigns { get; set; }
}

public class User : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<UserCampaign> UserCampaigns { get; set; }
}

public static IServiceCollection AddApplicationPostGresContext(this IServiceCollection services, IConfiguration _config)
{
    services.AddDbContext<PostGresContext>(options =>
    {
        options.UseNpgsql(_config.GetConnectionString("PostGresConnectionString"));
    });

    return services;
}

I tried altering the add methods hoping it might bring a change but with no effect, I also tried to call the context directly by using _context.addAsync(XXX) or _context.SaveChangesAsync() - this also had the same results.
I would like to add a model into the Postgres database.


text:
Q: Copy war file from local machine to docker I am using docker and created a tomcat container which is running fine.
But I am not sure how to copy a war file in webapps folder of tomcat container.
Please help!
Thanks,
Yash

A: Multiple solution :

*

*Mounting an ssh server on your container and sending the files via
scp. (non-recommended if you don't already use ssh for something else)

*Adding the file during the building process (via Dockerfile and ADD https://docs.docker.com/reference/builder/#add)

*Sharing a volume between host and container. ( run -v command. More info
https://docs.docker.com/engine/admin/volumes/volumes/)

A: You can:

*

*build a new image with a Dockerfile based on your tomcat image and use the ADD command. Then start it

*use a volume which points to a local directory in which you put the war, the run the container which probably starts tomcat

*use a volume and use a data container to manage the data in it. Most advanced, but also the most compliant with Docker philosophy. For more information on this, please see https://docs.docker.com/engine/admin/volumes/volumes/


text:
Q: Won't vs wouldn't What is the difference in the usage of "won't" and "wouldn't" in these sentences:
The bathroom is filthy. I won't even wash my socks in it.
The bathroom is filthy. I wouldn't even wash my socks in it.

I know that "wouldn't" expresses refusal in the past but what does it mean in this sentence (if it's correct of course)?

A: wouldn't isn't only the past tense; it can also be used in a conditional or hypothetical sense.
"I won't even wash my socks in it" is a simple factual statement that I will not do it.
"I wouldn't even wash my socks in it" is essentially saying "I would not use it for anything, even washing my socks."  It's like saying "Wash my face in that bathroom?  I wouldn't even wash my socks in there" but we don't always say it so verbosely.


text:
Q: Concise RAII for Trompeloeil mocks I have classes like this:
/* "Things" can be "zarked", but only when opened, and they must be closed afterwards */
class ThingInterface {
public:
   // Open the thing for exclusive use
   virtual void Open();
   // Zark the thing.
   virtual void Zark(int amount);
   // Close the thing, ready for the next zarker
   virtual void Close();
};

/* RAII zarker - opens Things before zarking, and closes them afterwards */
class Zarker {
public:
    Zarker(Thing& thing): m_thing(thing) {
        m_thing.Open();
    }

    ~Zarker() {
        m_thing.Close();
    }

    void ZarkBy(int amount) {
        m_thing.Zark(amount);
    }

private:
    Thing& m_thing;
}

I then have a Trompeloeil mock class that implements the interface:
struct MockThing: public ThingInterface {
    MAKE_MOCK0(Open, void(), override);
    MAKE_MOCK1(Zark, void(int), override);
    MAKE_MOCK0(Close, void(), override);
};

I then wish to test a "zarking" of 42:, including the (critical) Open and Close procedure.
MockThing mockedThing;
trompeloeil::sequence sequence;

REQUIRE_CALL(mockedThing, Open())
    .IN_SEQUENCE(sequence));

REQUIRE_CALL(mockedThing, Zark(42))
    .IN_SEQUENCE(sequence));

REQUIRE_CALL(mockedThing, Close())
    .IN_SEQUENCE(sequence));

Zarker zarker(mockedThing);
zarker.ZarkBy(42);

This works nicely and demonstrates that a Zarker does, in fact, close its Thing after use (Bad Things happen if it does not).
Now, I have a lot more tests to go, and I'd like to stay DRY and avoid duplicating the mock expectations for the Open and Close calls. In real life, these expectations are actually not just a pair of functions, there are other setup and teardown actions that have to happen in careful order, and it'll be very annoying to have to repeat this in every test.
Since this is a RAII idiom, it seems natural to also use that for the expectations. However, because Trompeloeil expectations are scoped, you have to use NAMED_REQUIRE_CALL and save the unique_ptr<trompeloeil::expectations>:
class RaiiThingAccessChecker {
public:
    /* On construction, append the setup expectation(s) */
    RaiiThingAccessChecker(
        MockThing& thing,
        trompeloeil::sequence& sequence,
        std::vector<std::unique_ptr<trompeloeil::expectation>>& expectations
    ):
        m_thing(thing),
        m_sequence(sequence),
        m_expectations(expectations) {

        m_expectations.push_back(
            NAMED_REQUIRE_CALL(m_thing, Open())
                .IN_SEQUENCE(m_sequence)
        );
    }

    /* On wrapper destruction, append the teardown expectation(s) */
    ~RaiiThingAccessChecker() {
        m_expectations.push_back(
            NAMED_REQUIRE_CALL(m_thing, Close())
                .IN_SEQUENCE(m_sequence)
        );
    }

private:
    MockThing& m_thing,
    trompeloeil::sequence& m_sequence,
    std::vector<std::unique_ptr<trompeloeil::expectation>>& m_expectations
}

Then you can use it like this:
MockThing mockedThing;
trompeloeil::sequence seq;
std::vector<std::unique_ptr<trompeloeil::expectation>> expectations;

{
    RaiiThingAccessChecker checker(mockedThing, seq, expectations);

    mockExpectations.push_back(
        NAMED_REQUIRE_CALL(mockedThing, Zark(42))
            .IN_SEQUENCE(seq)
    );
}

Zarker zarker(mockedThing));
zarker.ZarkBy(42);

So that's functional enough, but it seems rather verbose - you have to hold
a container of expectation pointers, the sequence outside the RaiiThingAccessChecker
and you also have to pass them all in, and store references internally.
Is there a more concise way, or otherwise idiomatic way to achieve this kind
of "expectation reuse"? I have a lot of "modular" expectations that can be modelled like this.

A: I would have tendency to create function instead of RAII class there:
std::unique_ptr<std::pair<MockThing, trompeloeil::sequence>>
MakeMockedThing(std::function<void(MockThing&, trompeloeil::sequence&)> inner)
{
    auto res = std::make_unique<std::pair<MockThing, trompeloeil::sequence>>();
    auto& [mock, sequence] = *res;
    REQUIRE_CALL(mock, Open()).IN_SEQUENCE(sequence));

    inner(mock, sequence);

    REQUIRE_CALL(mock, Close()).IN_SEQUENCE(sequence));
    return res;
);

And then
auto p = MakeMockedThing([](MockThing& thing, trompeloeil::sequence& sequence)
    {
        REQUIRE_CALL(thing, Zark(42)).IN_SEQUENCE(sequence));
    });
auto& [mock, sequence] = *p;
Zarker zarker(mock);
zarker.ZarkBy(42);

Note: std::pair<MockThing, trompeloeil::sequence> might probably be replaced by template class to have nicer syntax.


text:
Q: How to open a modal referencing a menu id The following code works fine in opening a modal window with an html page inside.
Menu Modal Window

I have a Wordpress menu selection I want to reference to open the Modal. This is what the link looks like:

Menu Modal Window

I am not able to edit the menu code and add the onClick event as you see above, so I have added the following jQuery:
$('#menu-item-51').click(function() {
    $(this).modal({width:600, height:400}).open();
    return false;
});

This does not open the Modal but instead forwards to the testpage.html. I think my problem is with my reference to "this" in the jQuery. Not sure how to solve this problem...? Any assistance is greatly appreciated.

A: Seem like you want to target anchor instead of your list:
$('#menu-item-51 a').click(function() {
    $(this).modal({width:600, height:400}).open();
    return false;
});


text:
Q: Stackdriver Logging - Log severity levels not reported/received when sent via syslog It appears that log severity is not being passed to Google Cloud Logging platform via fluentd agent, to reproduce you can try:
Bash:
logger -p user.crit "My log"
or PHP:
php -r "syslog(LOG_CRIT,'My log');"
or Python:
import syslog

syslog.syslog(syslog.LOG_ERR, 'My log')

things are getting passed to Google Logs Viewer as below:

but severity is not being sent across, any ideas why would that be?

A: OK, managed to find the solution, here you go:

*

*update your syslog output format under /etc/rsyslog.conf to the following:
$template googlelogger,"%syslogseverity-text% %timegenerated% %HOSTNAME% %syslogtag% %msg%\n"
$ActionFileDefaultTemplate googlelogger

*then update /etc/google-fluentd/config.d/syslog.conf template format:
format /^(?<severity>[a-zA-Z]*) (?<time>[^ ]*\s*[^ ]* [^ ]*) (?<host>[^ ]*) (?<service>[a-zA-Z0-9_\/\.\-]*): *(?<message>.*)$/
time_format %b %d %H:%M:%S

make sure to restart both rsyslog and google-fluentd after that severity will be sent to Google Cloud Logging


text:
Q: how do i add css style in angularJs?

 {{section.sectionName}}

    <input type="submit" value="Submit" style="display:none" class="btn btn-primary" ng-click="submissionCtlr.submitForm()" ng-disabled="submitForm.$invalid">

this.tab=1;
this.selectTab = function(setTab){
 var tabcount = $scope.submissionCtlr.submissionForm.sections.length;
 if(this.tab != tabcount){
     this.tab++;
 }else {

 }

On click next button i got count, at the end of li count need to submit. submit should be display and next should be display: none. how can i acheive in anugularJs.

A: You can use ng-show to tell that if the current tab(tab) is the same as the total number of tabs(submissionCtlr.submissionForm.sections.length).
<input type="submit" value="Submit" ng-show="submissionCtlr.tab==submissionCtlr.submissionForm.sections.length" class="btn btn-primary" ng-click="submissionCtlr.submitForm()" ng-disabled="submitForm.$invalid">

A: For modifying the DOM elements in angularjs. The proper way is to create a directive and access the element in that directive.
For example -
<button  class="btn btn-primary" ng-click="submit()" on-submit> Submit </button>

JS:
 angular.module('myApp')
    .directive('onSubmit', ,function() {
      return {
        restrict: 'A',
        link: function($scope,el) {

              $scope.submit = function() {
                          el[0].css("display", "none");  //change the css here accordingly.
                        }

        }

     };

    });

You can also add the class like
element.addClass('myclass');


text:
Q: nsswitch.conf - cannot modify (read-only) I am attempting to modify nsswitch.conf from:

hosts: files dns

to

hosts: dns files

But, it is read-only. I have tried using:

sudo vi /etc/nsswitch.conf

And even with

:w!

It is unable to modify the file. How can I go about doing this? Currently my system is unable to

A: Change permissions on the file first:
sudo chmod u+w /etc/nsswitch.conf

That will give write permission to the owner (should be root). Then try editing it as you tried before:
sudo vi /etc/nsswitch.conf


text:
Q: How can I auto selct a List item from UL? CLick here to see image!
I want to auto click the list item new with the console imput in CHrome ->look image.
I dont know how to do it. Does Anybody has an idea?
I tried the following code but it didnt work:
document.getElementbyId("new-category").click();

A: Can you try below code on console ?
document.getElementById('new-category').click()

To add event listeners use below something code
document.getElementById('new-category').addEventListener("click", function(){
  document.getElementById("demo").innerHTML = "Hello World";
});

A: Use jQuery to trigger the click event by using the below code. See image from this link
http://prntscr.com/m0b5wz
$( "#new-category" ).trigger( "click" );

note: must add jquery first by pasting the all the code from this below google js to your console and then add the trigger event
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js


text:
Q: Swift/iOS SDK: Generic Function with Class Type/Name Closure/Block Issue I'm trying to write a generic class, that takes a custom class name and creates an instance of that class name.
Before and after creation I do some generic stuff that applies to all classes.
I want to add some parameters to the instance that are class specific. That's why I added a closure that gets called after the instance was created with the instance object itself as a parameter of the closure. The closure is optional.
Interestingly calling the function without the closure works just fine, if I add the closure I get the following compiler error:

Expected member name or constructor call after type name

This compiler error applies for the first parameter, which makes no sense, since calling the function just with the first parameter works fine...
I have added my simple example for Playground use:
class Base {
    var test1: Int = 0
}

class A: Base {
    var test2: Int = 0
}

class B: Base {
    var test3: Int = 0
}

func create<T: Base>(aClass: T.Type, addParameter:((T) -> Void)? = nil) {
    println("Do generic stuff before object is created")

    var object = aClass()

    // Add custom class specific parameters to object
    if let l_addParameter = addParameter {
        l_addParameter(object)
    }

    println("Do generic stuff after object was created")
}

create(A)
create(B)
create(B, addParameter: { (b: B) -> Void in
    b.test3 = 1000
})

Any help would be much appreciated! Thanks!

A: The correct way to pass a Type is ClassName.self, e.g.
create(A.self)
create(B.self, addParameter: { (b: B) -> Void in
    b.test3 = 1000
})

(and I cannot tell you why omitting .self works if the function
is called without additional arguments).
With this correction, your code compiles without errors, but does
not work. As noticed in Swift Generic Factory: Bug?,
you have to add an required init method to your base class,
class Base {
    required init() { } // ***
    var test1: Int = 0
}

otherwise
var object = aClass()

will always create an object of the base class and not of the actual
type what was passed as an argument (and therefore b.test3 = 1000
in the closure will abort with an exception).


text:
Q: scale up node in SQL Server always on I have two SQL nodes in always on availability group (SQL on VM) with Availability Set configured. In case one node goes down and another node is not able to cater the application load, how to scale up additional database node in availability group?
What is the process we need to follow to scale additional node ASAP? How do we manage load until we spin up additional node?

A: This is what I think is the approach to overcome this situation.

*

*Assume that your primary node (Node 1) goes down in SQL Server availability group, automatic failover would failover to the secondary replica node (Node 2). During the failover, the failover targets (Node 2) takes over the primary role and bring it online as the new primary database.

*Assuming primary node (Node 1) which went down cannot be bring back immediately, add the additional replica to the availability group.

*Start a new virtual machine with higher configuration (more CPU/RAM) with golden image (SQL server already installed)

*Add newly created VM (Node 3) to the cluster

*Restore the most recent full and transaction logs backup to it

*Join it to the availability group and add it to the routing list

*Manually failover to the newly created VM (Node 3) and make this node as primary

*Make Node 2 which was primary earlier as secondary Node


text:
Q: CLI to set variable of env file There is a .env file which looks like this:
VAR1=1
VAR2=2
VAR3=3

Now I would like to change a specific value in shell like this
cli set .env VAR2 foo

should give me the result
VAR1=1
VAR2=foo
VAR3=3

A: You can write a single line CLI which does what you want:
#!/bin/bash

operation=$1
file=$2
var=$3
value=$4
[[ "$operation" = "set" ]] && sed "s/^\($var\)=.*/\1=$value/" "$file"

A: I am not sure to understand your question properly, but here is my answer...
If you want to use environment variables, the best thing you can do is exporting them. If you want to keep this .env file, for example in your home directory, you could simply add this to your .bashrc:
source ~/.env
Then, you can use the following commands to manipulate your variables:

*

*env to display all environment variables

*echo $VAR1 to display the value of a specific variable

*export VAR2=foo to change the value of a given variable in the current shell session

If you want to make changes permanent, you can use sed:
sed -i '/VAR2/c\export VAR2=bar' .env


text:
Q: What is the maximum size of temp tablespace in oracle database? Trying to execute the next command
SELECT * FROM dba_temp_free_space

I am getting an error:

Error: ORA-01652: unable to extent temp segment by 128 in tablespace temp

and there are 32 GB of space is free, but when I ran a procedure I've got an error. When I check autoextending of the temp tablespace, it says YES..
What should I do to get maximum size of temp tablespace?

A: I think you are focusing on a solution, not the problem. A 32 GB tablespace should be adequate for most operations in a small OLTP database.  You have not told us much about what is running when you get the error so I can only supply some diagnostics and test queries.  The maximum size of any tablespace could be as much as 128 Terabyte or as small as 32 Terabyte with 8k block size.
Try this query while your problem object is running:
select TABLESPACE_NAME, BYTES_USED, BYTES_FREE from V$TEMP_SPACE_HEADER;

If you cannot change the problem object you can create a temporary tablespace group and add multiple temporary tablespaces to it.
Be sure to check what temporary tablespace the user who is running the object is using with a command like this:
ALTER USER scott TEMPORARY TABLESPACE temp;


text:
Q: JS tests with Karma/Mocha/Chai/Gulp I've tried to add testing to my web app boilerplate which is held together with gulp.
I've added Karma/Mocha/Chai and I have execute the testing in Gulp watch:
gulp.task('watch', ['browserSync', 'build-css'], () => {
    gulp.watch('./app/scss/**/*.scss', ['build-css']);
  gulp.watch(['app/*.html', 'app/js/**/*.js'], browserSync.reload);     //Also reloads the browser when HTML or JS changes
    gulp.watch(['app/js/**/*.js', 'test/**/*.test.js'], ['test']);      //Re-run tests whenever JS or test changes
});

gulp.task('test',                                                       //Run tests once
    shell.task('karma start --single-run --browsers ChromeHeadless karma.conf.js')
);

In my karma.conf.js I'm loading all my files:
files: [
  'app/*.html',
  'app/css/*.css',
  'app/js/**/*.js',
  'test/**/*.test.js'
],

Now, the actual test file works.  So if I have this:
script.test.js
describe('Array', () => {
    describe('#indexOf()', () => {
      it('should return -1 when the value is not present', () => {
        assert.equal(-1, [1,2,3,].indexOf(4));
      });
    });
  });

then I get a pass, no problem.

The problem I have is that my main script.js file is causing Karma to fall over. I believe it's because it's trying to manipulate the DOM.  I have a function called createUI which takes a couple of arguments, one of which is the ID of the page element the UI should be inserted into.  It works exactly as I want when it's being run normally, but when Karma runs a test it gives me this:
HeadlessChrome 64.0.3282 (Mac OS X 10.13.2) ERROR
  {
    "message": "Uncaught ReferenceError: table is not defined\nat /var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/app/js/script.js:10:0 <- /var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/195d5d9b0835bfdadaba24427f863496.browserify:11:43\n\nReferenceError: table is not defined\n    at Object.require./Users/jamesbrenton/Documents/webapp-boilerplate/app/js/script.js (/var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/app/js/script.js:10:0 <- /var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/195d5d9b0835bfdadaba24427f863496.browserify:11:43)\n    at s (/var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/node_modules/browser-pack/_prelude.js:1:0 <- /var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/195d5d9b0835bfdadaba24427f863496.browserify:1:273)\n    at app/js/script.js:1:34",
    "str": "Uncaught ReferenceError: table is not defined\nat /var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/app/js/script.js:10:0 <- /var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/195d5d9b0835bfdadaba24427f863496.browserify:11:43\n\nReferenceError: table is not defined\n    at Object.require./Users/jamesbrenton/Documents/webapp-boilerplate/app/js/script.js (/var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/app/js/script.js:10:0 <- /var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/195d5d9b0835bfdadaba24427f863496.browserify:11:43)\n    at s (/var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/node_modules/browser-pack/_prelude.js:1:0 <- /var/folders/bb/v9p4j7395_9f24f49p04h1pr0000gq/T/195d5d9b0835bfdadaba24427f863496.browserify:1:273)\n    at app/js/script.js:1:34"
  }

If I wrap my function call inside a window.onload block like this:
script.js
window.onload = function() {
    cards.createUI(deck, table);
};

then the tests appear to pass.  However, I cannot believe that this is the correct way of resolving this issue as the code works under normal circumstances. Can I delay Karma from starting tests until the DOM is loaded?  Or have I missed something here?


text:
Q: Get Values from child nodes from XML | Python I have the following XML.
I am using ElementTree library to scrape the values.
<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <url>
  <loc> Test1</loc>
  </url>
 <url>
  <loc>Test 2</loc>
 </url>
 <url>
  <loc>Test 3</loc>
 </url>
</urlset>

I need to get the values out of 'loc tag'.
Desired Output:
Test 1
Test 2
Test 3

Tried Code:
tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('url'):
 rank = atype.find('loc').text
print (rank)

Any suggestions on where am I wrong ?

A: Your XML has a default namespace (http://www.sitemaps.org/schemas/sitemap/0.9) so you either have to address all your tags as:
tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('{http://www.sitemaps.org/schemas/sitemap/0.9}url'):
    rank = atype.find('{http://www.sitemaps.org/schemas/sitemap/0.9}loc').text
    print(rank)

Or to define a namespace map:
nsmap = {"ns": "http://www.sitemaps.org/schemas/sitemap/0.9"}

tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('ns:url', nsmap):
    rank = atype.find('ns:loc', nsmap).text
    print(rank)

A: from lxml import etree

tree = etree.parse('sitemap.xml')
    for element in tree.iter('*'):
        if element.text.find('Test') != -1:
            print element.text

Probably isn't the most beautiful solution, but it works :)


text:
Q: Why does overcoming inertia depend upon time? When a paper over a glass is pulled suddenly, the coin over it falls to the water. But on pulling it slowly, the coin gets pulled along with the paper. Why does the coin in the former case not feel the force applied to the paper, but in the latter case does?
Does force take time to transfer between the not-rigidly connected bodies?
Otherwise why in the second case, inertia of both bodies is overcome, while in the first,only that of the paper?

A: The forces are the same (assuming the the coin is moving relative to the paper in both cases), is the friction force between the coin and the paper, and is in a first approximation at least, independent of the relative speed between paper and coin.
The difference between the two cases is that is that the force acts during a shorter time in the fast motion case, just because it took less time to remove the paper.
Because $F=ma$, then you have the same acceleration of the coin but acting during a shorter time $t$, thus the change in position of the coin $\Delta x=\frac{1}{2}at^2$ the coin will move a smaller distance in the fast case.

A: There is a limit on how much frictional force the penny can apply to the paper in order to remain attached to it. It is limited by its mass based on $F_f = \mu _s F_N = \mu _s * m_{penny}*g$. If you accelerate the paper, you are applying a force $F = ma $ and the penny's frictional force will try to oppose to keep the penny on the paper (inertia). For a certain amount of acceleration, the force will be greater than the force attaching the coin to the paper, leaving it behind.
Basically, if $m_{paper}* a_{paper} > \mu _s* m_{penny}*g $ then the penny will stay.

A: This happends because of the friction generated between the paper and the coin.
Remember, friction, at low speed, is not affected by the speed. So when you pull the paper, at any speed, the friction will have always the same value.
The distance covered by the coin is always $x=\frac{1}{2}\frac{F}{m}t^2$, where, $F$ is the force of the friction (constant), $m$ is the mass of the object (constant) and $t$ is the time that the coin moves.
So you can see that the distance covered by the coin is relative to the time. So small time equals small distance for the coin.
If the distance covered by the coin is small and the distance covered by the paper is big (because you pulled the paper really really hard), the coin will not be pulled away with the paper.


text:
Q: Having trouble specifying and splitting Pandas dataframes to modifying them separately I am trying to split a pandas dataframe from a single index into multiple by splitting each column into its own index if it contains a " ; ". I have found a way to successfully achieve what I want in small scale, but I know I need a better solution for when I move it into my main project.
import pandas as pd

input_values = [['1;3', '2;5', '3;7']]
df = pd.DataFrame(input_values, columns = ['a', 'b', 'c'])

columns = ['a', 'b', 'c']

data1 = pd.DataFrame(input_values, columns = ['a', 'b', 'c'])
data2 = pd.DataFrame(input_values, columns = ['a', 'b', 'c'])

for column in columns:
    new = df[column].str.split(";", expand = True)
    data1[column] = new[0]
    data2[column] = new[1]

df = data1.merge(data2, how='outer')
# df print
print('\n', df)

Which gives the output that I am looking for:
   a  b  c
0  1  2  3
1  3  5  7

My current problem is that I want df = data1 = data2 without having to specify each separately as I've done in my solution.
What is the better solution that I know I have overlooked? I'm looking for a way to specify my dataframe once and then set other variables equal to it.
Ex of what I want to have (this does not work however as each dataframe is updating together):
df = pd.DataFrame(input_values, columns = ['a', 'b', 'c'])

data1 = df
data2 = df

Thanks for your time and input, hopefully I'm not overlooking something too simple.

A: Check if the following works for you:
df
#Out[266]:
#     a    b    c
#0  1;3  2;5  3;7

df.T[0].str.split(';', expand=True).T
#Out[267]:
#   a  b  c
#0  1  2  3
#1  3  5  7

A: You can split columns in a list comprehension and concatenate the results:
pd.concat([df[x].str.split(";", expand=True).stack()
          for x in df], axis=1).loc[0]
#   0  1  2
#0  1  2  3
#1  3  5  7

And an even more efficient solution:
df.T[0].str.split(";", expand=True).T
#   a  b  c
#0  1  2  3
#1  3  5  7


text:
Q: map issues with objects js The below piece of code angular does not indexing properly it keeps data from previous objects for some reason. The issue it comes there. I want to map the objects from a list of objects and update their index.
for (let i of this.arrayofObjects) {
        lobby.list.map(function (item: Model, index: number) {
            item.position = index + 1;
        });


text:
Q: Pagination: How to display a long text as book pages? I have a very long text and I want to display it as a book in a web page. The user will use arrow keys to move forward and backward in same way like flipping pages of the book.
Leaving apart the transition of pages, how can this be achieved using jQuery?
What I thought was calculating the amount of text that will occupy the space on one page and then breaking the whole text into such pages and then displaying them. But it seems to be a bad idea for the space occupied will be platform dependent even if we fix the font.
One more problem that I was facing while using the space calculation method was due to the css justified display of text.
Has anyone done such thing before for a web page?

A: To layout a long string in a beautiful book page format. You need to get the exact string portion.  You can use this function.
function get_page($text, $page_index, $line_length=76, $page_length=40){
    $lines = explode("\n", wordwrap($texxt, $line_length, "\n"));
    $page_lines = array_slice($lines, $page_index*$page_length, $page_length);
    return implode("\n", $page_lines);
}

$line_length = 70;
$lines_per_page=50;
$page = 3;
$longtext= "...";

$page_text = get_page($longtext, $page-1, $line_length, $page_length);

See Demonstration.
Example
PHP
$longtext = "..."; // it can be retrieved from sql as well.
$index=is_int($_GET['page'])? intval($_GET['page']): 1;
$line_length = 70;
$lines_per_page=50;
$longtext= "...";

$page_text = get_page($longtext, $index-1, $line_length, $page_length);
echo json_encode(array('text'=>$page_text));

JQuery
var nextPage=2;
$.get("getpage.php", { page: nextPage }, function(data){
   alert("text is "+data.text;
   // show the text data.text
});


text:
Q: Unable to replace \" to " in javascript In my .js have a string
var jdata ="[{\"name\":\"John\"}]"
I want to convert it to [{"name":"John"}].
I tried the following but fail
jdata = jdata.replace("\"","\"")
jdata = jdata.replace("\\"","\"")
jdata = jdata.replace("\\\"","\"")
What is the right way to replace?

A: \ is just to use escape the double quotes inside the string (because you use double quote outside).
There is no \ char in your string actually.
If you want to turn the string to object, then use:
var obj = JSON.parse(jdata);

A: If you want it to become an object just do this:
JSON.parse(jdata);

The result will be [{"name":"John"}] objectified.
Otherwise, you already have the job done. If you try to print "[{\"name\":\"John\"}]" you will see that has no \ character as it is an escape character.

A: When you print the string you will see the escape character \ is not displayed. It is just needed because something enclosed in quotes can't contain quotes that are not escaped.

A: If all you want is to convert it to a string [{"name":"John"}], you can use regex to do that with:
jdata = jdata.replace(/\\\"/,"\"");


text:
Q: Управление SVG-координатами `path` с помощью JavaScript У меня есть path SVG со следующими точками в атрибуте d.
Есть ли способ изменять только одно из координатных чисел в 'd', скажем, как 0 в "L25 0", чтобы манипулировать в сценарии JavaScript?
Если это возможно, то как бы выглядел этот синтаксис?
Я хочу получить доступ к одному из координатных чисел, чтобы я мог увеличить его,  и тем самым анимировать path.

function NavHalf() {
  var arrow = document.getElementById("arrowUp");
  arrow.setAttribute('d', 'M0 25 L25 0 L50 25');
}
<svg height="25" width="50" onclick="NavHalf()">
   <path id="arrowUp" d="M0 0 L25 25 L50 0 " style="stroke:green;stroke-width:2; fill:none" />
</svg>

Свободный перевод вопроса Manipulating SVG Path Coordinate with Vanilla JavaScript от участника  @Nhan Bui.

A: На самом деле нет никакого основанного на DOM способа прямого доступа и манипулирования только одной из точек в определении пути.
Манипулирование строками - это все, что вы можете сделать.

function NavHalf(x,y) {
  var arrow = document.getElementById("arrowUp");
  arrow.setAttribute('d', 'M0 0 L' + x + ',' + y + ' L50 0');
}
<button type="button" onclick="NavHalf(25,0)">Position 1</button>
<button type="button" onclick="NavHalf(20,15)">Position 2</button>
<button type="button" onclick="NavHalf(25,25)">Position 3</button>

<svg height="25" width="50">
   <path id="arrowUp" d="M0 0 L25 25 L50 0" style="stroke:green;stroke-width:2; fill:none" />
</svg>

Свободный перевод  ответа от участника  @Paul LeBeau.

A: Часть 1
Так как значение отдельной координаты здесь не является объектом/свойством DOM, прямые манипуляции с этим значением в JS невозможны - вместо этого мы манипулируем атрибутом, изменяя его строковое значение.
И, существует...

Типовой подход - реактивные библиотеки, фреймворки
(только критика, без примеров)
Сейчас уже мало кто пишет голый JS для решения подобных задач: распространена практика использования реактивных библиотек, чтобы упростить работу - и писать меньше кода, тем самым облегчая его поддержку.
Ну, так это должно работать...
Посмотрим как это выглядит для начинающего:
Для начала, нужно выбранную библиотеку подключить. Или две библиотеки, в случае реакта. Теперь страничка грузится чуть дольше. Хм, ну ладно, вроде мелочь - можно потерпеть ради преимуществ.
Далее надо написать бойлерплейт-код, в который поместим ту логику связи с DOM, которую мы хотим. Тут уже возникает смутное ощущение, что... а, неважно. Напишем. Мыжпрограммисты, в конце концов.
Но как-то это не очень удобно, в разметке набирать. Перенесем код в отдельный модуль - и бандлером будем все вместе собирать. Вебпак, то что нужно! Поглядим как его настраив... оооо... нет, НЕТ, мы не будем его настраивать. Все ж работает, да? Вот и хорошо, вот и славно.
Чтобы быстрее оправиться от психической травмы нанесенной вебпаком, изучим и применим TS - не надо будет сильно думать о логике выражений с типкастом. В самом деле, пусть машина думает, а нам и бойлерплейтов хватает... ведь мы уже по уши в фреймворке.
Вышло так, что в попытке упростить свою работу, мы ее усложняем.
Инструменты, призванные помочь сконцентрироваться на программировании, уводят все дальше от программирования: мы npm install половину задач, и зависимы от внутренней магии готовых решений.
Экономия времени и совершенствование библиотек это в целом хорошо, если бы разработчики не забывали язык(!) и не теряли гибкость ума, попадая в ловушку бездумного потребления.
Многобукв, но зачем? Просто этим подвожу к альтернативному варианту, который вдохновляет лично меня. К варианту, который хотя бы частично вернет мотивацию вникать, понимать, развивать фундаментальные навыки - и к отказу от "жизни в фреймворке", в пользу реализации реактивности на уровне языка.
Этот вариант существует больше на уровне идеи, но есть несколько первых попыток ее воплотить. Здесь упомяну только одну молодую реализацию, а именно...

Svelte
<svg height="25" width="50" on:click={toggle}>
   <path d="M0 0 L25 {$midY} L50 0" style="stroke:green; stroke-width:2; fill:none;" />
</svg>

<script>
  import { tweened } from 'svelte/motion';
  import { cubicOut } from 'svelte/easing';

  const midY = tweened(0, { duration: 250, easing: cubicOut });
  const toggle = () => midY.set($midY ? 0 : 25);
</script>

  Попробовать в REPL
Здесь мы связываем значение в атрибуте с переменной midY, которая плавно (необязательный бонус) меняет значение в функции toggle.
Код выглядит изящно, работает быстро, и не будет утяжелять страницу.
А главное - Svelte не очередной фреймворк, это транслятор (компилятор). Его синтаксис переводится в стандартный JavaScript, который можно изучить и понять, если захочется.
То есть, это тоже магия, но она значительно ближе к разработчику. И хотя бандлер по-прежнему требуется (как минимум для трансляции), все же сделан большой шаг в идеологии реактивности, и в избавлении от бойлерплейтов - пишем только логику.
Данный пример очень прост, а вся мощь реактивного программирования раскрывается только в более сложных задачах (как многие из нас уже знают, применяя например RxJS к данным и событиям).
Но и такие вот маленькие задачи по-прежнему выигрывают: в читаемости кода, а также в скорости и весе, по сравнению с React и Vue.
Можно ли использовать Svelte в продакшене - пока что нет: технология очень вкусная, но местами еще не просушена, и экосистема только зарождается (до третьей версии проект был мало кому известен).
Стоит ли ознакомиться и держать руку на пульсе - определенно да. Если даже Svelte будет незаслуженно брошен сообществом, схожие принципы используются в проекте Stencil (от Google).

Ответ получился рекламным, поэтому возможные минусы и тревоги будут встречены с пониманием.

A: Часть 2
Стандартный JavaScript
Упростить работу с отдельными значениями координат path можно и на чистом JS, без зависимостей. Например, можно добавить недостающее DOM-свойство d, и перехватывать обращения к нему используя Proxy (ES6+).
Следующий пример демонстрирует визуализацию частот во время воспроизведения звукового файла. Отрисовка линии выполняется через path (130 точек):

function attributesSerializer(element, attributes) {
  return new Proxy(element, {
    get(el, prop) {
      if (prop === '$attrs') return this.$attrs;
      if (this.$attrs[prop]) return this.$attrs[prop];
      const val = el[prop];
      return (typeof val === 'function') ? val.bind(el) : val;
    },
    set(el, prop, val) {
      if (prop in this.$attrs) return false;
      return ((el[prop] = val), true);
    },
    $attrs: attributes.reduce((r, { attr, delim=' ' }) => {
      r[attr] = new Proxy({}, {
        get(obj, i) {
          const values = element.getAttribute(attr).split(delim).map(v => v.trim());
          return values[i];
        },
        set(obj, i, newVal) {
          const values = element.getAttribute(attr).split(delim).map(v => v.trim());
          values[i] = newVal;
          element.setAttribute(attr, values.join(delim));
          return true;
        }
      });
      return r;
    }, {})
  });
}

const path = attributesSerializer(document.querySelector('path'), [
  { attr: 'd', delim: '\n' }
]);
let analyser, bufferLen, freqData;

document.querySelector('input').addEventListener('change', e => {
  const audio = document.querySelector('audio');
  audio.src = URL.createObjectURL(e.target.files[0]);
  audio.load();
  const ac = new AudioContext(),
        src = ac.createMediaElementSource(audio);
  analyser = ac.createAnalyser();
  src.connect(analyser);
  analyser.connect(ac.destination);
  bufferLen = (analyser.fftSize = 512) / 2;
  freqData = new Uint8Array(bufferLen);
  audio.play();
  loop();
});

function loop() {
  analyser.getByteFrequencyData(freqData);
  path.d[0] = `M0,100 0,${100 - freqData[0] / 2.55}`;
  for (var i = 2; i < bufferLen; i += 2)
    path.d[1 + i / 2] = `${100 * i / bufferLen},${100 - freqData[i] / 2.55}`;
  path.d[i] = 'L100,100 Z';
  requestAnimationFrame(loop);
}
body { display: flex; flex-flow: column nowrap; align-items: stretch; height: calc(100% - 32px); }
svg { align-self: center; width: 100%; max-width: 400px; height: 100px; outline: 1px dashed #ccc; }
input { margin: 0.5rem 0; }
audio { width: 100%; outline: none; }
input:invalid + audio { display: none; }
<svg viewBox="0 0 80 100" preserveAspectRatio="none">
  <path d="" fill="#def" stroke="#00f" stroke-width="0.1" />
</svg>
<input type="file" accept="audio/*" required>
<audio controls></audio>

Здесь функция attributesSerializer возвращает экземпляр Proxy, привязанный к DOM-объекту элемента path.
Этим прокси мы ловим только обращения к добавленному свойству d - которое так же отслеживается через прокси (вложенный), что позволяет считывать и присваивать значения отдельных точек в одноименном атрибуте через квадратноскобочную нотацию вида pathElement.d[индексТочки].
В качестве символа-разделителя для (де)сериализации атрибута используется символ \n.

Такой подход обладает рядом недостатков. Основными минусами реализации являются ее относительная сложность, низкое быстродействие, и то что она является "велосипедом".
Поэтому, для решения таких задач, всегда лучше использовать реактивность. Ведь инструменты которые ее реализуют, предоставляют также массу других возможностей, помимо работы с атрибутами SVG.


text:
Q: add postgres partitioning to existing table All examples show:
CREATE TABLE ... PARTITION BY ...

Which is kind of ridiculous, because the only time you would use partitioning is when a dataset has become too large, which by definition is not going to be a new table. If someone is making a new table with partitioning, i think almost anyone would criticize that as a premature optimization.

A: Just create a partitioned table and attach the existing table as a partition:
create table test (a int);

insert into test select generate_series(1,10);

alter table test_parent attach partition test DEFAULT;

select * from test_parent;
 a
----
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
(10 rows)

You could also rename the table.  However, if you do this, you will need to re-define any views that point at the original table.


text:
Q: How to disable (completely) and enable any mouse listener in jQuery? I have a strange question: How to disable all mouse events (mousewheel, click, hover etc.) on button click and after a timeout, for example 1s, enable them again?
First I've tried with the unbind/bind functions but there is a strange bug with the scroll events on Apple Magic mouse. Than I came up with this:
$("* ... or some selector").on("scroll click ...", function(){
  return false;
});

Its'not very pretty but it's work. The problem is that I don't know how to re-enable the events after one second for example?
Any ideas would be greatly appreciated.

A: You're currently probably using anonymous functions. If you actually name your function, you can always reinitialize your event listener later:
var myMethod = function () {
    // does something
}

$('my selector').on('my event', myMethod)

As for the one second: timeout


text:
Q: ADODB - Creating a VBA Function to minimize repeated code? i have the following code which gets data from a database table with ADODB and outputs to sheet.
I use this a lot, changing between cnn (access / mysql etc....) / different queries.
Is there a way i can create this as a function to minimize repeated code?
Sub getDBdata()
    Dim Cnn As ADODB.Connection
    Dim rs As ADODB.Recordset

     Set Cnn = New ADODB.Connection
     Set rs = New ADODB.Recordset

    Cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\test\TESTDB.MDB"

     SQLString = "SELECT * FROM TABLE1"

    rs.Open SQLString, Cnn, adLockReadOnly

    Sheet1.Range("A2").CopyFromRecordset rs

    rs.Close

    Cnn.Close
    Set Cnn = Nothing
    Set rs = Nothing
End Sub

example:
sub getSpecificData()

Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\test\TESTDB.MDB"
SQLString = "SELECT COLUMN1 FROM TABLE1"
OutputLocation = Sheet1.Range("A1")

      getDBData Connection, SQLString, OutputLocation

End Sub

Appreciate any help

A: The simplest thing to do is to add 3 parameters to your sub:
Sub getDBdata(connString as string, SQL as String, rngDest As Range)
    Dim Cnn As ADODB.Connection
    Dim rs As ADODB.Recordset

    Set Cnn = New ADODB.Connection
    Set rs = New ADODB.Recordset

    Cnn.Open connString
    rs.Open SQL, Cnn, adLockReadOnly
    rngDest.CopyFromRecordset rs

    rs.Close
    Cnn.Close
    Set Cnn = Nothing
    Set rs = Nothing
End Sub