text:
Q: spring security and facebook authentication not working I want to use facebook login + DB authentication in my application which uses Spring Security.
So I have added one fb button in index.jsp page which sends request like,
function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
        console.log('Good to see you, ' + response.name + '.' + response.email);
        window.location = "<%=request.getContextPath()%>/j_spring_facebook_security_check";
    });
}

applicationContext-Security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans">
    //spring security 3.
    <security:http auto-config="true" use-expressions="true" access-denied-page="/accessDenied.jsp">
        <security:form-login login-page="/index.jsp"
            default-target-url="/jsp/home.jsp"
            authentication-failure-handler-ref="authenticationFailureHandler"/>

        <security:intercept-url pattern="/jsp/listInBetweenPlaces.jsp"
            access="permitAll" />

        <security:intercept-url pattern="/jsp/home.jsp"
            access="permitAll" />

        <security:intercept-url pattern="/index.jsp"
            access="permitAll" />

        <security:intercept-url pattern="/jsp/*"
            access="isAuthenticated()" />

        <security:logout logout-url="/j_spring_security_logout" logout-success-url="/index.jsp?logout=success"
            invalidate-session="true"  />

        <security:custom-filter before="FORM_LOGIN_FILTER"
            ref="facebookAuthenticationFilter" />
</security:http>

    <bean id="facebookAuthenticationFilter" class="org.springframework.security.facebook.FacebookAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager"/>

        <property  name = "authenticationSuccessHandler">
            <bean  class = "org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
                <property  name = "defaultTargetUrl"  value = "/jsp/home.jsp"  />
                <property  name = "alwaysUseDefaultTargetUrl"  value = "true"  />
            </bean>
        </property>

        <property  name = "authenticationFailureHandler">
            <bean  class = "org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
                <property  name = "defaultFailureUrl"  value = "/fb/failure.jsp"  />
            </bean>
        </property>
    </bean>

    <bean id="authenticationProviderFacebook" class="org.springframework.security.facebook.FacebookAuthenticationProvider">
        <property name="roles" value="ROLE_FACEBOOK_USER" />
    </bean>

    <bean id="facebookHelper"  class="org.springframework.security.facebook.FacebookHelper">
        <property  name="apiKey"  value="my_api_key"  />
        <property  name="secret"  value="my_secret_key"  />
    </bean>

    <bean id="customUserDetailsService" class="com.onmobile.carpool.authentication.CustomUserDetailsService">
        <!--  <property name="carpoolService" ref="carpoolServiceImpl" /> -->
    </bean>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider user-service-ref="customUserDetailsService">
            <security:password-encoder hash="md5" />
        </security:authentication-provider>
        <security:authentication-provider ref="authenticationProviderFacebook">
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

FacebookAuthenticationFilter.java:
public class FacebookAuthenticationFilter extends
                AbstractAuthenticationProcessingFilter implements
                ApplicationContextAware {

    public static final String DEFAULT_FILTER_PROCESS_URL = "/j_spring_facebook_security_check";
    private FacebookHelper facebookHelper = null ;
    private ApplicationContext ctx;
    protected FacebookAuthenticationFilter() {
        super(DEFAULT_FILTER_PROCESS_URL);
    }

    public Authentication attemptAuthentication(HttpServletRequest req,
                        HttpServletResponse res) throws AuthenticationException,
                        IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        if(facebookHelper == null){
            facebookHelper = (FacebookHelper) ctx
                    .getBean("facebookHelper");
        }

        Long uid = null;
        String sessionkey = null ;
        try {
            uid = facebookHelper.getLoggedInUserId(request, response);
            sessionkey = facebookHelper.lookupSessionKey(request);
        } catch (FacebookUserNotConnected e) {
            throw new AuthenticationCredentialsNotFoundException(
                                        "Facebook user not connected", e);
        }

        FacebookAuthenticationToken token = new FacebookAuthenticationToken(uid);
        token.setSessionkey(sessionkey);
        token.setDetails(authenticationDetailsSource.buildDetails(request));

        AuthenticationManager authenticationManager = getAuthenticationManager();
        Authentication authentication = authenticationManager
                                .authenticate(token);

        return authentication;
    }

    public void setApplicationContext(ApplicationContext ctx)
                        throws BeansException {
        this.ctx = ctx;
    }

    public FacebookHelper getFacebookHelper() {
        return facebookHelper;
    }

    public void setFacebookHelper(FacebookHelper facebookHelper) {
        this.facebookHelper = facebookHelper;
    }

}

I am always getting problem with this call:
 uid = facebookHelper.getLoggedInUserId(request, response);

Details of getLoggedInUserId in FacebookHelper.java:
public Long getLoggedInUserId(HttpServletRequest request,
                    HttpServletResponse response) throws FacebookUserNotConnected {

    FacebookWebappHelper<Document> facebook = new FacebookWebappHelper<Document>(
                        request, response, apiKey, secret);
    Long uid = facebook.getUser();

    if (uid == null)
            throw new FacebookUserNotConnected(
                            "Facebook user id could not be obtained");
    return uid;
}

Below line always evaluates to null because of which it throws exception:
Long uid = facebook.getUser();

I took Facebook Related classes from link below,
https://code.google.com/p/spring-security-facebook/source/browse/trunk/src/?r=4#src%2Fmain%2Fjava%2Forg%2Fspringframework%2Fsecurity%2Ffacebook
My need is to keep user can either login to my app through DB check or through FB authentication.
I am not able to go ahead with this, can some one please point out What I am missing.
I am always getting redirected to failure.jsp.
Is there any thing i need to enable in FB account?
Or I am passing some incorrect data from UI to Filter?
I am not able to find complete tutorial anywhere for this, can someone point out the correct link.

A: I did something similar in a recent app I've been working on. I looked into using the Spring-Oauth project to perform the oauth authentication but realized later on that spring-oauth requires you to already be authenticated in your application, and all other solutions I found online were out-dated.
After struggling for a couple days this is what I ended up doing. I'm using JSF with PrimeFaces in my app, but I hope it'll give you an idea. The approach is to initially use the Facebook Javascript API to perform the Facebook authentication for you. There are plenty of examples on the Facebook page on how to do this:
login.xhtml - Facebook API section
...
FB.Event.subscribe('auth.authResponseChange', function(response) {
  // Here we specify what we do with the response anytime this event occurs.
  if (response.status === 'connected') {
    //a user has logged in to the app
    var responseToken = response.authResponse.accessToken;
    var responseUserId = response.authResponse.accessToken;
    loginJS([{name:'token', value: responseToken}, {name:'name', value: responseUserId}]);
  }
});
...

Somewhere in the body of you page also add this:
<p:remoteCommand name="loginJS" action="#{userBean.facebookLogin}" immediate="true"  process="@this" />;

The p:remoteCommand calls the managed bean (userBean) facebookLogin function. This function retrieves from the request the two parameters (userId, token). In your case, all you need to do is call your "login" servlet from the javascript and pass the two parameters as part of the request.
UserBean.java
public String facebookLogin(){
    FacesContext context = FacesContext.getCurrentInstance();
    Map<String, String> map = context.getExternalContext().getRequestParameterMap();
    String userToken = map.get("token");
    String name = map.get("name");

    if(logger.isLoggable(Level.FINEST)){
        logger.finest("Login attempt via facebook. Token: "+ userToken);
    }

    Authentication auth = new FacebookTokenAuthentication(userToken, name);

    SecurityContextHolder.getContext().setAuthentication(auth);

    return "home?faces-redirect=true";
}

FacebookTokenAuthentication.java
public class FacebookTokenAuthentication implements Authentication {

    /**
     *
     */
    private static final long serialVersionUID = 4218179259794454698L;
    private String token;
    private String name;

    public FacebookTokenAuthentication(String token, String name) {
        this.token = token;
        this.name = name;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return new ArrayList<GrantedAuthority>(0);
    }

    @Override
    public Object getCredentials() {
        return token;
    }

    @Override
    public Object getDetails() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return null;
    }

    @Override
    public boolean isAuthenticated() {
        return false;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated)
            throws IllegalArgumentException {
    }

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

FacebookAuthenticationProvider.java
The last part is to create a facebook authentication provider. This Authentication provider will call the facebook API to obtain the user information and lookup the user in your databases that matches. You can map the facebook id of the user in your database or you can use the email address to find the user. For this part I used spring-social FacebookTemplate to obtain the facebook profile information.
public class FacebookAuthenticationProvider implements AuthenticationProvider {
    private static final Logger logger = Logger
            .getLogger(FacebookAuthenticationProvider.class.getName());

    /*
     * (non-Javadoc)
     *
     * @see org.springframework.security.authentication.AuthenticationProvider#
     * authenticate(org.springframework.security.core.Authentication)
     */
    @Override
    public Authentication authenticate(Authentication auth)
            throws AuthenticationException {
        Authentication resultAuth = null;
        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("Attempting to authenticate user via the FacebookAuthenticationProvider.");
        }

        if (auth.isAuthenticated()) {
            return auth;
        }

        if (auth instanceof FacebookTokenAuthentication) {

            FacebookTokenAuthentication fbAuth = (FacebookTokenAuthentication) auth;
            String token = (fbAuth.getCredentials() != null) ? fbAuth
                    .getCredentials().toString() : null;

            if (logger.isLoggable(Level.FINEST)) {
                logger.finest("Creating facebook template. Token:" + token);
            }

            FacebookTemplate fbTemplate = new FacebookTemplate(token);

            FacebookProfile userProfile = fbTemplate.userOperations()
                    .getUserProfile();

            // LOOKUP THE USER IN YOUR DATABASE
            User user = //ADD CUSTOM USER LOOKUP HERE;

            resultAuth = new PreAuthenticatedAuthenticationToken(user, token);
            resultAuth.setAuthenticated(true);
        } else {

            throw new BadCredentialsException("Invalid credentials.");
        }

        return resultAuth;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.springframework.security.authentication.AuthenticationProvider#supports
     * (java.lang.Class)
     */
    @Override
    public boolean supports(Class<?> auth) {
        return auth.equals(FacebookTokenAuthentication.class);
    }

}

Dont forget to add the AuthenticationProvider to your Spring configuration


text:
Q: Trying to determine if there is any Advantage If I was in SQL Server i would just look at the execution plan, but i don't have rights to do that in my Oracle systems and I cannot see any speed difference when running. Any thoughts?
SELECT c_ID, c_Date
      FROM Table1
      WHERE CUR_IND = 'Y'
UNION
SELECT c_ID, c_Date
      FROM Table1
      WHERE LAST_UPDATE_DATE BETWEEN  TO_DATE('2015-07-01','YYYY-MM-DD') AND TO_DATE('2015-07-20','YYYY-MM-DD')
      AND c_ID NOT IN (SELECT c_ID FROM Table1 WHERE CUR_IND = 'Y')

I guess my main question, which seems obvious sorta is, since Union is going to run a distinct on this query, is the Sub Query in the second select helpful? This returns about 400K records on the first select, and about 10K on the 2nd, with the sub query the 2nd only returns 2. With or without it I get the same result in what appears to be the same amount of time. (Wishing i could see execution plan)

A: You don't need a UNION at all.  Just have a single query with an OR between your conditions (unless the c_ID-c_Date combination is not unique, in which case UNION might have been filtering out duplicate rows as well. But I suspect this is not your case.):
SELECT c_ID, c_Date
FROM Table1
WHERE CUR_IND = 'Y'
OR LAST_UPDATE_DATE BETWEEN  TO_DATE('2015-07-01','YYYY-MM-DD') AND TO_DATE('2015-07-20','YYYY-MM-DD')

Or... if the UNION from your original query was also performing DISTINCT duties for you, then simply add a DISTINCT:
SELECT DISTINCT c_ID, c_Date
FROM Table1
WHERE CUR_IND = 'Y'
OR LAST_UPDATE_DATE BETWEEN  TO_DATE('2015-07-01','YYYY-MM-DD') AND TO_DATE('2015-07-20','YYYY-MM-DD')

EDIT
Based on your comments, it sounds like you'll be writing a query like this (adding in for completeness):
SELECT c_ID, c_Date
FROM (
    SELECT c_ID, c_Date,
           row_number() over (partition by c_ID
                              order by case when CUR_IND = 'Y' then 1 else 2 end) as rn
    FROM Table1
    WHERE CUR_IND = 'Y'
    OR LAST_UPDATE_DATE BETWEEN  TO_DATE('2015-07-01','YYYY-MM-DD') AND TO_DATE('2015-07-20','YYYY-MM-DD')
) WHERE rn = 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Atypical merging in Google Sheets (only few common columns) I know, that there are many threads about merging sheets, but I'm solving uncommon problem. I couldn't find the answer for this here. I have Google Sheets document, which is working as an IT inventory. I have many sheets in that document. There is for example sheet servers, cameras, switches etc... (sheet - servers, sheet - switches, sheet - cameras).
There are few common columns in each sheet like a locality, IP address, manufacturer, model etc. and a lot of specific columns for each kind of device. Servers have an operating system column, switches has a VLAN settings columns and so on... I need to use all these sheets and create one new overview sheet. There will be all common columns from all sheets and relevant records, so I could for example filter out all devices in one location and see their IP addresses, count devices in one location, sort all devices according to their IP address and so on. (overview sheet)
Was anyone solving this?

A: So here it is. I wrote it:
function makeSummarySheet() {
  // spreadsheet ID
  var ID = '6Ca-aDgaHRsAALAh85vXjC79na4vgSOjs45Q6dOqxfQQ';
  // sheet names
  var sheetsArray = ["servers", "switches", "cameras"];
  // common columns - CASE SENSITIVE!
  var wantedColumns = [["name", "model", "locality", "IP address"]];
  // final summary array
  var overviewArray = [];
  var ss = SpreadsheetApp.openById(ID);

  var date = new Date();
  var dateTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +  date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

  if (sheetsArray.length >= 1) {
    for (var x = 0; x < sheetsArray.length; x++) {
      var sheet = ss.getSheetByName(sheetsArray[x]);
      var sheetID = ss.getSheetByName(sheetsArray[x]).getSheetId();
      var lastRow = sheet.getLastRow();
      var lastColumn = sheet.getLastColumn();
      var columnNames = sheet.getRange(1, 1, 1, lastColumn).getValues();
      var sheetData = sheet.getRange(2, 1, lastRow-1, lastColumn).getValues();
      var cachedColumns = [wantedColumns[0],[]];

      for(var i=0; i < lastColumn; i++) {
        for(var y=0; y < wantedColumns[0].length ; y++) {
          if (columnNames[0][i] == cachedColumns[0][y]) {
            cachedColumns[1][y] = i;
          }
        }
      }

      for(var i =0; i < sheetData.length-1; i++) {
        var tempArray = [];
        tempArray[0] = '=hyperlink("#gid='+sheetID+'&range='+sheet.getRange(i+2,cachedColumns[1][0]+1).getA1Notation()+'";"'+sheetData[i][cachedColumns[1][0]]+'")';
        for(var y=1; y < wantedColumns[0].length; y++) {
          tempArray[y] = sheetData[i][cachedColumns[1][y]];
        }
        overviewArray.push(tempArray);
      }
    }
  }

  var overviewSheet = ss.insertSheet("SUM " + dateTime, ss.getSheets().length+1);
  overviewSheet.getRange(1, 1, 1, wantedColumns[0].length).setValues(wantedColumns).setBorder(null, null, true, null, null, null).setFontWeight("bold");
  overviewSheet.getRange(2, 1, overviewArray.length, wantedColumns[0].length).setValues(overviewArray);
  overviewSheet.getRange(1, 1, overviewSheet.getLastRow(), overviewSheet.getLastColumn()).createFilter();

}

edit: according to comment - "for each" replaced


text:
Q: How do i open and create a file like this? Well,my current situation is like this.
When i search something on my site for ex. http://example.org/web-search.phtml?search=SEARCHED+TEXT the respective content is shown.
As you can see I'm using a GET form to get the data from the previous form.So the first thing i want to do is open a file with the same as SEARCHED+TEXT.So now i want to open and save file in
http://example.org/web-search/SEARCHED+TEXT.html

So each time a person searches a page like  http://example.org/web-search.phtml?search=SEARCHED+TEXT a respective .html file should be created in the respective folder
And no.2
Now i want the whole source of http://example.org/web-search.phtml?search=SEARCHED+TEXT to be copied into http://example.org/web-search/SEARCHED+TEXT.html
So how do i do this ?
NOTE: If i copy the whole source including the code for copying and creating file then each time the person creates http://example.org/web-search/SEARCHED+TEXT.html a new HTML file will be Opened..
So i hope you got my BIG BIG question !!
I'm not saving the results.I'm just saving the iframe source.So technically its not static

A: You can use file_put_contents() and the $_GET to do the operations you want.
Firstly you can get the filename of the file by calling :
$filename = $_GET['search'] . '.html';

That would return your value, SEARCHED+TEXT
Secondly you can use file_put_contents($filename, $some_source_content) to create the file.

A: What i think you want to do is use apache mod_rewrite, you point anything from /web-search/(.*).html to some php file on your server (search.php) and use that PHP file to render all of your searches.  This will give you the dynamics you want without creating a billion flat files on your server for no good reason.


text:
Q: Dialogflow : followEventInput I want to use follow-up intent. My user says something which launch an intent, send a response and launch another one, which sends a response and launch another one... I use those function
function send_message_follow(res,output,token,quote,id,action,parametre){
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({
    "fulfillmentText" : output,
    "outputContexts": [
        {
            "name": id + "/contexts/connected",
            "lifespanCount": 5,
            "parameters": {
                "token": token,
                "quote" : quote
            }
        }
    ],
    "followupEventInput": {
        "name": action,
        "languageCode": "fr",
        "parameters": {
            "param": parametre,
        }
    }
}));`

function send_message_final(res,output,token,quote,id){
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({
        "fulfillmentText" : output,
        "outputContexts": [
            {
                "name": id + "/contexts/connected",
                "lifespanCount": 5,
                "parameters": {
                    "token": token,
                    "quote" : quote
                }
            }
        ]
    }));
However, output is not shown with send_message_follow. I works only with send_message_final. I could add the 1rst output as a parameter to catch for the other ones, but this shows only 1 block of message. I want 1 per intent.
Is there a way to fix this ? Thanks

A: No, there is no way to "fix" this.  Follow up events are a way to redirect from the currently match intent to another intent.  The currently match intent does not have a chance to respond before it is redirected.  This means you will only have one response from the intent that is redirected to last.  You can't compile response from multiple intent responses by redirecting through multiple intents with follow up events.
When a followup event is triggered from the webhook, the event specified in the webhook response is triggered. Triggering the event through a webhook sends the request back through Dialogflow for matching without responding to the user. The response to the user is sent as if the user triggered the event that was triggered in the webhook.  After the second intent is matched by the event, Dialogflow will do any necessary work (like webhook calls or additional prompts for required parameters) and send a response back as if the second intent was the originally matched intent.

*

*A user sends a request to Dialogflow.

*"Intent 1" is matched by Dialogflow.

*A webhook request is sent to your fulfillment server, which indicates that intent 1 was matched.

*Your fulfillment server responds to the webhook request with a followup event response.

*Dialogflow re-matches intent 2 based on the followup event sent in the webhook response.

*Dialogflow sends a response to the user based solely on intent 2 being matched. Dialogflow may send another webhook call indicating intent 2 was matched, or send a prompt for unfulfilled required parameters (if configured) for intent 2.


text:
Q: Dynamically add property:value in JSON through rest services How do we create a json property:value dynamically by taking them as inputs from the user through a REST service, without having to have fields to hold the value.
Basically, the present output is :
{
    "name": "X",
    "price": "X",
    "ticker": "X",
    "status": "X",
    "supplier": "X",
    "attribute": [{
            "key": "index",
            "value": "Nasdaq"
        },
        {
            "key": "priority",
            "value": "high"
        }
    ]
}

Required output is :
{
    "name": "X",
    "price": "X",
    "ticker": "X",
    "status": "X",
    "supplier": "X",
    "attribute": [{
            "index": "Nasdaq"
        },
        {
            "priority": "high"
        }
    ]
}

Here, index and Nasdaq are the values given by the user, which is the key-value pair that is to be added to the attribute list.
The two POJO's used :
Stock.java
@XmlRootElement
public class Stock {

    public Stock() {

    }

    public Stock(String name, double price, String ticker, String status, String supplier, List<KV> attribute) {
        super();
        this.name = name;
        this.price = price;
        this.ticker = ticker;
        this.status = status;
        this.supplier = supplier;
        this.attribute = attribute;
    }

    private String name;
    private double price;
    private String ticker;
    private String status;
    private String supplier;

    private List<KV> attribute;

    public List<KV> getAttribute() {
        return attribute;
    }

    public void setAttribute(List<KV> attribute) {
        this.attribute = attribute;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getTicker() {
        return ticker;
    }

    public void setTicker(String ticker) {
        this.ticker = ticker;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getSupplier() {
        return supplier;
    }

    public void setSupplier(String supplier) {
        this.supplier = supplier;
    }

}

And :
KV.java
public class KV {
    private String key;
    private String value;

    public KV(String key, String value) {
        super();
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

Would prefer answers relating to usage of annotations or changes in the rest service, and not text processing at the end.

A: Try using Attributes class in java
Instead of defining a list of object you can just define
Attribute attributes;
For more details about how Attribute class works visit https://docs.oracle.com/javase/8/docs/api/org/xml/sax/Attributes.html

A: Okay, once you get the response you are getting currently then instead of a class "public class KV {} ", you can create a Hashmap,
& key of the Hashmap can hold the index/priority etc & value can hold Nasdaq/high.
Also name the Hashmap variable as "attribute".
So that you can extract the data from API using your current structure & then can convert it to one as I said above & send the response.


text:
Q: Creating webhook for Stripe in Node Express application; issue reading request I'm unable to read the request coming from Stripe or even to log a test string when the endpoint is hit.
Stripe says that the test was successful, but I'm unable to take action on the request.
Here's what my app.js file contains.
var billingWebhook = require('./routes/billingWebhook');
// Additional code here
app.use('/billingWebhook', billingWebhook);

Here's what my routes/billingWebhook.js file contains.
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');

router.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  console.log("We got here");
  let event;
  try {
    event = JSON.parse(request.body);
  }
  catch (err) {
    response.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle the event
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object;
      handlePaymentIntentSucceeded(paymentIntent);
      break;
    case 'payment_method.attached':
      const paymentMethod = event.data.object;
      handlePaymentMethodAttached(paymentMethod);
      break;
    // ... handle other event types
    default:
      // Unexpected event type
      return response.status(400).end();
  }

  // Return a response to acknowledge receipt of the event
  response.json({received: true});
});

module.exports = router;

Below is the URL that the webhook is set up for:
https://xxxx.ngrok.io/billingWebhook/webhook
Here's what the terminal reads:

Here's what Stripe reads:


text:
Q: GCP Quota request denied for GPU (All Regions) after "Quota 'GPUS_ALL_REGIONS' exceeded. Limit: 0.0 globally." I am attempting to learn the fast.ai course. This requires a GPU and I am trying to use GCP.
I am following this guide here: https://course.fast.ai/start_gcp.html
I attempted increasing the quota for GPU (All Regions) jus like the guide, by setting a limit of 1 but I got this email from the support:
"Unfortunately, we are unable to grant you additional quota at this time. If
this is a new project please wait 48h until you resubmit the request or
until your Billing account has additional history."
I asked them if this meant they could not increase my quota for GPU (All regions) and this was the reason:
"Nevertheless, after careful evaluation on your project _______ we have determined that we are unable to grant your quota increase due to insufficient service usage history within your preferred project.
We suggest for you to make use of your current quotas and/or other resources readily available to serve your purposes for the meantime. To discuss further options on higher quota eligibility, please reach out to your Sales team [1] and provide this case ID ______  as reference. You may also direct them to reach out to us for questions or clarifications about your request."
Does anyone know how to proceed? I appreciate any advice on this. Thank you!

A: Some regions have better GPU availability than other so have a look at the documentation and try moving (or create a new) VM - you may have more luck with this.
Unfortunatelly as @John Hanley said - there's nothing we can do if you were denied increased quotas. You try requesting increased quota for one region (not all) which should (IMHO) be more feasible.


text:
Q: Get Resource From Name in External Class I have a string that identifies a resource that i want to grab.
I know about the following:
public int getIdentifier(String name, String defType, String defPackage)

However i need to use it in an external class, and it won't let me.
For example i have a string called "thefile" and i want to access R.raw.thefile
Any ideas? I'm stuck
Cheers

A: You could pass a Context to your external class. Example...
public Myclass {

    public void doSomething (Context context) {
        int resId = context.getResources().getIdentifier(...);

}

Then in your Activity...
MyClass myClass = new MyClass();
myClass.doSomething(this);


text:
Q: How to make binding in the rows and columns of a grid? I am creating an emoji box for a text box. The emoticon box contains a CollectionView with a grid and an ImageButton inside. Every time I add an item to the CollectionView list, a new ImageButton is added. The ImageButton has the grid.row and grid.column property with binding but these don't work as they should. How can I solve it? This is how I want it to look:

And this is how it look right now:

Each cell of the grid should contain an emoji.
This is my code:
CKEditor.xaml:

<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
    x:Class="Aname.Xamarin.UIControls.Controls.CKEditor"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Name="CKEditorView">

    <!--  NO ESTA LISTO TODAVIA  -->
    <AbsoluteLayout>
        <Frame
            AbsoluteLayout.LayoutBounds="0.01,.85,300,300"
            AbsoluteLayout.LayoutFlags="PositionProportional"
            CornerRadius="20"
            IsVisible="{Binding Source={x:Reference CKEditorView}, Path=BoxVisible}">

            <CollectionView ItemsSource="{Binding Source={x:Reference CKEditorView}, Path=EmojiItemSource}">
                <CollectionView.ItemTemplate>

                    <DataTemplate>

                        <Grid Padding="0">
                            <Grid.ColumnDefinitions>

                                <ColumnDefinition Width="Auto" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                                <RowDefinition Height="*" />

                            </Grid.RowDefinitions>
                            <ImageButton
                                Grid.Row="{Binding RowNumber}"
                                Grid.Column="{Binding ColumnNumber}"
                                BackgroundColor="Transparent"
                                Command="{Binding Source={x:Reference CKEditorView}, Path=BindingContext.MethodCommandEmoji}"
                                CommandParameter="{Binding EmojiMethodCommand}"
                                HeightRequest="30"
                                Source="{Binding EmojiSource}"
                                WidthRequest="30" />

                        </Grid>

                    </DataTemplate>
                </CollectionView.ItemTemplate>

            </CollectionView>

        </Frame>

        <StackLayout AbsoluteLayout.LayoutBounds="1,1,AutoSize,AutoSize" AbsoluteLayout.LayoutFlags="PositionProportional">

            <Frame
                Margin="0,0,0,2"
                Padding="0,0,0,0"
                BackgroundColor="#55FFFFFF"
                BorderColor="{Binding Source={x:Reference CKEditorView}, Path=BorderColor}"
                CornerRadius="{Binding Source={x:Reference CKEditorView}, Path=CornerRadius}"
                HasShadow="False"
                VerticalOptions="EndAndExpand">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <ImageButton
                        Grid.Column="0"
                        Margin="10,0,0,0"
                        BackgroundColor="Transparent"
                        Command="{Binding Source={x:Reference CKEditorView}, Path=BindingContext.EmojiCommand}"
                        HorizontalOptions="Start"
                        Source="{Binding Source={x:Reference CKEditorView}, Path=LeftSideIcon}"
                        WidthRequest="30" />
                    <Entry
                        Margin="45,0,0,0"
                        Placeholder="{Binding Source={x:Reference CKEditorView}, Path=Placeholder}"
                        WidthRequest="320" />

                    <ImageButton
                        Grid.Column="1"
                        Margin="0,0,10,0"
                        BackgroundColor="Transparent"
                        Command="{Binding Source={x:Reference CKEditorView}, Path=SendMsgCommand}"
                        HorizontalOptions="End"
                        Source="{Binding Source={x:Reference CKEditorView}, Path=RightSideIcon}"
                        WidthRequest="30" />

                </Grid>
            </Frame>
        </StackLayout>
    </AbsoluteLayout>

</ContentView>

Page.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="ControlsExample.EntryControlPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

    <fav:CKEditor
        BorderColor="{Binding BorderColor}"
        BoxVisible="{Binding IsVisible}"
        CornerRadius="{Binding CornerRadius}"
        EmojiItemSource="{Binding EmojiList}"
        LeftSideIcon="{Binding LeftSideIcon}"
        Placeholder="{Binding Placeholder}"
        RightSideIcon="{Binding RightSideIcon}" />

</ContentPage>

Page.xaml.cs:
public partial class Page: ContentPage
{
    public EntryControlPage()
    {
        InitializeComponent();
        BindingContext = new EmojiViewModel();

    }
}

A: In your case it would be better to use CollectionView instead of Grid
<CollectionView ItemsSource="{Binding xxx}" >

            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical" Span="4"/>
            </CollectionView.ItemsLayout>

            <CollectionView.ItemTemplate>

                <DataTemplate>

                    <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">

                        <ImageButton  Command="{Binding xxxCommand}" CommandParameter="{Binding iconSource}"  />  // iconSource here is the property of icon in list

                    </StackLayout>

                </DataTemplate>

            </CollectionView.ItemTemplate>

        </CollectionView>

In xxxCommand you will get the icon as parameter and so that you can do something like set text of Entry .


text:
Q: Rendering components in v-for issue I'm having trouble to figure out how Vue 2 is rendering components within a v-for directive.
Here is a simplified snippet of what I'm working on, a light virtual scroll table.
Codepen

                    {{ item.id }}
                    <input :value="item.name"/>

new Vue({
    el: "#app",
    data: {
        start: 0,
        count: 10,
    },
    computed: {
        items() {
            return [...Array(100).keys()]
                .map((i) => i + 1)
                .map((i) => ({
                    id: i,
                    name: `Item ${i}`,
            }))
        },
        visibleItems() {
            return this.items.slice(this.start, this.start + this.count)
        }
    },
    methods: {
        onWheel(event) {
            if (event.deltaY < 0)
                this.start = Math.max(0, this.start - 1)
            else if (event.deltaY > 0)
                this.start = Math.min(this.items.length - this.count, this.start + 1)
        },
    }
})

With this code, when I scroll up, only the top rows are rendered, leaving the others untouched, but when I scroll down, each row is re-rendered.
The node rendering can be seen in navigator console, the nodes are highlighted when they change.
The thing is, I have inputs in the second column, when one is focused and I scroll up, the focus remains, but when I scroll down, because the row is rendered, the input loose it's focus.
Why all rows are rendered instead of only the ones at the end ? How could I tell Vue to render only the new rows ?


text:
Q: Table heading and \tikzpicture cells are not vertically centered in tabularray package, and \polylongdiv is not working in a table environment \documentclass{article}
\usepackage[a4paper, portrait, margin=0.5in]{geometry}
\usepackage[table]{xcolor}
\usepackage[most]{tcolorbox}
\usepackage{amsmath}
\usepackage{tabularray}
\usepackage{polynom}

\begin{document}
\large

\newenvironment{tablemath}
    {
    \begin{array}{@{} l}
    }
    {
    \end{array}
    }

\begin{center}
\begin{tblr}{hlines, vlines,
             colspec={Q[c,m, wd=1.5cm] Q[l,m, wd=9.5cm, mode=dmath]
                      Q[r,m, wd=1cm, font=\bfseries] Q[l, m, wd=4.5cm]},
             row{1} = {font=\bfseries, mode=text},
             row{2-Z} ={rowsep=7pt},
             }
    \SetRow{gray!20} A & B & C & D \\
    Regular Row & \begin{tablemath}
                  f(3) = 100  \\
                  a = \dfrac{50}{21} - \dfrac{13}{42}b
                  \end{tablemath} & C1 & D1 \\
    Tikz Row & \begin{tikzpicture}[scale=1.5]
                      \draw[thick,<->] (-2,0) -- (2,0);
                      \draw[thick] (0,0.1) -- (0,-0.1) node[anchor=north] {$0$};
                      \draw[thick] (-1.5,0.1) -- (-1.5,-0.1) node[anchor=north] {$-1.5$};
                      \draw[thick] (-1.5,0.25) -- (0,0.25);
                      \draw[fill=white] (-1.5,0.25) circle (0.05);
                      \draw[fill=white] (0,0.25) circle (0.05);
                      \end{tikzpicture} & \textbf{C2} & D2 \\
    Long Division Row & \polylongdiv{5x^5-4x^4+25x^3-x^2+36x-2}{x^3-x^2+3x-3} & \textbf{C3} & D3 \\
\end{tblr}
\end{center}

\polylongdiv{5x^5-4x^4+25x^3-x^2+36x-2}{x^3-x^2+3x-3}

\end{document}

The above code gives the following result:

The table heading (ABCD row) and \tikzpicture (Tikz Row) cells are not vertically centered. Can anyone show me how to vertically center these rows?
The \polylongdiv command does not work in this table environment as well, but it works otherwise (as shown outside the table). Can someone also help in getting the command to work as such? (While maintaining vertical centering as well)

A: Edit:

*

*Column headers are vertical centered. To see this add to headers texts letters with descents as are g, j, p, ... If in column headers texts contain only capital letters, than you may add to row{1} specifications also  abovesep+=2pt, which will vertical centered such column headers (see MWE below).

*For image: to tikzpicture you need add option baseline.

*For \polylongdiv you need to do the following:

*

*increase column width, for example for it use X column and reduce width of last column from 4.5cm to 3.5cm,

*locally shift \polylongdiv equation to top of cell (by locally prescribed option h),

\documentclass{article}
\usepackage[a4paper, portrait, margin=0.5in]{geometry}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}

\usepackage{xcolor}
\usepackage{tabularray}
\UseTblrLibrary{amsmath}
\usepackage{polynom}

\begin{document}
\large

\newenvironment{tablemath}
    {
    \begin{array}{@{} l}
    }
    {
    \end{array}
    }

\begin{center}
\begin{tblr}{hlines, vlines,
             colspec= {Q[c,m, wd=1.5cm] X[l,m, mode=dmath]
                       Q[r,m, wd=1cm, font=\bfseries] Q[l, m, wd=3.5cm]},
             row{1} = {font=\bfseries, mode=text, bg=gray!20, abovesep+=2pt},
             row{2-Z} ={rowsep=7pt},
             }
A   & B & C & D \\
Regular Row
    &   \begin{tablemath}
            f(3) = 100  \\
            a = \dfrac{50}{21} - \dfrac{13}{42}b
        \end{tablemath}     & C1            & D1 \\
Tikz Row
    &   \begin{tikzpicture}[c/.tip = {{Circle[open, length=0 8, sep=-3.2]}},
                            font=\small, baseline=-1ex]
            \draw[thick,<->] (-2,0) -- (2,0);
            \draw[thick] (0,0.1) -- (0,-0.1) node[below] {$0$};
            \draw[thick] (-1.5,0.1) -- (-1.5,-0.1) node[below] {$-1.5$};
            \draw[thick,c-c] (-1.5,0.4) -- (0,0.4);
        \end{tikzpicture}   &  C2           & D2 \\
Long Division Row
    &   \SetCell{h}
        \polylongdiv{5x^5-4x^4+25x^3-x^2+36x-2}{x^3-x^2+3x-3}
                            &   C3          & D3 \\
\end{tblr}
\end{center}

\polylongdiv{5x^5-4x^4+25x^3-x^2+36x-2}{x^3-x^2+3x-3}

\end{document}

A: To better see the problem, I add the option draw in the node and \vrule after the tikzpicture

With outer sep=20pt

With \adjustbox{valign=m}{

Without \adjustbox{valign=m}{ with ,inner sep=0pt,yshift=-2pt

With the CODE of zarko
    \documentclass{article}
    \usepackage[a4paper, portrait, margin=0.5in]{geometry}
    \usepackage{tikz}
    \usetikzlibrary{arrows.meta}

    \usepackage{xcolor}
    \usepackage{tabularray}

    \UseTblrLibrary{amsmath}
    \usepackage{polynom}
    \usepackage{adjustbox}

    \begin{document}
    \large

    \newenvironment{tablemath}
        {
        \begin{array}{@{} l}
        }
        {
        \end{array}
        }

    \begin{center}
    \begin{tblr}{hlines, vlines,
                colspec= {Q[c,m, wd=1.5cm] X[l,m]},
                row{1} = {font=\bfseries, mode=text, bg=gray!20},
                row{2-Z} ={rowsep=7pt},
                }
    A  & B\\
    Tikz Row
    &
    %\adjustbox{valign=m}{%
    \begin{tikzpicture}[c/.tip = {{Circle[open, length=0 8, sep=-3.2]}},
                font=\small, baseline]
                %\draw(0,0)--(0,-0.7);
                \draw[thick,<->] (-2,0) -- (2,0);
                % \draw[thick] (0,0.1) -- (0,-0.1) node[below,draw,inner sep=0pt,yshift=-2pt] {$0$};
                % \draw[thick] (-1.5,0.1) -- (-1.5,-0.1) node[below,draw,inner sep=0pt,yshift=-2pt] {$-1.5$};
                \draw[thick] (0,0.1) -- (0,-0.1) node[below,inner sep=0pt,yshift=-2pt] {$0$};
                \draw[thick] (-1.5,0.1) -- (-1.5,-0.1) node[below,inner sep=0pt,yshift=-2pt] {$-1.5$};
                \draw[thick,c-c] (-1.5,0.4) -- (0,0.4);
            \end{tikzpicture}%
            \vrule
            %}%
    \end{tblr}
    \end{center}
    \end{document}


text:
Q: npm install and codepush: The uploaded package was not released because it is identical to the contents of the specified deployment's current release when i update a package with npm install only, codepush fails with message:
The uploaded package was not released because it is identical to the contents of the specified deployment's current release.
Is there a way to upload update even when there is only one package updated, right now users have to install new apk everytime package version changes?

A: Not a lot of information in this question, but this error is from the appcenter-cli, which produces this error if the target contents are the same as the source, indicating that it did not create a new codepush release.
This situation will happen all the time in a typical project. If this error is stopping your CI pipeline from completing, you can use the --disable-duplicate-release-error parameter, which simply reports a warning instead of an error.
See https://learn.microsoft.com/en-us/appcenter/distribution/codepush/cli#no-duplicate-release-error-parameter for more details.

A: I just did logout and login again! it worked


text:
Q: CSS - Media query responsive design - same height but width increases I'm working on responsive design. My goal is to make my website responsive for all sizes.
Generally, I increase the font-size of my elements as the width of the device increases.
But what if the width increases and the height remains the same? I was thinking about this scenario while creating a responsive design.
ex: 400x300 500x300 600x300
In this scenario, as width increases I increase the font-size. But the height stays the same leading to oversized elements because the height stays the same, when the font-sizes are increased.

A: So as other users have said before what you want to do first is include this meta tag in your html header:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

then you would go to your CSS file and select a certain veiw size.
@media (min-width:300px) and (max-width:400px){
     .myClass{
       height: 18em;
       font-size: 1em;
     }
    }

This @media allows the CSS to run ONLY when the viewport is within the specified range, in this case between 300px and 400px. You can treat it just as any normal CSS modification, change height, font size, color, background etc. Just remember to open and close your @media with curly brackets{} just like you would when you select an element in CSS.

A: I use this:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Hope it helps!


text:
Q: Infinite Scroll do Jetpack com problema de paginação Em minha instalação do Wordpress estou usando o plugin JETPACK e sua feature Infinite scroll.
Na pagina inicial do blog, eu estou usando a action pre_get_posts e o filter infinite_scroll_query_args para alterar a Query e fazer puxar postagens comuns e um custom post type.
O problema é que com isso a paginação do infinite scroll quebra e só contabiliza a paginação do custom post type que estou usando, porém puxando ambos os post type normalmente. Onde era para o infinite scroll ser ativado 48 vezes, ele só ativa 8 vezes.
Estou usando o seguintes códigos:

add_action( 'pre_get_posts', 'function_pre_post' );

function function_pre_post( $query ) {
    if ( $query->is_main_query() && $query->is_home() ) {
        $query->set( 'post_type', array( 'post', 'critica' ) );
    }
}

function jetpack_infinite_scroll_query_args( $args ) {
    $args['post_type']   = array( 'post', 'critica' );
    return $args;
}
add_filter( 'infinite_scroll_query_args', 'jetpack_infinite_scroll_query_args', 100 );


text:
Q: Maintain the aspect ratio of an image that is within a circle I am trying to make basic CSS challenges. In this case I have an image that I have given a circle, but I do not know what to do so that it retains its aspect ratio, does not fully cover the entire circle and is centered. This is the code I have. I want to learn a way to achieve this effect with any image of any resolution.
Desired effect:

img{
  border-radius:50%;
  width:300px;
  height:300px;
  border: solid 1px black;
}

.image_container{
  display:flex;
  justify-content:center;
  align-items:center;
}

A: Set the sizing condition on the container rather than the image.

img{
  width: 100%;
  height: auto;
}

.image_container{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 300px;
  height: 300px;
  border: 1px solid black;
  border-radius: 50%;
  overflow: hidden;
  padding: 30px;
}

A: You are using CSS on img that should be on .image-container. Then, you can set width for image enough to be centered and not override the circle, like this:
.image_container {
  width:300px;
  height:300px;
  border-radius:50%;
  border: solid 1px black;
  display:flex;
  justify-content:center;
  align-items:center;
}
img {
  width: 70%;
}

A: Maybe something like that?

* {
  box-sizing: border-box;
}

img {
  padding: 30px;
  position: absolute; top: 50%; left: 0;
  transform: translateY(-50%);
  width: 100%;
}

.image_container {
  border-radius: 50%;
  border: solid 1px black;
  overflow: hidden;
  position: relative;
  width: 300px; height: 300px;
}

A: Outline

*

*Wrap  tag in a block level tag and then wrap that tag with another block level tag:

  ...

*Assign the top ancestor tag (demo. section.frame)
position: relative;
width: 50vw;
height: 50vw;

Basic CSS positioning -- parent is relative -- child is absolute -- child references its relative parent's area for X, Y position. The value: 50vw is equivalent to 50% of viewport width. This makes the tag responsive and it will dynamically change it's dimensions and maintain aspect ratio whenever the viewport width changes.

*Assign the parent tag of  tag (demo. figure.logo)
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;

This positions it to the edges of section.frame.

*Assign the  the following:
display: block;
width: 100%;
height: 100%;
object-fit: contain;

This will position img.image to the edges of figure.logo
Added a :hover effect to show how the img tag fits within the figure and section tags. Each tag is assigned border-radius: 50% so that there are no square corners overlapping the visible border on section.frame.

.frame {
  position: relative;
  width: 50vw;
  height: 50vw;
  border: 3px solid #B9BBC0;
  border-radius: 50%;
}

.logo {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  border-radius: 50%;
}

.image {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 50%;
}

.frame:hover {
  background-color: #000;
}

References
Viewport CCS Concepts
object-fit: contain property
position property


text:
Q: How bulk update with Model to Laravel 5.4? How bulk update with Model to Laravel 5.4?
Model Brand
class Brand extends Model
{
   use BulkInsertOrUpdate;

   ...
}

My trait for this operation
Sample using -
Brand::bulkInsertOrUpdate($array, 'title');
or
Brand::bulkInsertOrUpdate($array, ['title', 'slug']);
Is there an easier way to have a bulk upload? How much I understood standard method updateOrCreate works only with one tuple

A: You can try to get all images in Array once you get it just use for or foreach loop for insert/update Array Images.


text:
Q: PHP cookie impossible to read issue My PHP is unable to read a cookie like this:
1010081-COP-9-20-20110606172032

echo $_COOKIE["SubmCookie"];

It just returns empty...
How is that possible?
This is the way how I set the Cookie:
setcookie("SubmCookie",$refNumb, time()+3600*24);

A: Try:
setcookie("SubmCookie",$refNumb, time()+3600*24,'/');


text:
Q: React Router V4 isnt working properly I am making a web application in which iI want to display the details of the user when clicked on them in the same page using routers.
here is my index.js page
window.React = React;

render(

    <Menu/><MainMenu/><App/>

, document.getElementById('react-container'))

This is my App.js Page
class App extends Component {
  render () {
    return (

            <BrowserRouter>
                   <Side>
                    <Route path="/" component={Side}>

                    <Route exact path="/" component={Home}/>
                    <Route path="/user-lists" component={Table}>
                    </Route>

                    </Route>

</Side>

            </BrowserRouter>

    )
  }
}

export default App

this is my users page
export default class Table extends React.Component {
    constructor(props) {
        super(props);

        this.columns = [
            {
                name: "ID",
                key: "id"
            }, {
                name: "Name",
                key: "name"
            }, {
                name: "Username",
                key: "username"
            }, {
                name: "Email",
                key: "email"
            }, {
                name: "Website",
                key: "website"
            }
        ];

        this.maxItems = 5;
    };

    state = {
        pgNo: 0,
        table: [],
        isFetching: true,
        url:"https://jsonplaceholder.typicode.com/users/"

    };
    componentDidMount() {
        fetch("https://jsonplaceholder.typicode.com/users")
            .then(response => response.json())
            .then(res => {
                this.setState({table: res, isFetching: false});

            });

        }

    render() {
        return this.state.isFetching
            ? (

            )
            : (

                <MyTable pgNo ={this.state.pgNo}
                         maxItems = {this.maxItems}
                         columns={this.columns}
                         data={this.state.table}
                         url={this.state.url}/>
            )
    }

}

Here is my Sidebar.js page
export const Side = () =>

        Dashboard

                Irtaza

<Link  to='/'>Home</Link>

<Link  to='/posts'><Fausers /> Posts  </Link>

<Link  to='/user-lists'><Fafile/> Users </Link>

<Link  to='*'><Fatimes/> Whoops 404 </Link>

And finally this is my table.js page
export default class MyTable extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            currentPage: this.props.pgNo,
           details : [],
    id: null
        }
        this.MaxPages = 0;

    }

    PrevButton() {

        if (this.state.currentPage === 0) {
            return (null);
        } else {
            return (
                <button
                    type="button"
                    key={this.state.currentPage}
                    style={{
                    float: "left"
                }}
                    onClick=
                    { () => { this.setState({ currentPage: this.state.currentPage - 1 }) } }>
                    Previous Page
                </button>
            );
        }

    }

    NextButton() {
        if (this.state.currentPage === this.MaxPages - 1) {
            return (null);
        } else {
            return (

                <button
                    style={{
                    float: "right"
                }}
                    key={this.props.pgNo}
                    onClick={() => {
                    this.setState({
                        currentPage: this.state.currentPage + 1
                    })
                }}>
                    Next Page
                </button >
            );
        }
    }

    createTable = () => {

        let tableHeader =

                {this.props.columns.map(column => {
                        return
                            {column.name}

                    })}

;
        this.state.number = this.state.number + 1;
        let tableRows = [];
        for (let i = this.state.currentPage * this.props.maxItems; (i < (this.state.currentPage + 1) * this.props.maxItems) && (i <= this.props.data.length); i++) {

            this.state.id= i + 1;

         let row = <Link to={{
            pathname: `/user-lists/details(/${i+1})`

          }}>

                {this
                    .props
                    .columns
                    .map(column => {
                        this.state.id= i + 1;
                        return (

                                {this.props.data[i][column.key]}

                        )
                    })}

</Link>
            tableRows.push(row)
            }
        for (let i = 0; i <= Math.ceil(this.props.data.length / this.props.maxItems); i++) {
            this.MaxPages = i;

        }

        let tableBody =
{tableRows}
;
        return
{tableHeader}{tableBody}

;
    }

    render() {

        return (

                        {this.createTable()}
                        {this.PrevButton()}
                        {this.NextButton()}

        )
    }

}

Every time I click on a Link in sidebar.js
it redirects me to the new link but does not render anything also it gives me an error "Failed to load resource: the server responded with a status of 404 (Not Found)"
I dont know what i am doing wrong. Feel free to point out any mistakes you see.

A: Firstly, In order for Link to work correctly, it needs to Receive the Router Props but since its rendered as a Route, it doesn't receive any props.
Secondly all routes are defined as children to Side, but they are never rendered in the Side component
You would write your components like
App.js
class App extends Component {
  render () {
    return (

            <BrowserRouter>

                <Route component={Side}>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/user-lists" component={Table}>
                    <Route path="*" component={NotFound}/>
                </Switch>

            </BrowserRouter>

    )
  }
}

export default App

and Side.js
export const Side = (props) => (

            Dashboard

                    Irtaza

<Link  to='/'>Home</Link>

<Link  to='/posts'><Fausers /> Posts  </Link>

<Link  to='/user-lists'><Fafile/> Users </Link>

<Link  to='*'><Fatimes/> Whoops 404 </Link>

)


text:
Q: Matching entities with ManyToMany relationship with any element of a Set In JPA/JQL, I've as input a Set<Tag> and I want to find entities that are associated to at least one Tag in my input Set (:tags).
The Tagged entity has a property tags
@ManyToMany
private Set<Tag> tags;

How the query should look like? I've tried
SELECT t FROM Tagged t WHERE t.tags = ANY(:tags)
but it's not correct. Does anyone know how the correct query should be?
Example: if a Tagged Entity has Tags ("one", "two", "tree") and my :tags input parameter is a Set of Tags ("three", "four"), I expect a match because "three" is in common.

A: I don't believe ANY(subquery) is what you're looking for. I would use an inner join instead. Something like this:
SELECT DISTINCT t FROM Tagged t JOIN t.tags tag WHERE tag IN :tags


text:
Q: Getting problem in accessing web cam I have written code in Java to access web cam,and to save image...
I am getting following exceptions :
Exception in thread "main" java.lang.NullPointerException
 at SwingCapture.(SwingCapture.java:40)
 at SwingCapture.main(SwingCapture.java:66)
how to remove this exceptions.
here is the code:
import javax.swing.*;

import javax.swing.event.;
import java.io.;
import javax.media.;
import javax.media.format.;
import javax.media.util.;
import javax.media.control.;
import javax.media.protocol.;
import java.util.;
import java.awt.;
import java.awt.image.;
import java.awt.event.;
import com.sun.image.codec.jpeg.;
public class SwingCapture extends Panel implements ActionListener
{
  public static Player player = null;
  public CaptureDeviceInfo di = null;
  public MediaLocator ml = null;
  public JButton capture = null;
  public Buffer buf = null;
  public Image img = null;
  public VideoFormat vf = null;
  public BufferToImage btoi = null;
  public ImagePanel imgpanel = null;
public SwingCapture()
  {
    setLayout(new BorderLayout());
    setSize(320,550);
imgpanel = new ImagePanel();
capture = new JButton("Capture");
capture.addActionListener(this);

String str1 = "vfw:iNTEX IT-308 WC:0";
String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
di = CaptureDeviceManager.getDevice(str2);
ml = di.getLocator();

try
{
  player = Manager.createRealizedPlayer(ml);
  player.start();
  Component comp;

  if ((comp = player.getVisualComponent()) != null)
  {
    add(comp,BorderLayout.NORTH);
  }
  add(capture,BorderLayout.CENTER);
  add(imgpanel,BorderLayout.SOUTH);
}
catch (Exception e)
{
  e.printStackTrace();
}

}
public static void main(String[] args)
  {
    Frame f = new Frame("SwingCapture");
    SwingCapture cf = new SwingCapture();
f.addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent e) {
  playerclose();
  System.exit(0);}});

f.add("Center",cf);
f.pack();
f.setSize(new Dimension(320,550));
f.setVisible(true);

}
public static void playerclose()
  {
    player.close();
    player.deallocate();
  }
public void actionPerformed(ActionEvent e)
  {
    JComponent c = (JComponent) e.getSource();
if (c == capture)
{
  // Grab a frame
  FrameGrabbingControl fgc = (FrameGrabbingControl)
  player.getControl("javax.media.control.FrameGrabbingControl");
  buf = fgc.grabFrame();

  // Convert it to an image
  btoi = new BufferToImage((VideoFormat)buf.getFormat());
  img = btoi.createImage(buf);

  // show the image
  imgpanel.setImage(img);

  // save image
  saveJPG(img,"\test.jpg");
}

}
class ImagePanel extends Panel
  {
    public Image myimg = null;
public ImagePanel()
{
  setLayout(null);
  setSize(320,240);
}

public void setImage(Image img)
{
  this.myimg = img;
  repaint();
}

public void paint(Graphics g)
{
  if (myimg != null)
  {
    g.drawImage(myimg, 0, 0, this);
  }
}

}
public static void saveJPG(Image img, String s)
  {
    BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage(img, null, null);
FileOutputStream out = null;
try
{
  out = new FileOutputStream(s);
}
catch (java.io.FileNotFoundException io)
{
  System.out.println("File Not Found");
}

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
param.setQuality(0.5f,false);
encoder.setJPEGEncodeParam(param);

try
{
  encoder.encode(bi);
  out.close();
}
catch (java.io.IOException io)
{
  System.out.println("IOException");
}

}
}

A: Your code is somewhat messy, but did you make sure to specify that your Frame had a borderlayout set? I've been through this issue many times. Try explicitly stating this.Layout = new BorderLayout();. If the problem persists let me know and ill try to help.

A: If you are using built in web cam most of the time it shows errors. You can try with external web cam.

A: I have ENTER Web Camera Model No: E-1.3MPIR what should be the argument for CaptureDeviceManager.getDevice()


text:
Q: Plotly: how to stretch line over the graphics end? I need to extend line at the end of graphics area, that is made with 2 DataFrame points with DatetimeIndex as on screen below:

How to do that? With math I would calculate where line exactly hits x axis, buy it's impossible, because you can not measure distance between Jan 4 and Jan 5, because it's 1 day.
import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({
    'score':[30, 60, 38, 10, 50, 70, 40],
    'date':['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07'],
})
df['date'] = pd.to_datetime(df['date'])

fig = go.Figure()
fig.add_shape(
    dict(
        type="line",
        x0=df.iloc[1]['date'],
        y0=df.iloc[1]['score'],
        x1=df.iloc[2]['date'],
        y1=df.iloc[2]['score'],
        line=dict(
        color="RoyalBlue",
        width=3
    )
))

fig.add_trace(
    go.Scatter(
        mode='markers',
        x=df['date'],
        y=df['score'],
        marker=dict(
            color='LightSkyBlue',
            size=12,
            line=dict(
                color='MediumPurple',
                width=4
            )
        ),
    )
)

fig.update_xaxes(tickmode='auto',)
fig.show()

A: As long as you convert days in minutes it shouldn't be a big deal. Here I already calculated the date for you

import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({
    'score':[30, 60, 38, 10, 50, 70, 40],
    'date':['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07'],
})
df['date'] = pd.to_datetime(df['date'])

fig = go.Figure()
fig.add_shape(
    dict(
        type="line",
        x0=df.iloc[1]['date'],
        y0=df.iloc[1]['score'],
        x1=df.iloc[2]['date'],
        y1=df.iloc[2]['score'],
        line=dict(
        color="RoyalBlue",
        width=3
    )
))
fig.add_shape(
    dict(
        type="line",
        x0=df.iloc[2]['date'],
        y0=df.iloc[2]['score'],
        x1=pd.Timestamp(2000,1,4,17,16),
        y1=0,
        line=dict(
        color="red",
        dash="dot",
        width=3
    )
))

fig.add_trace(
    go.Scatter(
        mode='markers',
        x=df['date'],
        y=df['score'],
        marker=dict(
            color='LightSkyBlue',
            size=12,
            line=dict(
                color='MediumPurple',
                width=4
            )
        ),
    )
)

fig.update_xaxes(tickmode='auto',)
fig.show()


text:
Q: As part of "nuking it from orbit", is it safe to reinstall the OS using Recovery? Context: I've erased my hard drive and had OS El Capitan reinstalled via a bootable drive from a Genius Bar many times leading up to me asking this question. After going through the process of erasing + reinstalling + setting up preferences/calendars + changing passwords etc, the day after there have always been little things that were noticeable enough to arouse suspicion regarding a RAT/trojan on my Macbook (minor changes to iCal entries I definitely didn't make etc).
Recently, I tried a different route: I erased the hard drive and reinstalled the OS via Recovery using an Apple store's wifi. But even after doing this, I noticed the day after of setting up my Macbook as new again that one of my iCal entries were edited that I didn't make...
However, I read somewhere that it's best to reinstall the OS from a non-recovery partition source because if there is/was a RAT/trojan on my Macbook, said RAT/trojan could modify some files in the recovery partition without my knowledge thus leading me to unwittingly install a backdoored OS. Does this seem plausible? Should I once again try and erase/reinstall the OS from a bootable drive at a Genius Bar?

A: You are correct - a suitably advanced attacker could technically rewrite the OS on the recovery HD to point it to a bad source when you reinstall the OS.
Better would to be use internet recovery since that would require even more advanced work to compromise the firmware on the Mac.
Best would be to bring a bootable installer from a machine you have more confidence hasn't been comnptromised.
In 98% of the time - all of the above steps to erase the hard drive and reinstall the OS are going to be equally effective, but there are increased levels of safety to be had than just using the self-contained recovery HD.


text:
Q: Placing button on top of asp.net image control Is it possible to place a button on top of an Image control in a custom control ?

A: You can take Image button
like this
<asp:ImageButton runat="server" ID="imgButton" ImageUrl="~/images/asc.gif" />

set your image url , this image button work same as normal asp button,
You can also get server side Click event of this button.


text:
Q: Apache Camel Issue having routingSlip after a filter I am in the process of implementing a Camel route in which I need to put a filter before redirecting the message processing to an end point or another depending of a routing slip header. Something like below:
        from("direct:a")
            .routeId("a")
            .choice()
                .when(header("foo"))
                    .filter(body().isNotNull())
                    .routingSlip(header("my-slip"))
                .endChoice()
                .otherwise()
                    .log("header 'foo' was false")
                .endChoice()
            .end();

When trying to run the application I am getting the following exception:
java.lang.ClassCastException: class org.apache.camel.model.FilterDefinition cannot be cast to class org.apache.camel.model.ChoiceDefinition

Any explanation why this is not a legal construct and how should I code my route to achieve what I want. From my own observations it is the choice() construct that is causing this. Adding a routingSlip construct after a filter works just fine if the choice is not there.
Thank you in advance for your inputs.

A: Try adding .end() after .routingSlip(header("my-slip")) to close the filter definition.
 from("direct:a")
.routeId("a")
.choice()
    .when(header("foo"))
        .filter(body().isNotNull())
            .routingSlip(header("my-slip"))
        .end()
    .endChoice()
    .otherwise()
        .log("header 'foo' was false")
    .endChoice()
.end();

A: Just remove the filter. Put all the conditions in the whenbranch.
For example, here I am using the Simple language:
from("direct:a")
.routeId("a")
.choice()
    .when(simple("${header.foo} !=null and ${body}!=null))
        .routingSlip(header("my-slip"))
    .endChoice()
    .otherwise()
        .log("header 'foo' was false")
    .endChoice()
.end();

filter and choice are similar. You can use filter instead of a single if (or also to filter items from a list); use choice instead in case of an if .. else.


text:
Q: MassTransit StateMachineSagaTestHarness - double message consumption I have a problem with InMemoryTestHarness and state machine saga. It looks like each published message are consumed twice by saga. If message are sent (not published) the problem does not occur. The problem started when I changed CorrelationId to custom field - ProcessId. Below simplified example exposing the problem.
Saga definition:
    public class MySaga : MassTransitStateMachine<MySagaState>
    {
        public State InProgress { get; private set; }

        public Event<StartProcess> StartProcess { get; private set; }
        public Event<ProcessStageFinished> StageFinished { get; private set; }
        public Event<ProcessFinished> ProcessFinished { get; private set; }

        public MySaga()
        {
            InstanceState(x => x.CurrentState);

            Event(() => StartProcess, e => e
                .CorrelateBy(i => i.ProcessId, x => x.Message.ProcessId)
                .SelectId(x => NewId.NextGuid()));

            Event(() => StageFinished, e => e
                .CorrelateBy(i => i.ProcessId, x => x.Message.ProcessId)
                .SelectId(x => NewId.NextGuid()));

            Event(() => ProcessFinished, e => e
                .CorrelateBy(i => i.ProcessId, x => x.Message.ProcessId)
                .SelectId(x => NewId.NextGuid()));

            Initially(
                When(StartProcess)
                    .Then(x => x.Instance.ProcessId = x.Data.ProcessId)
                    .TransitionTo(InProgress)
                );

            During(InProgress,
                When(StageFinished)
                    .Then(x => x.Instance.Stage++)
                );

            During(InProgress,
                When(ProcessFinished)
                    .Finalize()
                );
        }
    }

    public class MySagaState : SagaStateMachineInstance, ISagaVersion
    {
        public Guid CorrelationId { get; set; }
        public int Version { get; set; }
        public string ProcessId { get; set; }
        public string CurrentState { get; set; }
        public int Stage { get; set; }
    }

    public record StartProcess(Guid CorrelationId, string ProcessId) : CorrelatedBy<Guid>
    {
    }

    public record ProcessStageFinished(Guid CorrelationId, string ProcessId) : CorrelatedBy<Guid>
    {
    }

    public record ProcessFinished(Guid CorrelationId, string ProcessId) : CorrelatedBy<Guid>
    {
    }

And the xUnit test:
    public class MySagaTests
    {
        InMemoryTestHarness Harness { get; }
        IStateMachineSagaTestHarness<MySagaState, MySaga> SagaHarness { get; }

        public MySagaTests()
        {
            var services = new ServiceCollection()
                .AddMassTransitInMemoryTestHarness(config =>
                {
                    config.AddSagaStateMachine<MySaga, MySagaState>(sagaConfig =>
                        {
                            sagaConfig.UseConcurrentMessageLimit(1);
                            sagaConfig.UseInMemoryOutbox();
                        })
                       .InMemoryRepository();

                    config.AddSagaStateMachineTestHarness<MySaga, MySagaState>();
                });

            var serviceProvider = services.BuildServiceProvider(true);

            Harness = serviceProvider.GetRequiredService<InMemoryTestHarness>();
            Harness.OnConfigureInMemoryReceiveEndpoint += config =>
            {
                config.ConfigureSagas(serviceProvider.GetRequiredService<IBusRegistrationContext>());
            };

            SagaHarness = serviceProvider.GetRequiredService<IStateMachineSagaTestHarness<MySagaState, MySaga>>();
        }

        [Fact]
        public async Task TestMySaga()
        {
            string processId = "newProcessId";
            var correlationId = NewId.NextGuid();

            await Harness.Start();

            try
            {
                await Harness.Bus.Publish(new StartProcess(correlationId, processId));

                Assert.True(await Harness.Published.Any<StartProcess>());
                Assert.True(await Harness.Consumed.Any<StartProcess>());
                Assert.True(await SagaHarness.Consumed.Any<StartProcess>());
                Assert.Equal(1, SagaHarness.Sagas.Count());  // HERE should be only one saga created

                Assert.True(await SagaHarness.Created.Any(s => s.ProcessId == processId && s.CurrentState == "InProgress"));

                await Harness.Bus.Publish(new ProcessStageFinished(correlationId, processId));

                Assert.True(await Harness.Published.Any<ProcessStageFinished>());
                Assert.True(await Harness.Consumed.Any<ProcessStageFinished>());
                Assert.True(await SagaHarness.Consumed.Any<ProcessStageFinished>());
                var saga = SagaHarness.Sagas.Select(s => s.ProcessId == processId).FirstOrDefault()?.Saga;
                Assert.NotNull(saga);
                Assert.Equal(1, saga.Stage); // HERE stage should by 1

                await Harness.Bus.Publish(new ProcessFinished(correlationId, processId));

                Assert.True(await Harness.Published.Any<ProcessFinished>());
                Assert.True(await Harness.Consumed.Any<ProcessFinished>());
                Assert.True(await SagaHarness.Consumed.Any<ProcessFinished>());

                Assert.True(await SagaHarness.Sagas.Any(s => s.ProcessId == processId && s.CurrentState == "Final"));
            }
            finally
            {
                await Harness.Stop();
            }

        }
    }

I have tried it on simple in-memory bus configuration and on RabbitMQ. On both configuration it works fine. Messages are consumed twice only within InMemoryTestHarness.
Do you have any suggestions what should be fixed? At first glance it looks like a wrong behavior.

A: Yeah, remove this line – you're configuring the saga on two separate endpoints.
Harness.OnConfigureInMemoryReceiveEndpoint += config =>
{
    config.ConfigureSagas(serviceProvider.GetRequiredService<IBusRegistrationContext>());
};

A: After [@Chris Patterson] response I've reorganized the test. Maybe it will help somebody, reorganized test below:
    public class MySagaTests
    {
        InMemoryTestHarness Harness { get; }
        IStateMachineSagaTestHarness<MySagaState, MySaga> SagaHarness { get; }

        public MySagaTests()
        {
            var services = new ServiceCollection()
                .AddMassTransitInMemoryTestHarness(config =>
                {
                    config.AddSagaStateMachine<MySaga, MySagaState>(sagaConfig =>
                        {
                            sagaConfig.UseConcurrentMessageLimit(1);
                            sagaConfig.UseInMemoryOutbox();
                        })
                       .InMemoryRepository();

                    config.AddSagaStateMachineTestHarness<MySaga, MySagaState>();
                });

            var serviceProvider = services.BuildServiceProvider(true);

            Harness = serviceProvider.GetRequiredService<InMemoryTestHarness>();

            SagaHarness = serviceProvider.GetRequiredService<IStateMachineSagaTestHarness<MySagaState, MySaga>>();
        }

        [Fact]
        public async Task TestMySaga()
        {
            string processId = "newProcessId";
            var correlationId = NewId.NextGuid();

            await Harness.Start();

            try
            {
                await Harness.Bus.Publish(new StartProcess(correlationId, processId));

                var sagaExists = (await SagaHarness.Exists(s => s.ProcessId == processId, x => x.InProgress)).Any();
                Assert.True(sagaExists, "Saga not exists");

                await Harness.Bus.Publish(new ProcessStageFinished(correlationId, processId));

                sagaExists = (await SagaHarness.Exists(s => s.ProcessId == processId && s.Stage == 1, x => x.InProgress)).Any();
                Assert.True(sagaExists, "Saga not exists");

                await Harness.Bus.Publish(new ProcessFinished(correlationId, processId));

                sagaExists = (await SagaHarness.Exists(s => s.ProcessId == processId, x => x.Final)).Any();
                Assert.True(sagaExists, "Saga not exists");
            }
            finally
            {
                await Harness.Stop();
            }
        }
    }


text:
Q: Laravel 8 - use route parameter inside the view Taking the following code as an example, how can I use the param paramenter inside the index view?
Route::get('foo/{param}', [FooController::class, 'index']);

A: Have you index method of the controller take a parameter, $param, and pass it to your view:
public function index($param)
{
    return view('index', ['param' => $param]);
}

Then in the Blade view:
{{ $param }}

Or, you could get the route parameter from the request directly in the view if needed:
{{ request()->route('param') }}


text:
Q: Hibernate - Column of Embedded missing in Audit Table I am using hibernate version 5.3.18.Final but I face an issue with the Embedded object with the Audit table
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [createDate] in table [audit.Address_AUD]

here is the full code
@Audited
@Entity
public class Address {
    @Id
    @Column(name = "address_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Address_generator")
    @SequenceGenerator(name = "Address_generator", initialValue = 1, allocationSize = 1, sequenceName = "address_sequence")
    private Long addressId;

    @Column(name = "address")
    private String address;

    @Version
    @Column(nullable = false)
    private Long version;

    @ManyToMany(mappedBy="addresses")
    private List<AddressGroup> addressGroups;

    public Long getAddressId() {
        return addressId;
    }

    public void setAddressId(Long addressId) {
        this.addressId = addressId;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Embedded
    private TemporalEntity temporal;

    public TemporalEntity getTemporal() { return temporal; }

    public void setTemporal(TemporalEntity temporal) { this.temporal = temporal; }

    public List<AddressGroup> getAddressGroups() {
        return addressGroups;
    }

    public void setAddressGroups(List<AddressGroup> addressGroups) {
        this.addressGroups = addressGroups;
    }

}

@Embeddable
public class TemporalEntity {

    @Column(updatable = false)
    private DateTime createDate;

    @Column
    private DateTime lastModifiedDate;

    @ManyToOne
    @JoinColumn(name = "created_by_id", updatable = false)
    private AdminUser createdBy;

    @ManyToOne
    @JoinColumn(name = "last_modified_by_id")
    private AdminUser lastModifiedBy;

    @Column(nullable = false, columnDefinition = "boolean not null default false")
    private boolean deleted = false;

    public DateTime getCreateDate() {
        return createDate;
    }

    public void setCreateDate(DateTime createDate) {
        if (createDate == null) {
            //ignore attempts to clear this field
            return;
            //throw new IllegalStateException("Null create date not allowed");
        }
        this.createDate = createDate;
    }

    public DateTime getLastModifiedDate() {
        return lastModifiedDate;
    }

    public void setLastModifiedDate(DateTime lastModifiedDate) {
        if (lastModifiedDate == null) {
            //ignore attempts to clear this field
            return;
            //throw new IllegalStateException("Null last modified date not allowed");
        }
        this.lastModifiedDate = lastModifiedDate;
    }

    public AdminUser getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(AdminUser createdBy) {
        if (createdBy == null) {
            //ignore attempts to clear this field
            return;
            //throw new IllegalStateException("Null created by not allowed");
        }
        this.createdBy = createdBy;
    }

    public AdminUser getLastModifiedBy() {
        return lastModifiedBy;
    }

    public void setLastModifiedBy(AdminUser lastModifiedBy) {
        if (lastModifiedBy == null) {
            //ignore attempts to clear this field
            return;
            //throw new IllegalStateException("Null lastModifiedBy not allowed");
        }
        this.lastModifiedBy = lastModifiedBy;
    }

    public boolean isDeleted() {
        return deleted;
    }

    public void setDeleted(boolean deleted) {
        this.deleted = deleted;
    }

}

the error log
18:58:48,265 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 28) MSC000001: Failed to start service jboss.persistenceunit."bds-core-1.0-SNAPSHOT.war#com.berwick.dal": org.jboss.msc.service.StartException in service jboss.persistenceunit."bds-core-1.0-SNAPSHOT.war#com.berwick.dal": javax.persistence.PersistenceException: [PersistenceUnit: com.berwick.dal] Unable to build Hibernate SessionFactory
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:198) [wildfly-jpa-21.0.0.Final.jar:21.0.0.Final]
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:128) [wildfly-jpa-21.0.0.Final.jar:21.0.0.Final]
    at java.security.AccessController.doPrivileged(Native Method) [rt.jar:1.8.0_221]
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:659) [wildfly-elytron-security-manager-1.13.1.Final.jar:1.13.1.Final]
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:213) [wildfly-jpa-21.0.0.Final.jar:21.0.0.Final]
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35) [jboss-threads-2.1.1.Final.jar:2.1.1.Final]
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.lang.Thread.run(Thread.java:748) [rt.jar:1.8.0_221]
    at org.jboss.threads.JBossThread.run(JBossThread.java:513) [jboss-threads-2.1.1.Final.jar:2.1.1.Final]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: com.berwick.dal] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1327) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1253) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:170) [wildfly-jpa-21.0.0.Final.jar:21.0.0.Final]
    ... 10 more
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [createDate] in table [audit.Address_AUD]
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateTable(AbstractSchemaValidator.java:136) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    at org.hibernate.tool.schema.internal.GroupedSchemaValidatorImpl.validateTables(GroupedSchemaValidatorImpl.java:42) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.performValidation(AbstractSchemaValidator.java:89) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:68) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:191) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:310) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1250) [hibernate-core-5.3.18.Final.jar:5.3.18.Final]
    ... 12 more

18:58:48,277 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 1) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "bds-core-1.0-SNAPSHOT.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"bds-core-1.0-SNAPSHOT.war#com.berwick.dal\"" => "javax.persistence.PersistenceException: [PersistenceUnit: com.berwick.dal] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: com.berwick.dal] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [createDate] in table [audit.Address_AUD]"}}
18:58:48,280 ERROR [org.jboss.as.server] (management-handler-thread - 1) WFLYSRV0021: Deploy of deployment "bds-core-1.0-SNAPSHOT.war" was rolled back with the following failure message:
{"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"bds-core-1.0-SNAPSHOT.war#com.berwick.dal\"" => "javax.persistence.PersistenceException: [PersistenceUnit: com.berwick.dal] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: com.berwick.dal] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [createDate] in table [audit.Address_AUD]"}}

A: simply I need to add name to column matched field name in my case its name="create_date"
@Embeddable
public class TemporalEntity {

    @Column(name="create_date",updatable = false)
    private DateTime createDate;


text:
Q: Twilio TwiML: Don't record after client hangs up I have my twiml as such:
<Response>
    <Dial timeout="12">
    <Client>Robbie</Client>
    </Dial>
    <Say>
    The person you are trying to reach is currently unavailable. Please leave a message at the beep.
    </Say>
    <Record action="/voicemail/fdasjhklewu/" maxLength="90" method="GET" timeout="7"/>
    </Response>

Here twilio tries to reach the client to connect and incoming call and then if there's no response, it goes to voicemail.
However, if I answer and then hangup, it still goes to voicemail. How can I hangup and not goto voicemail?

A: Twilio developer evangelist here.
You can actually achieve what you want, but in a slightly different way.
If you pass an action to your <Dial> like this:
<Response>
  <Dial action='/after_dial'>
    <Client>Robbie</Client>
  </Dial>
</Response>

Then once the call completes, you'll need something to deal with a callback to that action. Here is an example in Ruby with Sinatra (though you can do this with whatever language you want):
post '/after_dial' do
  content_type 'text/xml'
  if ['busy', 'no-answer', 'failed', 'canceled'].include?(params['DialCallStatus'])
    "<Say>
       The person you are trying to reach is currently unavailable. Please leave a message at the beep.
     </Say>
     <Record action="/voicemail/fdasjhklewu/" maxLength="90" method="GET" timeout="7"/>"
  else
    "<Hangup/>"
  end
end

The DialCallStatus parameter tells you what happened to the call, so if it was busy, missed, canceled or failed for any reason you can go to voicemail, otherwise the call was completed and you can just hangup.
Let me know if this helps at all.

A: I don't think there is a way to do what you want.
Twilm is executed in the order it comes in.
What you would want to do is specify a call back page for the dial.
Then if it was completed you would want to hangup
If it was not completed you would then do the voice mail.
He is the example from the website. Remember you will use the same logic if it is a client or a phone
https://www.twilio.com/docs/howto/voicemail


text:
Q: Reading a crosstabs I am confused and struggling to read this simple crosstabs.

I am trying to create a profile of downloaders. One of the demographics I am looking at is age. Should I be looking at the percentage within Age or percentage within Type of downloader?
For example, Mixed downloaders are most likely to be 18-21 (50%)? Or should it be they are most likely to be 18-21 (68.4%)??
Could someone help explain please
Thanks

A: Since we generally treat age as a stratifying variable, we would look at age standardized proportions. That's because, comparing like-to-like in usage habits, we expect great variation in usage between age groups. Indeed we see that. The "% within age" proportions are the values you're after.


text:
Q: Searching for meta posts on the Stack Exchange network I want to do a network-wide search that covers all meta sites on Stack Exchange.
Specifically, I'm looking to find site-specific announcement posts so I can research which communities have site-specific formatting enabled.
I've tried using the Network Wide search, but it seems that is:meta isn't a valid search option.
How can I search for meta posts across the Stack Exchange network?
Preferably, I would like to sort the results by votes, as feature announcements like these tend to be highly voted.

A: We use Google custom search on the network-wide search page, not an in-house search engine. The benefit of this is that the custom search is already scoped to only our network sites.
You can still further scope it using Google's site: search operator, which happens to support wildcards. So something like this would search for a particular term on all sites that have meta in their URL:
site:meta.* MathJax


text:
Q: IBM worklight 7.1 change push notification icon I'm confused right now, I want to change push notification icon (android) and I've change push.png in all res-drawable folder and add this line in AndroidManifest.xml:
< meta-data android:name="com.parse.push.notification_icon" android:resource="@drawable/push" >
But no success. Still showing default worklight push notification icon
(default push notification icon).
Any help here?
FYI I'm using IBM mobile first platform 7.1

A: As Vivin suggested in the comments, you should not update AndroidManifest.xml with any new line.
You need only to replace the existing push.png with your own image, also named push.png. That is all.


text:
Q: Combine two tables in R I have 2 tables and need to combine them using R as follows:-
Table 1

id
A
B
C
D

Table 2

group class
1     X
2     Y

I need a combined table like this:-
id group class
A  1     X
B  1     X
C  1     X
D  1     X
A  2     Y
B  2     Y
C  2     Y
D  2     Y

I tried many types of merges (like inner, left, full join etc) by creating dummy columns in the tables, but couldn't get the desired output. Any help will be of great help

A: You are looking for a cross join between the two tables:
t1 <- data.frame(id=c("A", "B", "C", "D"))
t2 <- data.frame(group=c(1, 2), class=c("X", "Y"))

merge(t1, t2, all=TRUE)

   id group class
1  A     1     X
2  B     1     X
3  C     1     X
4  D     1     X
5  A     2     Y
6  B     2     Y
7  C     2     Y
8  D     2     Y

Demo


text:
Q: Trying to understand bash function return values I have looked at the bash function return values and it seems I still don't understand how that works.
I setup 3 function each supposedly returning a RET_VAL return value.
I assume func_1 returns either a 1 or 0 based on the if statement
I assume func_2 return either a 1 or a 0 based on the if statement
I assume func_3 should either print a 1 or a 0 based on the return value of func_2
func_1() {
  RET_VAL=0
  if [ -d /tmp/dir ]; then
    echo "Dir exists"
    RET_VAL=0
  else
    echo "Dir doesn't exist"
    RET_VAL=1
  fi
  return ${RET_VAL}
}

func_2() {
  RET_VAL=0
  if func_1; then
    if [ -f /tmp/file_1]; then
      echo "File exists"
    else
      echo "File doesn't exist"
      RET_VAL=1
    fi
  else
    RET_VAL=1
  fi
  return ${RET_VAL}
}

func_3() {
  if func_2; then
    echo "Dir and File do exist"
  else
    echo "Dir and file do not exist"
  fi
}

Are my assumptions correct or is each function returning what it executed last, like the echo statement?
If so, how could I assure that the functions return a 1 or a 0 value?
Cheers,
Roland

A: func_3 will not print the return value of func_2. The if statement will use the exit status of func_2 to determine which branch to take. Every command has an exit status, so in the absence of an explicit return command, the exit status of the last command to execute will be the exit status of a function. In the case of func_3, the exit status will be the exit status of whichever echo command executes (which is virtually always 0, absent any I/O errors).


text:
Q: Rolling sums in SQL? I need to find out how many times an event has occurred in the past x-day, rolling interval interval. In a 2-day case, this can be accomplished without too much of a headache.
WITH lagged AS
(SELECT
   IF(attr IS NOT NULL, 1,0) AS is_curr
   IF(LAG(attr, 1) IS NOT NULL, 1,0) AS is_prev
FROM tab)
SELECT
   SUM(is_curr, is_prev) AS occurences_in_x_days
FROM lagged

However, if I want to change x to something like 7, 30, or 90, this design comes impractical.
Is there a more scalable option?

A: count(attr) over(date rows between x(Enter no of days here) preceding and current row) as rolling_sum


text:
Q: sacar si el usuario existe o no en la base de datos Estoy intentando hacer esta validación en mi servidor pero no me sale cuando le paso un valor string al método que seria un nombre de usuario, debe pasar por los métodos y ver si existe en la base de datos que no te deje salir y si no existe que puedas continuar.
Tengo en la capa SERVICE esto:
 public ReplyBean getexistsusername() throws Exception {
    /*
    //recuperar el username y ver si existe
    String username = ParameterCook.prepareUsername(oRequest);

    //mirar en la bd si existe username
     Connection oConnection = null;
        ConnectionInterface oDataConnectionSource = null;
    return new ReplyBean(200, JsonMessage.getJsonMsg(200, "true"));

     */
    if (this.checkpermission("getexistsusername")) {
        //recuperar el username y ver si existe
        String username = ParameterCook.prepareUsername(oRequest);

        ReplyBean oReplyBean = new ReplyBean();
        Connection oConnection = null;
        ConnectionInterface oDataConnectionSource = null;
        try {
            oDataConnectionSource = getSourceConnection();
            oConnection = oDataConnectionSource.newConnection();
            oConnection.setAutoCommit(false);
            Usuarios_propietariosDao oUserDao = new Usuarios_propietariosDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null);
            Integer iResult = oUserDao.getexistsusername(username);
            if (iResult >= 1) {
                oReplyBean.setCode(200);
                oReplyBean.setJson(JsonMessage.getJsonExpression(200, "este usuario ya existe"));
            } else {
                oReplyBean.setCode(500);
                oReplyBean.setJson(JsonMessage.getJsonMsg(500, "el usuario no existe"));
            }
            oConnection.commit();
        } catch (Exception ex) {
            if (oConnection != null) {
                oConnection.rollback();
            }
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        } finally {
            if (oConnection != null) {
                oConnection.close();
            }
            if (oDataConnectionSource != null) {
                oDataConnectionSource.disposeConnection();
            }
        }
        return oReplyBean;
    } else {
        return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized"));
    }
}

y en la capa DAO:
 public Integer getexistsusername(String strValor) throws Exception {
    String strResult = null;
    Statement oStatement = null;
    ResultSet oResultSet = null;
    Integer iResult = null;
    try {

        String strSQlL = "SELECT id FROM usuario WHERE username ='" + strValor + "'";
        oResultSet = oStatement.executeQuery(strSQlL);
        if (oResultSet.next()) {
            strResult = oResultSet.getString("id");
            iResult = Integer.parseInt(strResult, 1);
        } else {
            Log4j.errorLog(this.getClass().getName() + ":" + "getId error");
            throw new SQLException();
        }
    } catch (SQLException ex) {
        Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
        throw new Exception();
    } finally {
        if (oResultSet != null) {
            oResultSet.close();
        }
        if (oStatement != null) {
            oStatement.close();
        }
    }
    return iResult;
}