text:
Q: Is it possible to use the same node.js server for two/three different domains (aliases)? Is it possible to use the same nodeJS server for two/three different domains (aliases)?  (I don't want to redirect my users. I want them to see the exact URL they typed in the address bar. However, all three domains are exactly the same!)
I want my users to be logged in on all three domains at the same time, in order to avoid any confusion.
What is the simplest way to do this and avoid cross-domain issues?
Thanks!

A: If you mean that all domains will serve the same nodejs app then Yes you can do that.
but if each domain should open a different application then you must have a reverse proxy running on the server to handle and manage the sites/vhosts.
You may install nginx and use it as reverse proxy server or look for http-proxy a library for nodejs.
If you would like to manage the vhosts in your app you can look for vhost middleware for nodejs and use it

A: Choose one of:
Use some other server (like nginx) as a reverse proxy.
Use node-http-proxy as a reverse proxy.
Use the vhost middleware if each domain can be served from the same Connect/Express codebase and node.js instance.

A: This is a very broad question.  Moreover, it is generally a pretty bad idea, SEO-wise, to have multiple independent domains that each serve the same content.
Logging in is generally either done through Cookies, or through extra parameters in the URL.  Cookies are always domain-specific, for obvious security reasons.  If you want to ensure folks will be logged in to all the domains at once, you can create an internal purpose-driven domain to handle authentication (without such domain showing in URL bar, and only being used for HTTP redirects, effectively); such domain will store the login state for all the rest, and the rest would pick up the login state through such purpose-driven domain (through HTTP redirects).
In general, however, this sounds like too much trouble.  Consider that, perhaps, some users specifically want to use different domains for different accounts, so, you'll effectively break their usage if you mandate that a single login be used for all of them.  And, back to the original point, doing this is pretty bad for SEO, so, just don't do it.


text:
Q: LWC pass callback function dynamically I have a modal component where I am passing in two-button handler methods which are callbacks.
These two buttons are hooked up to a getter with the intent that I can override them, which I am having trouble doing.
Code Sample:
export default class CreateCaseApp extends LightningElement {

  // Default button handlers
  _saveHandler = {
    cb: this._modalSaveHandler,
    label: "Create Case",
    variant: "brand",
  };
  _cancelHandler = {
    cb: this._modalCancelHandler,
    label: "Cancel",
    variant: "netrual",
    class: "btn-left",
  };

  /**
   * Getter: Save handler callback and button props
   */
  get saveHandler() {
    return this._saveHandler;
  }

  /**
   * Getter: Cancel handler callback and button props
   */
  get cancelHandler() {
    return this._cancelHandler;
  }

  /**
   * Save event send to modal
   * @param {*} event
   */
  _modalSaveHandler = (event) => {
    console.log("Save Clicked");
  };

  /**
   * Handler event sent to modal
   * @param {*} event
   */
  _modalCancelHandler = (event) => {
    console.log("Cancel Clicked");
  };

  // Questionable code below

  /**
   * Handler event sent to modal for override
   * @param {*} event
   */
  _modalOverrideHandler = (event) => {
    console.log("Override Clicked");
  };

  onDispatchedEventFromChild(event) {
    if (event.detail == "nodata") {
      // Override save handler button
      this._saveHandler = {
        cb: this._modalOverrideHandler,
        label: "Okay",
        variant: "brand"
      };
    }
  }
}

In the above code, the initial saveHandler() and cancelHandler() are passing the fat arrow methods correctly via the cb property in the object. I can click on these buttons in the child component and they execute the method from this parent.
In the bottom section of code, I have an event listener onDispatchedEventFromChild() that receives data from a child component. When the logic in this method is met, I am trying to override the _saveHandler button by setting it with this._saveHandler={...}.
This updates the button details such as label and variant, but when I click on it, the new referenced callback isn't being fired.
Is this possible to do, or am I approaching this incorrectly? I tried using @track on the two variables, but that also didn't work.
Edit:
Parent Component HTML
<template>

    <c-modal
      modal-header={modalHeader}
      modal-save-handler={saveHandler}
    >
      <div
        slot="modalContent"
        class="modalContent slds-modal__content slds-p-around_medium"
      >
        <!-- Wrapper -->
        <c-create-case-wrapper
          contact-id={recordId}
          onmodalheaderupdate={handleModalHeaderEvent}
          onmodalhandlerupdate={handleModalHandlerEvent}
        ></c-create-case-wrapper>
        <!-- Wrapper -->

      </div>
    </c-modal>

    <!-- Main Modal Launch Button -->
    <lightning-button
      variant="brand"
      label="Create Enterprise Case"
      title="Create Enterprise Case"
      onclick={handleClick}
      class="slds-m-left_x-small"
    ></lightning-button>
    <!-- Main Modal Launch Button -->

  </template>

The parent is providing the callback for the button click within the modal component. When a button is clicked, the parent executes that method (in the parent).
In this example, the <c-create-case-wrapper> is also loading child components based on logic. When certain logic is met within those components, I need to change the button callback and label. This is where a child would dispatch an event to the parent so that I know I need to update the modal button.
I assumed that since the button was being passed to the modal reactively through the getter that I could just update that object/callback to override its defaults. This works for the label and variant properties just fine, its passing another/different callback that is not working.

A: There are a few ways to accomplish your requirement as mentioned below. Please note that code snippets are based on the github repo you pointed out and hence, you'll have to tweak it a bit if needed. Also, I've only given the code snippets that are to be added or updated (rest of your code would remain as-is).
Option 1:
In the parent component, introduce a private boolean field overrideSave and a method _modalSaveDefaultHandler. Update _modalSaveHandler code to execute based on the boolean flag value. Update onDispatchedEventFromChild code to toggle the boolean flag based on your specific conditions met. Now, the child modal component will get the callback reference to both _modalSaveDefaultHandler & _modalOverrideHandler through _modalSaveHandler.
overrideSave = false;

_modalSaveHandler = (event) => {
    if(!this.overrideSave){
        this._modalSaveDefaultHandler(event);
    }
    else{
        this._modalOverrideHandler(event);
    }
};

_modalSaveDefaultHandler = (event) => {
    console.log("Save Clicked");
};

onDispatchedEventFromChild() {
    if (event.detail == "nodata") {
        this.overrideSave = true;
    }
}

Option 2:
In the modal component HTML, you probably have the click event wired like this <button class="slds-button slds-button_brand save" onclick={modalSaveHandler.cb}>. Replace this with <button data-id="modalSaveBtn" class="slds-button slds-button_brand save">. Note that we have removed the declarative event wiring and will be doing it programmatically instead. Also, we have included a data- attribute to be able to query for the specific button element via code.
In the modal component JS, introduce a new private field handleRef which will be used to hold the reference to the callback. Modify the renderedCallback method to pass the callback reference (from modalSaveHandler public property) to handleRef and programmatically add the click event handler on the specific button. Add a new public method updateRegisteredEvent which will be called by the parent component and this method will be responsible for removing the old event listener as well as adding new event listener.
handlerRef;
isFirstRender = true;

renderedCallback() {
    if (this.isFirstRender) {
        this.handlerRef = this.modalSaveHandler.cb;
        this.template.querySelector('[data-id="modalSaveBtn"]').addEventListener('click', this.handlerRef);
        this.isFirstRender = false;
    }
}

@api updateRegisteredEvent(overrideFn) {
    this.template.querySelector('[data-id="modalSaveBtn"]').removeEventListener('click', this.handlerRef);
    this.template.querySelector('[data-id="modalSaveBtn"]').addEventListener('click', overrideFn);
}

In the parent component JS, update onDispatchedEventFromChild code to call the child component's public method (passing the override method as input param).
onDispatchedEventFromChild() {
    if (event.detail == "nodata") {
        // Override save handler button
        this._saveHandler = {
            label: "Okay",
            variant: "brand"
        };

        this.template.querySelector('c-modal').updateRegisteredEvent(this._modalOverrideHandler);
    }
}

Option 3:
In the modal component JS, define the event handler methods and hook them up in the HTML onclick attribute declaratively. The event handler code should only pass the modal component details (or form details) to the parent component via custom event. So, it doesn't know how the data will be processed by the parent component.
In the parent component, hook up event handlers corresponding to the custom events (dispatched by modal component) and implement your custom logic in these event handler based on your requirements (and specific conditions to be met).
Not providing any code samples here because this is the straight-forward LWC way of event communication and hence, should be easier to do. I would suggest to take this approach since its inline with LWC standard, defines specific function/ responsibility to each component and can be developed as reusable components.
Additional Info:
In your current code, the callback function is passed via saveHandler property during the component initialization and both the components go thru connected- and rendered- callback lifecycle hooks. So, the LWC init and render lifecycle hooks wire up the callback to the button element's click event. However, when onDispatchedEventFromChild execution updates the callback via object literal (this._savehandler), only the renderedCallback lifecycle hook executes on both the components. This basically re-evaluates the UI elements and rerenders them, but doesn't do anything about the callback fn wiring to the button click event. This could be because of the way LWC event registration works internally.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Graph an individual road's condition over time in a form I have a road_insp query in an MS Access database:
+---------+---------+-----------+-----------+
| INSP_ID | ROAD_ID | INSP_YEAR | CONDITION |
+---------+---------+-----------+-----------+
|       1 |     100 |      2009 |         1 |
|       2 |     100 |      2011 |      0.95 |
|       3 |     100 |      2012 |       0.9 |
|       4 |     100 |      2015 |      0.85 |
|       5 |     100 |      2017 |       0.8 |
+---------+---------+-----------+-----------+
|       6 |     200 |      2009 |      0.75 |
|       7 |     200 |      2011 |       0.7 |
|       8 |     200 |      2013 |      0.65 |
|       9 |     200 |      2017 |       0.6 |
+---------+---------+-----------+-----------+
|      10 |     300 |      2009 |      0.55 |
|      11 |     300 |      2011 |       0.5 |
|      12 |     300 |      2014 |      0.45 |
|      13 |     300 |      2015 |       0.4 |
|      14 |     300 |      2017 |      0.35 |
|      15 |     300 |      2017 |       0.3 |
+---------+---------+-----------+-----------+
|      16 |     400 |      2009 |      0.25 |
|      17 |     400 |      2011 |       0.2 |
|      18 |     400 |      2014 |      0.15 |
|      19 |     400 |      2015 |       0.1 |
|      20 |     400 |      2017 |      0.05 |
+---------+---------+-----------+-----------+

I would like create a form that has a record for each road. Each record in the form would have a line graph that shows the road's condition over time.
What I've tried:
I can do a couple of things that are close to what I want:

*

*I can use a where clause in the underlying query to limit the inspection records to include only road #1. While this might have the appearance of achieving what I want, unfortunately, it's not quite right. I can't navigate to the rest of the roads.

*Conversely, I can remove the where clause in the query to include all the inspection records. Again, this gives me a single record in the form, but this time it shows an average of all roads. Unfortunately, this is not what I want either:

How can I graph an individual road's condition over time in a form?

A: *

*Use a report, not a form.

*Set the report RecordSource to the Road_Insp table

*Create a GROUP in the report for the Road_ID (Insp_Year and Condition go in Detail section)

*Put a textbox in the Road_ID group header named tbxRoad

*Create a line chart in the group header section, just let the wizard build it with any RowSource

*Change the chart RowSource to SELECT Insp_Year, Condition FROM [Road_Insp] WHERE Road_ID = tbxRoad;
Or if you really prefer a form, the form RecordSource would have to be a recordset of distinct Road_ID values, such as SELECT DISTINCT Road_ID from Road_Insp; or a table of unique road IDs. Then tbxRoad and the chart would go in the Detail section of form. Could not have the Insp_Year and Condition fields (or have them in a subform or listbox next to the chart).


text:
Q: Using Bootstrap Modals to represent a external HTML file I have tried looking into setting up Bootstrap modals as external html files so I can show other websites I've made inside of the one website but couldn't really find anything that works with modals. Is this even possible or am I supposed to use a jQuery popover style method?
Thanks!

A: Rather then using an iFrame just use the following solution.
Fist visit this link. And see section with label 'Loading remote page (1)'.
You can always use this bootstrap-dialog method to populate popup any time and any situation. and also you can customize popup however you want

A: Ended up solving it and for those that possibly have the same issue, I solved it using an iframe reference inside the modal-body and stretching the iframe to fit the modal


text:
Q: What is the difference between sort data.txt | uniq -q and just 'uniq -q'? I understand that it sorts and that output is used to find out the unique statement in the file. I also feel that uniq -u should print every unique statement in the file.
uniq -u data.txt

Output for this statement is:
MsxcvOe3PGrt78wpZG2bBNF5wfXpZhET
L0nxAwlfV9V3J5onKIT8KYQ9InTcQ7yE
4c7EsUtqLnLR9hiepV5EQVhdMgyi8onL
1drBmDT7PYS7hVgoTWkJSjUZUK7ZAIAa
L0nxAwlfV9V3J5onKIT8KYQ9InTcQ7yE
78rgduVcLZjLzZmooObdaN541MKV6IfQ
x0bga8Oxz5lgM8k52HrYy4ez7XJI0lM0
irGm6F73sbUrFhHukhp6JXgMQyLxJTz1

However when I run
sort data.txt | uniq -u

Output is:
UsvVyFSfZZWbi6wgC7dAFyFuR62324324324
I am not able to understand why the first statement prints a list when there is only one line output.

A: Uniq only compares adjacent lines. Therefore uniq -u on the following input will not detect duplicates and print out everything
foo
bar
foo
bar

If you call sort first, you will get a sorted list which is deduplicated correctly. You probably have some duplicates later in the file

A: The uniq utility reads the specified input file and compares only adjacent lines and writes  a copy of each unique input line to the output file.
For example if your data is:
1
1
2
5
4
1

Output of uniq -u data  would be:
2
5
4
1

Whereas output for sort data | uniq -u would be as follows:
Output of sort:
1
1
1
2
4
5

And when this is passed to uniq -u the output would be:
2
4
5


text:
Q: Pandas convert datatime format I have a pandas dataframe with a column of datetime object with the following format:
df['TIME_M']=pd.to_datetime(df['TIME_M'],format='%Y%m%d %H:%M:%S.%f')

However, at the same time, I also want a column of datetime with the following format (without the %f):
%Y%m%d %H:%M:%S

Can I covert from the datetime object %s to the one without %s in a fast way?
Currently I am using the following code:
df['TIME_S']=df.TIME_M.map(lambda t:t.strftime('%Y%m%d %H:%M:%S'))

However, it seems that converting to string is a rather slow operation for pandas. I was wondering if there is a fast way to make the conversion, while keeping the output of the conversion as a datetime object?
P.S. Assume that I already have df['TIME_M'] in format %Y%m%d %H:%M:%S.%f

A: First if need datetimes format is a bif different like need - YYYY-MM-DD HH:MM:SS.
If need datetimes without %f add floor:
df['TIME_M'] = pd.to_datetime(df['TIME_M'], format='%Y%m%d %H:%M:%S.%f').dt.floor('s')
#if datetimes column
#df['TIME_M'] = df['TIME_M'].dt.floor('s')

Or convert to numpy values ant then seconds:
df['TIME_M'] = pd.to_datetime(df['TIME_M'],format='%Y%m%d %H:%M:%S.%f').values.astype('datetime64[s]')
#if datetimes column
#df['TIME_M'] = df['TIME_M'].values.astype('datetime64[s]')

Or split in list comprehension:
df['TIME_M'] = pd.to_datetime([x.split('.')[0] for x in df['TIME_M']], format='%Y%m%d %H:%M:%S')

Timings in sample data:
N = 100000
df = pd.DataFrame({'TIME_M':['20190913 04:04:20'] * N})
df['TIME_M'] +=  ['.{}'.format(x) for x in range(1, len(df)+1)]

df['TIME_M1'] = pd.to_datetime(df['TIME_M'],format='%Y%m%d %H:%M:%S.%f').dt.floor('s')
df['TIME_M2'] = pd.to_datetime([x.split('.')[0] for x in df['TIME_M']], format='%Y%m%d %H:%M:%S')
df['TIME_M3'] = pd.to_datetime(df['TIME_M'],format='%Y%m%d %H:%M:%S.%f').values.astype('datetime64[s]')

#print (df)

In [180]: %timeit df['TIME_M3'] = pd.to_datetime(df['TIME_M'],format='%Y%m%d %H:%M:%S.%f').values.astype('datetime64[s]')
28.2 ms ± 358 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [181]: %timeit df['TIME_M1'] = pd.to_datetime(df['TIME_M'],format='%Y%m%d %H:%M:%S.%f').dt.floor('s')
28.7 ms ± 208 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [182]: %timeit df['TIME_M2'] = pd.to_datetime([x.split('.')[0] for x in df['TIME_M']], format='%Y%m%d %H:%M:%S')
69 ms ± 1.81 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Thanks for another 2 solutions, @Anton vBR:
In [187]: %timeit df['TIME_M4'] = pd.to_datetime(df['TIME_M'].str[:17], format='%Y%m%d %H:%M:%S')
58 ms ± 709 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [188]: %timeit df['TIME_M5'] = pd.to_datetime([x[:17] for x in df['TIME_M']], format='%Y%m%d %H:%M:%S')
45.6 ms ± 536 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)


text:
Q: RecyclerView.Adapter items with different layoutparams I'm using RecyclerView to show elements of my data set. everything seems to work perfectly except I had two different types of items and I wish to change the Margin of each type to emphasize this slight difference.
to this end I used the viewtype of the adapter , however getLayoutParams() in onCreateViewHolder(ViewGroup parent, int viewType) seems to not give the correct params which I need to modify. recreating this param from scratch dynamically (with all the shadow and what not) seems unjustified.
here's my code:
private final static int TYPE1= 1;
private final static int TYPE2= 2;

@Override
public int getItemViewType(int position) {
    if(data_set.get(position).isType1()) {
        return TYPE1;
    }
    return TYPE2;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // create a new view
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
    int margin = parent.getContext().getResources().getDimensionPixelSize(R.dimen.end_margin);
    if(viewType == TYPE1)
    {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) parent.getLayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            params.setMarginStart(margin);
        }else{
            params.setMargins(margin,0,0,0);
        }
        v.setLayoutParams(params);
    }
    return new ViewHolder(v);
}

and heres my xml for item_layout
<android.support.v7.widget.CardView
    android:id="@+id/item_card"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:foreground="?android:attr/selectableItemBackground"
    android:orientation="vertical"
    card_view:cardElevation="@dimen/cardview_default_elevation"
    android:clickable="true"
    card_view:cardCornerRadius="3dp"
    android:nestedScrollingEnabled="false">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layoutDirection="rtl"
        android:layout_marginEnd="20dp"
        android:layout_marginRight="20dp"
        android:orientation="horizontal">
        <ProgressBar
            android:id="@+id/img_loading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true" />
        <TextView
            android:id="@+id/tv_contact_name"
            android:gravity="end"
            android:layout_margin="5dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

</android.support.v7.widget.CardView>

many thanks for any guidance provided.

A: When you call parent.getLayoutParams(); you are getting the params from the recyclerview.
If you want the parameter to the LinearLayout inside your xml file give it an id, and retrieve it inside your code. So something like this:
LinearLayout myLayout = v.findViewById(R.id.mylinearlayout);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) myLayout.getLayoutParams();

//do something with parameters

myLayout.setLayoutParams(params);

A: after some trial and error, I found a rather weird solution which most likely stems from that fact that I do not know the working of RecyclerViewwell.
at any rate I solved this problem by getting parent.getParent()'s CardView.LayoutParams and after modifications setting it to the view.
here's the modified code:
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // create a new view
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
    int endMargin = MyApplication.getSharedContext().getResources().getDimensionPixelSize(R.dimen.chat_end_margin);
    int margin = MyApplication.getSharedContext().getResources().getDimensionPixelSize(R.dimen.chat_margin);
    if(viewType == TYPE1)
    {
        ViewGroup parentView = (ViewGroup)parent.getParent();
        CardView.LayoutParams params = (CardView.LayoutParams) (parentView.getLayoutParams());
        params.setMargins(endMargin,margin,margin,margin);
        v.setLayoutParams(params);
    }
    return new ViewHolder(v);
}


text:
Q: How to loop through specific data frames based on a List and add them all in a rbind function using R? I have 5 dataframes all with the same heading and columns
df1,df2,df3,df4,df5

I created a list based on the dataframe names
List<-c("df1","df2","df3","df4",d"f5")

I want to create an rbind looping the df's based off the list. i tried this
ALL_dfs<-lapply(List,rbind)

but this doesn't read it as a combined dataframe by rbind function.

A: I think the most straightforward option is this:
do.call(rbind, mget(List))

?mget

Search by name for an object (get) or zero or more objects (mget).

The other option, if possible, is to store your data.frames in a list when you create them. Not always an option, but may be possible with some planning

A: With map_df from purrr.
library(purrr)
all_dfs <- map_dfr(.x = List, .f = bindr)


text:
Q: Eliminar un registro de un modelo que no posee una llave primaria Estoy teniendo un problema quiero eliminar un registro el problema que tengo es que para eliminar un registro tengo que identificarlo por dos campos los cuales son ID_ENLACE Y PERIODO ya que en esta base no se guarda un id ya es algo establecido
esta es mi vista de mi datatable donde obtengo el id_enlace y el periodo

                                PROVEEDOR
                                DESC_ENLACE
                                NO_FACTURA
                                ID_ENLACE
                                VALOR_PAGO
                                PERIODO
                                FECHA_FACTURA
                                OPCIONES

                            @foreach($datos as $datos)

                                    {{$datos->proveedor}}
                                    {{$datos->desc_enlace}}
                                    {{$datos->no_factura}}
                                    {{$datos->id_enlace}}
                                    {{$datos->valor_pago}}
                                    {{ \Carbon\Carbon::parse($datos->periodo)->format('d-m-Y')}}
                                    {{ \Carbon\Carbon::parse($datos->fecha_factura)->format('d-m-Y')}}

                                        id_enlace.'/'.$datos->periodo)}}"  class="btn btn-danger active" role="button" aria-pressed="true">Eliminar

                            @endforeach

Esta es mi ruta donde mando el id y el periodo
Route::GET('eliminar/{id_enlace}/{periodo}',[
   'as'=>'eliminar',
   'uses'=>'vista@destroy'
]);

este es mi controlador donde quiero indicar que me elimine ese registro
  public function destroy($id_enlace,$periodo)
    {

//        var_dump($id_enlace,$periodo);
        $user = importar::where('ID_ENLACE', $id_enlace)
            ->where('PERIODO', $periodo)
            ->first();
        $user->delete();
        return view('formulario');
    }

este es mi modelo
class importar extends Model
{

    protected $table="fcm_enl_ter_fact";

    protected  $fillable  = [
        'PROVEEDOR','DESC_ENLACE','NO_FACTURA','ID_ENLACE','VALOR_PAGO','PERIODO','FECHA_FACTURA','FECHA_INGRESO','MONEDA','TC_FACTURA'
    ];

    public $timestamps = false;
    public $incrementing = false;
}

este es el error que me esta tirando
Error Code : 904
 Error Message : ORA-00904: "ID": invalid identifier
 Position : 37
 Statement : delete from "FCM_ENL_TER_FACT" where "ID" is null
 Bindings : []
 (SQL: delete from "FCM_ENL_TER_FACT" where "ID" is null)

al hacer un dd si me esta traendo los valores
dd($id_enlace,$periodo);
Si me esta traendo los valores

le hice un dd ala consulta y si me identifica el registro

A: El método find solo recibe:

*

*El id o llave primaria del modelo relacionado

*Si deseas pasar múltiples valores dentro de este método entonces deben ser:

*

*Dentro de un vector

*Ser llaves primarias

En caso de que los puntos anteriores no se cumplan, entonces tu consulta debería ocupar:

*

*2 métodos where para indicar las 2 condiciones a cumplir

*Usar el método first para indicar que de la consulta solo nos devuelva el primer resultado

Consulta:
public function eliminar_datos_usuarios($id_enlace,$periodo)
{
    $user = fcm_enl_ter_fact::where('id_enlace', $id_enlace)
                            ->where('periodo', $periodo)
                            ->delete();
    return view('formulario');
}

Nota:

*

*Si tu modelo no posee llave primaria entonces agrega las siguientes propiedades

Código:
protected $primaryKey = null;
public $incrementing = false;

Enlaces
Revisa aquí la documentación

A: La primer recomendación, es crear una llave primaria, ya puede ahorrarte bastante trabajo en el futuro sobre todo si vas a usar Eloquent.
Si aún así, no quieres agregar una llave primaria, puedes que omitir Eloquent y escribir la consulta con Query Builder.
Consulta con Query Builder:
DB::table('fcm_enl_ter_fact')
    ->where('ID_ENLACE', $id_enlace)
    ->where('PERIODO', $periodo)
    ->delete();


text:
Q: How to implement headless browser for secure browser (HTTPS) or validate certificate by utilizing PhantomJs in Selenium? I need to implement Headless Browser for HTTPS (validate certificate). For this I need to write extra line of code.
I have written for browser HTTP and it is working fine.
public class Headless {

  public static void main(String[] args)

 {

File src=new File("C:\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");

  System.setProperty("phantomjs.binary.path",src.getAbsolutePath());

  WebDriver driver=new PhantomJSDriver();

  driver.get("https://www.google.co.in/");

  System.out.println(driver.getTitle());

 }

}

I google it and get some info:-
phantomjs --ignore-ssl-errors=yes;

A: DesiredCapabilities dcap = new DesiredCapabilities();
String[] phantomArgs = new String[] {
    "--ssl-protocol=any",
    "--ignore-ssl-errors=true"
};

dcap.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, phantomArgs);

PhantomJSDriver driver = new PhantomJSDriver(dcap);

You can read more about the command-line options on this link: Command Line Interface | PhantomJS


text:
Q: How to revert to one line terminal in new Kali Linux 2020.04 ┌──(kali㉿kali)-[~]
└─$

I want this to be in one line on terminal like it was before I updated kali.
I tried changing bashrc on kali user and on root user there was no update.

A: Edit your .zshrc file and change the variable PROMPT like so:
PROMPT=$'%F{%(#.blue.green)}${debian_chroot:+($debian_chroot)──}(%B%F{%(#.yellow.blue)}%n%(#..㉿)%m%b%F{%(#.blue.green)})-[%B%F{reset}%(6~.%-1~/…/%4~.%5~)%b%F{%(#.blue.green)}]%B%(#.%F{yellow}#.%F{blue}$)%b%F{reset} '

You can also get rid of the newline between prompts. Just change this variable to "no":
new_line_before_prompt=no

While I was at it I also changed the color red to yellow, because It was popping out too much to me.
In order for the changes to take effect you must restart the Terminal or execute source ~/.zshrc.

A: Three options are there so you can choose your preferred configuration, as depicted below
first, edit the zshrc with your favorite editor; after that, replace the PROMPT_ALTERNATIVE and NEWLINE_BEFORE_PROMPT accordingly.
$ nano ~/.zshrc

When done refresh the terminal to apply the new changes
$ source ~/.zshrc

Second option as highlighted by @user1678412  is to use kali-tweaks following the steps below:
$ kali-tweaks

A: Kali has very simple command utility for this purpose:
kali-tweaks

source:
https://www.kali.org/docs/general-use/kali-linux-sources-list-repositories/```

A: Very easy solution! Type in the terminal kali-tweaks, then go to shell and prompt then configure prompt move cursor to one line and press space then apply and you're done!

A: In addition to the above answer, if you would like to revert to a simple one liner (without blue brackets and parentheses or icons):
nano ~/.zshrc

Then edit the line to be
PROMPT='${debian_chroot:+($debian_chroot)}%B%F{%(#.red.blue)}%n%(#.@.@)%m%b%F{reset}:%B%(6~.%-1~/…/%4~.%5~)%b%B%(#.%F{red}#.%F{blue}$)%b%F{reset} '

Would also recommend turning off $new_line_before_prompt

A: Another option is to use bash instead of zsh. Since you already edited the .bashrc file, just run bash in the prompt to test your edits. To make permanent, you can edit /etc/passwd, making /usr/bin/bash your default shell:
┌──(rootblackbox01)-[~]
└─# vim /etc/passwd
...
root:x:0:0:root:/root:/bin/bash  ##<< instead of /usr/bin/zsh
...
### reboot
...
root@blackbox01:~#
root@blackbox01:~#

A: In ~/.zshrc there's a kali config variable named PROMPT_ALTERNATIVE, possible values oneline, twoline (default value) and a keybinding ^P (Ctrl+P) is associated with it.
Using this one can toggle between the two possible alternatives.


text:
Q: handling logging in laravel on balanced servers I have 2 balanced servers for my Laravel app, but each of them is logging in it's own target folder (we use a daily file logging): is there any way to have a centralized location to save logs to?
I already arranged the logging configurations to include server name in the output, but i can't figure out how to handle this situation.
Maybe an object storage? or what?
Non third party solutions will be better, we would like to keep everything inside laravel and our servers, but if it's no choice we'll arrange an external solution.

A: Now there probably isn't a "best" way to do this and Laravel offers a lot of flexibility on how to do this if you check the docs. In fact since NewRelic is supported this can be a decent way to solve this issue if you are using NewRelic already.
We use the database to log. We can do this because the database is hosted outside the servers but in the same VPC of AWS which means the latency is very low. We have a table with id, message, detail, created_at, severity here's a simple way to do it:
In your EventServiceProvider (any service provider will work really)
Event::listen(MessageLogged::class, function (MessageLogged $messageLogged) {
      [ $level, $message, $context ] = [ $messageLogged->level, $messageLogged->message, $messageLogged->context ];
      if (!\Log::getLogger()->isHandling(Logger::toMonologLevel($level))) {
            return; // Don't log if the logger isn't actually handling this level
      }
      if (($message instanceof \Exception || $message instanceof \Throwable)) {
          $context = [$message];
          $message = $message->getMessage();
      }
      DB::table('log')->insert([
          'message' => $message
          'detail' => implode(PHP_EOL, $context ?: []),
          'created_at' => Carbon::now(),
          'severity' => $level
      ]);
});

If performance is an issue you can also create a task that will queue the processing of the log event, but that means you have to queue it with the time the event happened rather than the time it was handled.


text:
Q: Unable to configure IntelliJ to use Java 11 Although IntelliJ IDE doesn't give me any warning, this two-line method causes a compilation error Error:(12, 37) java: incompatible types: byte[] cannot be converted to int:
import java.math.BigInteger;

public class Test {

    public static void main(String[] args){
        String foo = "123";
        new BigInteger(foo.getBytes(), 1, 1);
    }
}

In JDK 11 there is a valid constructor with this signature public BigInteger(byte[] val, int off, int len)(line 306 of java.math.BigInteger) but not in JDK 8. I was able to compile it directly with javac for JDK 11 but it fails with JDK 8 as expected. I have configured IntelliJ to use JDK 11 but I don't know why it's using an older version... System.out.println(System.getProperty("java.version")) prints 11.0.1. Seems like it's compiling with JDK 8 and running it with JDK 11.
I have checked I have JDK 11 selected in the following places:

*

*Run/Debug Configurations > JRE

*Project Structure > Project > Project SDK

*Project Structure > Project > Project Language Level

*Project Structure > Modules > Language Level

I am using IntelliJ IDEA 2018.2.6 (Community Edition). Problem persists after restarting IntelliJ.
Edit:
project uses maven

A: There can be few factors of similar problems, mainly caused by other tools being in use (e.g. maven or gradle).
When using just the IDE to compile and run code there should be no problem (as the used Java version was fully configured).
The build tools (maven,gradle) can be set to use different version of Java then the one configured in IDE.
To see the version use by those tools run in terminal:
gradle -version
mvn -version

The output should contain of Java version configured with those tools.
Their Java version mostly uses the JAVA_HOME environment variable, which points to the JRE/JDK location.
If the build tools are using the different Java version to compile the sources, then the version which starts the application may lead to such errors and exception.
That problems are related to the changes of standard API between Java8 and newer versions.
Changing the value of JAVA_HOME variable to point to the Java11 folder should do the work, but if the older version is still needed then, for example when using Maven, it's possible to use the plugin:
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.11</source>
        <target>1.11</target>
    </configuration>
</plugin>


text:
Q: Android emulator errors (socketTcpLoopbackClientFor and AdbHostServer.cpp) I just installed Android Studio (Windows) and I created a google pixel 3 XL, API 29, no play store installed.
When I launch an hello word application, I get these 2 errors:
Emulator: socketTcpLoopbackClientFor: error: fd 52252 above FD_SETSIZE (32768)
Emulator: emulator: ERROR: AdbHostServer.cpp:102: Unable to connect to adb daemon on port: 5037

For what concerning the first error, I tried this Problem with the emulator since the update but it didn't work.

A: If you're using an AMD processor, you must activate "Android Emulator Hypervisor Driver for AMD Processors" included in SDK Tools.
After this, the emulator operates normally. If error is present yet, it don't stop the emulation

A: I am not sure if it is helpfull but I will share my experience as a possible answer. I struggled for three days trying to face a very similar issue as yours. And in my case it was working properlly until that. I created a question here but I din't get answer yet. Well, I tried all I found around. Then I read somewhere someone facing issues with emulator and just downground it and it fixed it. I just tried downgraded from Android 10+ to Android 10 and to API #29 and I got a complete diferent issue. Than I tried again to Android 9 and API #28 and it fixed my issue.
One more thing it can be usefull. I noted that before I downgraded Android/API I had many more for this list
C:\Users>netstat -ano | findstr "5037"
  TCP    127.0.0.1:5037         0.0.0.0:0              LISTENING       7892
  TCP    127.0.0.1:5037         127.0.0.1:49735        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51843        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51855        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51859        ESTABLISHED     7892
  TCP    127.0.0.1:5037         127.0.0.1:51867        ESTABLISHED     7892
  TCP    127.0.0.1:49735        127.0.0.1:5037         ESTABLISHED     9604
  TCP    127.0.0.1:51843        127.0.0.1:5037         ESTABLISHED     13184
  TCP    127.0.0.1:51855        127.0.0.1:5037         ESTABLISHED     9604
  TCP    127.0.0.1:51859        127.0.0.1:5037         ESTABLISHED     9604
  TCP    127.0.0.1:51867        127.0.0.1:5037         ESTABLISHED     9604

And maybe checking you SDk Tools installed can help also

A: *

*Install the following stuff I mentioned in the pic.

*Make sure you are using any nexus emulator which is good for a performance boost.

*Update the plugins frequently to avoid these errors.

More Info

A: I finally have found a kind of workaround for this. This is a problem caused by the now latest stable version of Android Studio(4.0.1).
I fixed this by downloading Android Studio 4.2 Canary 7 build, installing it. Then, running the emulator from it, followed by using that emulator in my primary Android Studio.
I advice you not to work on your project from the Canary itself, as it has many unknown bugs, and you will regret working.
Feel free to ask any more doubts.

A: I had the same issue on Android Studio 4.0.1 and resolved it by deleting the plugins located in C:\Users\yourusername\AppData\Roaming\Google and installed Android Studio 4.1 RC 1
https://developer.android.com/studio/preview/index.html


text:
Q: How to write a line to text file when particular condition is satisfied I have a loop and checking one condition as follows
 while (t<len(var)):
        PR=y
        ...
        if z[t]<PR :
              pass_check=1
        else:
              pass_check=0
      t=t+1

# check z for all samples and print the result
if pass_check==1:
print ('Test is  pass')
elif pass_check==0:
print ('Test is  fail')
else:
print ('Test is  fail')

Goal
How to write Test is pass or fail in a text file depending upon the condition if all samples are 1 or 0 respectively

A: Just write it to a file like this:
with open('your_file', 'w') as output_file:
    output_file.write('Test is pass' if pass_check==1 else 'Test is fail')


text:
Q: Problema con WebStorn no abre en Linux Instale Webstorn y al abir la primera vez todo bien pero cuando intente abrirlo por segunda vez no abre nada, Nose a que se deba eso alguna ayuda.?
Intento abrirlo con la terminal ejcutando el comando webstorn pero me da este error:
Traceback (most recent call last):
  File "/usr/local/bin/webstorm", line 136, in
    start_new_instance(ide_args)
  File "/usr/local/bin/webstorm", line 131, in start_new_instance
    os.execv(RUN_PATH, [bin_file] + args)
OSError: [Errno 2] No such file or directory
La distro que estoy usando es KaliLinux.

A: Estas intentando abrir de nuevo el programa que ya esta en ejecución. es probable que tenga instancias en segundo plano a pesar que lo cierres, lo que te aconsejería fuera matar totalmente el proceso mediante el PID.
Primero buscas el proceso para encontrar el número del PID
ps -f | grep -i webstorm

En el PID lo cambias por el número de proceso del programa webstorm
kill -9 PID

Espero haberte ayudado.


text:
Q: How to set custom web console name in IBM WebSphere 7.0 using jython? This is my first question,need your help,thanks!
My question is :How to set custom web console name in  IBM WebSphere 7.0 using jython?I've known how to set it on the web console.

this url  tells how to set on the web console and some description about custom console name string:     https://www.ibm.com/support/knowledgecenter/zh/SSAW57_7.0.0/com.ibm.websphere.nd.iseries.doc/info/iseriesnd/isc/console_id.html

I just want to set it(the value of  "ISC.CONSOLE.ID.CUSTOM" which key mentioned in above url) in command line(wsadmin.sh) by jython.I've search for this answer for several days,and I've also viewed the ibm official online doc.But not got what I want.
   AdminConfig,AdminTask,AdminControl,AdminApp,which type command should I use? I've read help() method of them,but also found no answer.
Please help me,thanks!
just change the red marked title using jython


text:
Q: Animating alerts with AngularJS instead of jQuery I am working on a blog application with Codeigniter 3.1.8 and AngularJS v1.7.8.
The post comments form is submitted via AngularJS. Here is the form:

Leave a comment

    <form name="commentForm" novalidate>

                <input type="text" name="name" id="name" ng-model="newComment.name" placeholder="Name" ng-required="true" />
                This field can not be empty

                <input type="email" name="email" id="email" ng-model="newComment.email" placeholder="Email" ng-required="true" />
                Enter a valid email address

                <textarea name="comment" rows="6" id="message" ng-model="newComment.comment" placeholder="Comment" ng-required="true"></textarea>
                This field can not be empty

                <input type="submit" value="Add comment" ng-click="createComment()" class="button special fit" />

    </form>

{{commentSuccessMsg}}

And here is the AngularJS controller that manages it's submission to the application's back-end:
 // Post comment
.controller('PostCommentController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
    const slug = $routeParams.slug;
    $http.get('api/' + slug).then(function(response) {

        let post_id = response.data.post.id;

        $scope.commentSubmitted = false;

        $scope.newComment = {
            slug: slug,
            post_id: post_id,
            name: $scope.name,
            email: $scope.email,
            comment: $scope.comment
        };

        $scope.createComment = function(){
            if ($scope.newComment.name !== undefined && $scope.newComment.email !== undefined && $scope.newComment.comment !== undefined){
                $http.post('api/comments/create/' + post_id, $scope.newComment)
                .then(() => {
                    $scope.newComment = {};
                    $scope.commentForm.$setPristine();
                    $scope.commentForm.$setUntouched();
                    $scope.commentSuccessMsg = "Your comment was submitted. It will be published after aproval";
                    $scope.commentSubmitted = true;
                });
            }
        };
    });
}])

I have not been able to find an AngularJS way to animate the form alert(s) out of the scene. I have been using jQuery for a long time for frontend animations and with jQuery I would have done something like this:
// Hide alerts
$('.alert:not(".alert-dismissible")').each(function(){
 $(this).delay(4000).slideUp(200);
});

What would be a simple and robust AngularJS alternative to this kind of solution?

A: I have found a solution with CSS keyframes and AngularJS's $timeout:
CSS:
@-webkit-keyframes fadeOut {
  0% {
    opacity: 1;
  }
  99% {
    opacity: 1;
    height: auto;
    padding-top: 0;
    padding-bottom: 0;
  }
  100% {
    opacity: 0;
    height: 0;
    padding-top: 0;
    padding-bottom: 0;
  }
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  99% {
    opacity: 0.01;
  }
  100% {
    opacity: 0;
    height: 0;
    padding-top: 0;
    padding-bottom: 0;
  }
}

.fadeout {
  -webkit-animation: fadeOut 1s;
   animation: fadeOut 1s;
   animation-fill-mode: forwards;
   border: none;
   overflow: hidden;
}

I have ised AngularJS $timeout to $scope.createComment for the delay:
$scope.createComment = function() {
  if ($scope.newComment.name !== undefined && $scope.newComment.email !== undefined && $scope.newComment.comment !== undefined) {
    $http.post('api/comments/create/' + post_id, $scope.newComment)
      .then(() => {
        $scope.newComment = {};
        $scope.commentForm.$setPristine();
        $scope.commentForm.$setUntouched();
        $scope.commentSuccessMsg = "Your comment was submitted. It will be published after aproval";
        $scope.commentSubmitted = true;
        // this was added for the delay (3 seconds)
        $timeout(function() {
          $scope.fadeout = "fadeout";
        }, 3000);
      });
  }
};

The alert div looks like so:

{{commentSuccessMsg}}

There is a working demo HERE.

A: Change the class after the delay, use CSS to animate the slides.
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations


text:
Q: Using HTTPS or encrypt response myself Currently, My site is facing many bad requests, and i want to encrypt the response in order to reduce those bad requests.
My first idea is that let client side invokes my site's api with their unique signature which is allocated by me,
e.g. http://www.my_api/?query=aa&sign=unique_string.
And then i verify the signature, if it's valid, i encrypt the response with the signature by some encryption algorithm. Then let client side decrypt the response by its signature.
I wonder whether it is a common way?
And i've also heard about HTTPS. Can HTTPS solve my problem? If so, which is better, or please share your idea.

A: You should go for HTTPS.
Using HTTPS provides authentication mechanism which helps to get rid of MITM attacks. It protects you from Information Disclosure and Tampering of the data as it encrypts the communication between the client and the server (and vice versa).


text:
Q: Dragon Naturally Speaking in Ubuntu I'm trying to get Dragon Naturally Speaking working through Ubuntu....
I set it up in virtualbox, but i found it incredibly tough to access its features through Linux. I know there is a way to do it through wine, because this dude did a pretty sick hack for speech recognition in python.
 YouTube.com: Using Python to Code by Voice
Also i know theres a neat little python hack called dragonfly that works. My overall goal here is to create my own commands using my keyboard (piano) that correspond to cool functions like unlocking my computer or something (imagine how cool it would be if your password was the noise the guy in the movie Contact plays for the aliens or something like that).
Arbitrary references aside, this is my first post on the forums so please go easy on me. I 'm also relatively new to Ubuntu and the Linux format, but if someone could walk me through the steps to get dragon naturally speaking 12 premium edition working on Ubuntu's latest version(whatever i downloaded like 3 weeks ago) I'm pretty sure I can struggle through making some custom macros myself.
I have Googled and tried a number of different approaches through wine, but, none have been successful thus far.
Cheers!

A: You should look at Platypus. This should do what you want, translating voice commands from Dragon Speak running in Wine to Linux keystrokes.
It's not easy to install, nor easy to configure. You are expected to know how to compile software and hunt dependencies, so if you are a beginner be ready for a though ride and lots of trial and error.


text:
Q: Filter a list of dictionaries based on another list of strings I have a list of dictionaries such as below
data = [{'Person1':['a', 'b', 'c']}, {'Person2':['1', '2', '3']}, {'Person3':['x', 'y', 'z']}]

and it consists of almost 7000000 dictionaries. Then I have a list of strings such as
people = ['person1', 'person3']

that is of length 450000. All of the strings in this list exist as keys in the list of dictionaries.
What is the fastest/most efficient way to filter the list of dictionaries based on this list of strings, so as to get back a new dictionary that only contains keys that corresponds to the strings in the list such as
d = {'Person1':['a', 'b', 'c']}, 'Person3':['x', 'y', 'z']}

This is my code, but it takes a really long time to run, and I was wondering what the best way to approach this is.
d = {}

for p in people:
    for i in data:
        for k in i:
            if p == k.lower():
               d[p] = i[k]

A: A first suggestion using dict-comprehension:
from collections import ChainMap

data = [
    {'Person1':['a', 'b', 'c']},
    {'Person2':['1', '2', '3']},
    {'Person3':['x', 'y', 'z']}
]
people = ['Person1', 'Person3']

big_dict = dict(ChainMap(*data))

# drop duplicates
people = list(set(people))

smaller_dict = {person: big_dict[person] for person in people}

For ChainMap see here.
I used people as a list (not as a set) because it has been reported that lists perform slightly faster in these cases.

A: Few benchmarks -
Nested For loops
%%timeit

out = []
for i in data:
    for j in people:
        if list(i.keys())[0]==j:
            out.append(i)

#1.78 µs ± 55.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

List comprehension with in
%%timeit

out = [i for i in data if list(i.keys())[0] in people]

#1.02 µs ± 36.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

List comprehension with set.intersection
%%timeit

out = [i for i in data if set(i).intersection(people)]

#1.04 µs ± 27.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


text:
Q: Define specific json export format of pandas dataframe I need to export my DF into a specific JSON format, but I'm struggling to format it in the right way.
I'd like to create a subsection with shop_details that show the city and location for the shop if it's known, otherwise it should be left empty.
Code for my DF:
from pandas import DataFrame

Data = {'item_type': ['Iphone','Computer','Computer'],
        'purch_price': [1200,700,700],
        'sale_price': [1150,'NaN','NaN'],
        'city': ['NaN','Los Angeles','San Jose'],
        'location': ['NaN','1st street', '2nd street']
        }

DF looks like this:
  item_type  purch_price sale_price         city    location
0    Iphone         1200       1150          NaN         NaN
1  Computer          700        NaN  Los Angeles  1st street
2  Computer          700        NaN     San Jose  2nd street

The output format should look like below:
[{
    "item_type": "Iphone",
    "purch_price": "1200",
    "sale_price": "1150",
    "shop_details": []
  },
  {
    "item_type": "Computer",
    "purch_price": "700",
    "sale_price": "600",
    "shop_details": [{
        "city": "Los Angeles",
        "location": "1st street"
      },
      {
        "city": "San Jose",
        "location": "2nd street"
      }
    ]
  }
]

A: import json

df = df.fillna('')

def shop_details(row):
    if row['city'] != '' and row['location'] !='':
        return [{'city': row['city'], 'location': row['location']}]
    else:
        return []

df['shop_details'] = df.apply(lambda row: shop_details(row), axis = 1)

df = df.drop(['city', 'location'], axis = 1)

json.dumps(df.to_dict('records'))

Only problem is we do not group by item_type, but you should do some of the work ;)

A: You can do like below to achieve your output. Thanks
from pandas import DataFrame

Data = {'item_type': ['Iphone','Computer','Computer'],
        'purch_price': [1200,700,700],
        'sale_price': [1150,'NaN','NaN'],
        'city': ['NaN','Los Angeles','San Jose'],
        'location': ['NaN','1st street', '2nd street']
        }

df = DataFrame(Data, columns= ['item_type', 'purch_price', 'sale_price', 'city','location' ])

Export = df.to_json ('path where you want to export your json file')


text:
Q: Regular expression for arabic with spaces I have to validate arabic letters using regular expression.
For the same I use the below one
^[\u0600-\u06ff]+$

its works for Arabic characters without spaces. To accept with spaces I modified the regular expression as below
 ^[\u0600-\u06ff]?(\w)+$
 ^[\u0600-\u06ff]?[\w]+$
 ^[\u0600-\u06ff?\w]+$

but all the method failed and not passing for Arabic characters without spaces also.
Please help me to include spaces also with the same.

A: Just add space to the character class to match the spaces
^[\u0600-\u06ff ]+$

A: Just include \s inside the character class.
^[\u0600-\u06ff\s]+$


text:
Q: What turns the Hulk red? I've seen multiple cartoons and comics where the Hulk is not green, but red. Is there any explanation for this? What are the changes to his powers and personalities? Does he have any other 'colours'?

A: The Red Hulk is a different character.

A: The Bruce Banner Hulk has been portrayed as both grey and green over the years, largely due to changes in printing technologies, artist changes, etc.
In the late 80s, Marvel retconned the changes to reflect an unrevealed Dissociative Identity Disorder (DID)  that Banner suffered from long before he became the Hulk. The physical effects of his Gamma radiation mutation reflected the dormant personalities that were part of Banner's psyche.
They also used the mental illness to explain why the Hulk's intelligence would vary dramatically over the course of the character's development. Peter David took the idea even further to introduce more varied personalities, like Mr. Fixit.
The Red Hulk is an entirely different character.
General Thunderbolt Ross, in an effort to finally defeat the Banner Hulk, undergoes a variation of the super-soldier program that transforms him into the Red Hulk. Part of Ross' plan involved faking his own death at the hands of Red Hulk, presumably at Banner's request, so that his true identity would remain secret. Since Ross doesn't suffer from Banner's DID, he is better able to retain his intelligence and tactical knowledge.
Later in the series, Ross uses the same process to save his daughter Betty, turning her into the Red She-Hulk.


text:
Q: How X509 Certificate renewal does not impact the code? What attribute should I use to load the certificate from cert store in code so that no
 change is required when the certificate is renewed?

A: The Subject (distinguished name) is what's generally used for this in any libraries that use certificates (WCF, WSE and the like).  You should be safe with that.


text:
Q: How to check in java if user is clicking save button unnecessarily and there is nothing to save? In my piece of code there is one input box so data will be fetched in that box on drop down selection. And if user do not want to insert/update/delete that data and click on save button unnecessarily then i have to show an error message that: "There is nothing to save..You pressed the save button unnecessary."
Currently , i am checking if the data in input box is equals to the  database value then show that error but its not working.
if (inputVal1.equals(dbVal1.getValue()) && inputVal2.equals(dbVal2.getValue())) {
    addPageError(T_NOTHING_TO_SAVE);
}

Please suggest how to handle this validation in java.

A: Store the data in a separate variable and simply compare it to the current values in the input box. If you do this, you could even detect if the values were changed, but then changed back to the original value. Apart from this you could also even deactivate the button and compare in an edit-event of the input box if the content has really changed and enable the button accordingly.


text:
Q: How to start webkitSpeechRecognition on CefSharp browser for wpf I've created a javascript page and when I load that page inside chrome browser I am able to start webkitSpeechRecognition. However when I call that url with CefSharp browser for winform, It does not start the webkitSpeechRecognition.
Could you please advise me what could be the possible reason?
Here is the code snippet I call on button click.
function startWebKit() {

  if (window.hasOwnProperty('webkitSpeechRecognition')) {

    var recognition = new window.webkitSpeechRecognition();
    var recognizing = false;

    recognition.onstart = function () {
      recognizing = true;
    };

    recognition.onend = function () {
      recognizing = false;
    };

    recognition.onerror = function (event) {
      recognizing = false;
    };

    try {
      recognition.start();
    } catch (error) {
      alert(error);
    }

    if (recognizing) {
      // Do stuff
    }
  }
}

TIA


text:
Q: Selecting different number of columns in a CSV file The task is to extract data from multiple CSV files according to a criteria. The file contains a sampleId (this is the criteria) and other columns. At the end of the file there are the measurement values under 0...100 named columns (the numbers are the actual names of the columns). To make it a bit more interesting there can be variations in different CSV files, depending on the customer needs. This means the measurement data count can be 15, 25, 50 etc. but no more than 100 and no variations within one file. This data is always placed in the end of the line, so there is a set of columns before the numbers.
I'd like to have a SQL statement which can accept parameters:
SELECT {0} FROM {1} WHERE sampleId = {2}

0 is the numbers, 1 is the CSV file name and 2 is sampleId is what we looking for. The other solution which came into my mind is to look all the columns after the last fix column. I don't know is it possible or not, just thinking out loud.
Please be descriptive, my SQL knowledge is basic. Any help is really appreciated.

A: So finally managed to solve it. The code is in VB.NET, but the logic is quite clear.
 Private Function GetDataFromCSV(sampleIds As Integer()) As List(Of KeyValuePair(Of String, List(Of Integer)))
           Dim dataFiles() As String = System.IO.Directory.GetFiles(OutputFolder(), "*.CSV")
           Dim results As List(Of KeyValuePair(Of String, List(Of Integer))) = New List(Of KeyValuePair(Of String, List(Of Integer)))

          If dataFiles.Length > 0 And sampleIds.Length > 0 Then
                  For index As Integer = 0 To sampleIds.Length - 1
                       If sampleIds(index) > 0 Then
                            For Each file In dataFiles
                                 If System.IO.File.Exists(file) Then
                                      Dim currentId As String = sampleIds(index).ToString()
                                      Dim filename As String = Path.GetFileName(file)
                                      Dim strPath As String = Path.GetDirectoryName(file)

                                   Dim conn As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strPath & "; Extended Properties='text; HDR=Yes; FMT=Delimited'")

                                   Dim command As OleDb.OleDbCommand = conn.CreateCommand()
                                    command.CommandText = "SELECT * FROM [" & filename & "] 'WHERE Sample ID = " & currentId

                                   conn.Open()
                                   Dim reader As OleDb.OleDbDataReader = command.ExecuteReader()
                                   Dim numberOfFields = reader.FieldCount
                                   While reader.Read()
                                            If reader("Sample ID").ToString() = currentId Then 'If found write particle data into output file
                                                 Dim particles As List(Of Integer) = New List(Of Integer)
                                                 For field As Integer = 0 To numberOfFields - 1
                                                     particles.Add(CInt(reader(field.ToString())))
                                                 Next field
                                                 results.Add(New KeyValuePair(Of String, List(Of Integer))(currentId, particles))
                                            End If
                                       End While
                                       conn.Close()
                                  End If
                             Next file
                    End If
               Next index
               Return results
          Else
               MessageBox.Show("Missing csv files or invalid sample Id(s)", "Internal error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
         End If
         End Function


text:
Q: How to create Polls on LinkedIn I was able to successfully create regular Text, Image and Video Shares on LinkedIn using the Shares API.
Now, I also need to create Polls on LinkedIn and I've searched so much around but can't seem to find any documentations on how to do that using the Shares API.
Does LinkedIn support creating Polls programmatically? If yes, can anyone suggest API documentations for this?
Thanks.

A: LinkedIn recently added a possibility to create polls with their Posts API.
The details are on a dedicated page, but the gist is this payload:
POST https://api.linkedin.com/rest/posts

{
 "author": "urn:li:organization:2414183",
 "commentary": "test poll",
 "visibility": "PUBLIC",
 "distribution": {
   "feedDistribution": "MAIN_FEED",
   "targetEntities": [],
   "thirdPartyDistributionChannels": []
 },
 "lifecycleState": "PUBLISHED",
 "isReshareDisabledByAuthor": false,
 "content": {
     "poll": {
       "question" :"What is your favorite color?",
       "options" : [ { "text" : "Red" }, { "text" : "Blue" }, {"text": "Yellow"}, {"text": "green"} ],
       "settings" : { "duration" : "THREE_DAYS" }
     }
 }
}


text:
Q: PaperClip - How to skip an attachment from being saved based on dimentions I have a rails 3 app with paperclip. If the attachment is an image, and the image width or height is under 100, I want to skip it from being saved.
I have the following in the model:
  validate :file_dimensions, :unless => "errors.any?"

  def file_dimensions
    dimensions = Paperclip::Geometry.from_file(attachment.to_file(:original))
    if dimensions.width < 100 || dimensions.height < 100
      errors.add(:file,'Width or height must be at least 100px')
    end
  end

Problem is I don't want to raise an error because then the entire job fails, I just want paperclip to skip that attachment from being saved, and not stop the entire process.

A: You claim you don't want to raise an error so you can save.  In that case just use a :before_validate callback:
before_validate :check_file_dimensions

def check_file_dimensions
  if attachment.dirty?
    dimensions = Paperclip::Geometry.from_file(attachment.to_file(:original))
    if dimensions.width < 100 || dimensions.height < 100
      attachment.clear
    end
  end
end

Of course if you want to show an error message to the user you will need to pass it through in an instance var or something (obviously you can't use errors or it won't save).
The attachment.dirty? line above is a small enhancement so that you aren't constantly checking the attachment every time you save the model, but only when a new attachment is uploaded.  This is particularly important if you store files on S3.

A: Why are you not wanting to save it?  If you want it to keep going, then an easy solution is to not make it a validation, but can put it in like a before_save, before_create, or after_save callback.
Probably the easiest thing would be in a before_save, if it doesn't pass your tests, just delete it, then save.

A: You can just rescue from ActiveRecord::RecordInvalid


text:
Q: Suggestions needed for threading and process architecture for search engine software The software is a classic search engine. There is one portion of the app that is tasked with crawling/collecting data, and there is another that takes that data and builds an index or database. The final portion handles queries from clients, and performs a search on the data, before retrieving the results.
The specific engine that I'm discussing is one where the data is frequently updated (at least once per minute) so the queries must always be operating on the latest data.
My question is simple. Should these three tasks be handled by three separate processes, or a single process with multiple threads dedicated to each?
The main reason for my question is regarding the best way to partition memory. If the searcher has to update the available data for the indexer, and the indexer has to update the datasets for the query handler, would it make sense for them all to live under the same process and have the same address space? Or would it be acceptable to have separate processes that use shared memory mapped files?
I am leaning towards separate processes so that each can live on a different machine, enabling clustering, distribution, etc. But in terms of raw speed for smaller datasets, would a consolidated approach be preferred?
The OS is Windows, the language is C++.

A: I'm no expert but I would be leaning towards the seperate processes approach as that gives the best flexibility, ability to scale, easy to manage (restarting one service wouldn't afect the others) and performance.
I'd also be tempted to consider different databases for the different tasks as well.
If you take the approach of having one component doing one job - and doing it well, then it makes sense to apply this principle to the DB as well.
I it depends on where you see the performance bottle-knecks being as to how you do that.
I'm thinking along the lines of an initial collection area, perhaps a staging area (sorting, etc) and a final area dedicated to fast access and searching.
SQL to SQL batch processes / ETL would give best performance I guess.
Thinking it through - I'd build 3 seperate application that together formed the solution.  That would also allow you to use different technology for different tasks if you really wanted to.  Allows a more flexible maintenance path.


text:
Q: Expectation of the absolute value in a sequence of Bernoulli trials On this tweet:

Can I get some help in understanding the proposed solution by N. Taleb:

*

*It is not clear how he describes success, i.e. $n-x$ to come up with $\binom{n}{n-x}.$ It almost seems as though $x$ should correspond to the number of tails, according to the formulation of the question, but I bet it's not...

*He applies LOTUS (?) in the equation
$$\mathbb E(|X|)=\sum_{x=0}^n\Big\lvert x-\frac{n}{2}\Big\rvert \phi_n(x)$$
but where does the term $\lvert x-\frac{n}{2}\rvert$ come from?

*Where do the gamma functions come from?

A: The solution you cite is approximate, and we can avoid the gamma function (I also believe that solution has some errors).  We are tossing a fair coin independently $n$ times, coding the outcomes as $+1$ or $-1$, respectively.  Summing this up we get $X_n$. Let $R_n$ be the number of times we throw $+1$, then we find that $X_n=2 R_n-n$, and $R_n$ has a binomial distribution with $p=1/2$. The expectation of $|X_n|$ is then
$$ \DeclareMathOperator{\E}{\mathbb{E}}
   a_n=\E |X_n | = \E |2R_n-n| = 2^{-n}\sum_{k=0}^n |2k-n| \binom{n}{k}
$$ (the solution you cited seems to have missed a factor of 2 here. Thats why they get 1/2 in their binomial coefficient, so need to use gamma function).
This looks complicated, because of the absolute value, so let us try to rewrite without the absolute value. But first note that we have $a_{2m}=a_{2m-1}$. This is because the walk can never reach 0 (the starting point) after an odd number of steps. Therefore we only need to study the case $n=2m$, an even number of steps.
Remember the symmetry of the binomial coefficient, that $\binom{n}{k}=\binom{n}{n-k}$, also the absolute value term is symmetric about the midpoint of the series of terms. Write now $n=2m$. Then the above sum can be written as
$$
   2\cdot 2^{-n} \sum_{k=0}^{m} \left( 2(m-k)\right) \binom{2m}{k}
$$
which we can sum exactly to get (I got tired and used maple)
$$
   2\cdot 2^{-n} (m+1) \binom{2m}{m+1}
$$
Now we could rewrite this using gamma functions, but there is no need to.
What is the limit of this absolute expected value when $n \to\infty$? By using Stirling approximation we can see it must be $\infty$, but some asymptotic expression would be more useful. First, let us simplify the above expression to something that is obviously asymptotically equivalent.
$$
(n+\frac12) \cdot 2^{-n} \cdot \binom{n}{n/2+1}
$$
and using Stirling's approximation we can find a first order asymptotic approximation as
$$
    \E |X_n| \sim \sqrt{\frac{2 n}{\pi}}
$$
so after $n$ steps the expected distance from the origin is of the order of $\sqrt{n}$. To some further terms we can find the asymptotic approximation
$$
\E |X_n| \sim \sqrt{\frac{2}{\pi}}\left\{ \sqrt{n} - \frac74 \frac1{\sqrt{n}} +\frac{109}{32}(\frac1{\sqrt{n}})^3 - \frac{865}{128}(\frac1{\sqrt{n}})^5 - \pm \dotsm \right\}
$$


text:
Q: How do i execute shell script using java How do I execute shell script file with an input parameter like "./flows.sh suspend" and print the the result to a file using java in linux?

A: This is a simple code to execute the shell script and read its output:
import java.io.*;

public class Test {
  public static void main(String[] args) throws Exception {
    String[] command = { "./flows.sh", "suspend" };
    Process process = Runtime.getRuntime().exec(command);
    BufferedReader reader = new BufferedReader(new InputStreamReader(
        process.getInputStream()));
    String s;
    while ((s = reader.readLine()) != null) {
      System.out.println("Script output: " + s); // Replace this line with the code to print the result to file
    }
  }
}

To print it to a file, just replace the System.out.println for the code to write into a file

A: You can use the  JSCH API:
http://www.jcraft.com/jsch/examples/Shell.java.html
http://www.jcraft.com/jsch/examples/Exec.java.html
Bye!


text:
Q: Check the value exist in codeigniter I am trying to make a condition of getting value but it is not working actually I have 3 pages and the layout of the page is same only the form is changed so what I am trying to do is if pagename?page is set then do something otherwise show recent activities in normal php it is easy to do by using isset() function but in codeigniter the isset function is not working here is what i did
<?php
    if($this->input->get('page') == true) {
        if($this->input->get('page')  == true && $this->input->get('page') == 'page1') {
            echo 'page 01';
        }
        if($this->input->get('page')  == true && $this->input->get('page') == 'page2') {
            echo 'page 02';
        }
    } else {
        //normal activities page to be shown
    }
?>

This is what I am trying to do but nothing is working for me like it's directly jumping to else condition can anyone help me our please if not clarified do ask me please.
Thank You and hoping to learn

A: Try This :
if($this->input->get('page')) {
    if($this->input->get('page') == 'page1') {
        echo 'page 01';
    } else if($this->input->get('page') == 'page2') {
        echo 'page 02';
    }
} else {
    //normal activities page to be shown
}

A: Try this ;)
switch($this->input->get('page')) {
  case 'page1':
    echo 'page 01';
    break;

  case 'page2':
    echo 'page 02';
    break;

  default:
  /* normal activities page to be shown */
}

A: In View
<a href="<?php echo  base_url() ?>index.php/controller_name/order/one">Page One
<a href="<?php echo  base_url() ?>index.php/controller_name/order/two">Page two
<a href="<?php echo  base_url() ?>index.php/controller_name/order/three">Page three

In Controller
public function order($value)
{
    switch ($value) {
        case 'one':
            $page = 'one';
            break;

        case 'two':
            $page = 'two';
            break;

        case 'three':
            $page = 'three';
            break;

        default:
            $page = 'three';
            break;
    }
    echo $page;
}


text:
Q: Rails 4.2 is serving stylesheets twice in development mode I'm started a new project:
rails new test-styles
cd test-styles
rails generate controller CreditCards open
rails server

This is the produced HML
<link rel="stylesheet" media="all" href="/assets/credit_cards-1ed56f25de9e08bdac6a0e4c565de8ec.css?body=1" data-turbolinks-track="true" />
<link rel="stylesheet" media="all" href="/assets/application-5760c24f7be45363d79a66235e9d6b39.css?body=1" data-turbolinks-track="true" />

And Here the content of each css:
application.css
/* line 4, /.../test-styles/app/assets/stylesheets/credit_cards.scss */
body {
  background: red;
}

credit_card.css
/* line 4, /.../test-styles/app/assets/stylesheets/credit_cards.scss */
body {
  background: red;
}

As we can see application.css is included credit_cards so why is credit_cards also included in the page?
This is very annoying because I would like to use the gem twitter-bootstrap-rails and also less variables. Of course if credit_cards is compile alone, it will fail...
I'm new to RoR, maybe I messed something...

A: You paste it wrong... Rails's application css has lines:
*= require_tree .
*= require_self
*/

These lines use all css files in directory assets/stylesheets of your application. More information about it is here.


text:
Q: Python groupby with single line if else statement I would like to apply a single line if else statement to a group in my data frame, but unsure how to map it.
My data looks like this:
    user                in               out location  overlap    Time    overlap_new
0    ron  12/21/2021 10:11  12/21/2016 17:50     home     0  4:19:03      'complete'
1    ron  12/21/2016 13:26  12/21/2016 13:52   office     2  0:25:28      'complete'
2  april   12/21/2016 8:12  12/21/2016 17:27   office     0  8:15:03      'none'
3  april  12/21/2016 18:54  12/21/2016 22:56   office     0  4:02:36      'none'
4   andy   12/21/2016 8:57  12/21/2016 12:15     home     0  2:59:40      'partial'
5   andy   12/21/2016 8:57  12/21/2016 12:15     home     1  2:59:40      'partial'

I would like the overlap to be a single value as shown in overlap_new, based on the value in overlap.
Here is my code:
s = sample.groupby('user')['overlap']
sample.loc[:,'overlap_new'] = s.apply(['partial' if ele == 1 else 'complete' if ele ==2 else 'none' for ele in sample['overlap']])

How do I apply a groupby to a single if else line?

A: Use GroupBy.transform with test values by Series.any for match at least one value per groups:
f = lambda x: 'partial' if (x == 1).any() else 'complete' if (x == 2).any() else 'none'
sample['overlap_new'] = sample.groupby('user')['overlap'].transform(f)
print (sample)
    user                in               out location  overlap     Time  \
0    ron  12/21/2021 10:11  12/21/2016 17:50     home        0  4:19:03
1    ron  12/21/2016 13:26  12/21/2016 13:52   office        2  0:25:28
2  april   12/21/2016 8:12  12/21/2016 17:27   office        0  8:15:03
3  april  12/21/2016 18:54  12/21/2016 22:56   office        0  4:02:36
4   andy   12/21/2016 8:57  12/21/2016 12:15     home        0  2:59:40
5   andy   12/21/2016 8:57  12/21/2016 12:15     home        1  2:59:40

  overlap_new
0    complete
1    complete
2        none
3        none
4     partial
5     partial


text:
Q: PHP stops executing with no error I'm administering a system used by around 100 users. Everything is working fine except for one user. When that user logs in, the source will only output about 70 lines og html and then just stop executing. PHP show no errors whatsoever, and nothing is shown in the error log. Errors is enabled in the script.
If i remove some lines, in the html, it will execute more PHP, but then still stop at about 70 lines in the source code.
This, as I said, only happens for one user.
Does anyone have an idea about what could be going wrong here?

A: if error is not displaying it means the error display or error reporting is off in php.ini you can turn it on by the following php functions
<?php
    error_reporting(E_ALL);
    ini_set('display_errors','On');
?>

place above functions in the starting of your file and it will output error if any occurs.


text:
Q: Javascript not calling my PHP the way I expect it Can't seem to know what am I missing here. Javascript returns 0. Here are my files
index.html

<title> New </title>

<input type="text" id="desc" placeholder="Description">

<button onclick="addParticular()">Submit</button>

 Response goes Here

alpha.js
function addParticular()
{
    var desc = document.getElementById("desc").value;

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML = this.responseText;
        }
    };

    xmlhttp.open("GET", "new.php?q='" + desc + "'", true);
    xmlhttp.send();
}

new.php
<?php
include_once("conn.php");

$q = $_REQUEST["q"];
echo $q + " Hello World!";
?>

Why is the response 0, and not [What's written in the textbox] + Hello World?
How do I see the opened URL by XMLHttp?
Should I really use $_REQUEST instead of $_GET?

A: You need to concatenate in PHP using a dot:
<?php
    include_once("conn.php");
    $q = $_REQUEST["q"];
    echo $q . " Hello World!"; // Instead of `echo $q + " Hello World!";`

A: In PHP, you concatenate with the . operator. You have:
echo $q + " Hello World!";

This will attempt to add the two as numbers. You're lucky to get 0.
You should use:
echo $q . " Hello World!";

More simply, you can use:
echo "$q Hello World!";

which is marginally more efficient, and more readable.

A: Error in this line-
echo $q + " Hello World!";

It should be -
echo $q . " Hello World!";

A: A quick quote from the documentation of PHP strings:

Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this.

The expression $q + " Hello World!" is evaluated in numeric context. The strings are converted to numbers then added. The conversion of strings to numbers is explained in the same documentation page:

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).

That should explain why the result you get is 0 (zero) and also how to fix it.


text:
Q: The property 'xyz' can't be unconditionally accessed because the receiver can be 'null' I was upgraded my flutter project version to the latest (2.5.3). then occurred some errors due to unsupported null-safety. I had fixed many but still, haven't any idea to fix following null-safety to error,
Code
itemBuilder: (context, suggestion) {
 return ListTile(
          subtitle: Text(
            suggestion.stateA == null || suggestion.stateB == null
                ? '${suggestion.city}, ${suggestion.country}'
                : '${suggestion.city}, ${suggestion.state}, ${suggestion.country}',
            style: Theme.of(context).textTheme.bodyText,
          ),
        );
 }

Errors
The property 'stateA' can't be unconditionally accessed because the receiver can be 'null'.
The property 'stateB' can't be unconditionally accessed because the receiver can be 'null'.
The property 'city' can't be unconditionally accessed because the receiver can be 'null'.
The property 'country' can't be unconditionally accessed because the receiver can be 'null'.

how add the check null-safety above code?
I already try with ! & ? Operator but it does not work for me
(i.e. suggestion!.state)


text:
Q: What is the solution for rejected applications This is respon from Apple :
Guideline 3.1.1 - Business - Payments - In-App Purchase
We noticed that your app includes or accesses paid digital content, services, or functionality by means other than in-app purchase, which is not appropriate for the App Store. Specifically:

*

*The digital content can be purchased in the app using payment mechanisms other than in-app purchase.

Next Steps
The paid digital content, services, or subscriptions included in or accessed by your app must be available for purchase using in-app purchase.
If you have any additional information to provide regarding the digital content and services in your app and how the guidelines apply to them, please reply to this message in Resolution Center and let us know. If there is information you'd like us to consider in our review of future submissions, please feel free to include it in the App Review Information section of App Store Connect.
Resources

*

*See how to implement in-app purchase with the StoreKit framework.

*Review step-by-step instructions for creating in-app purchases in App Store Connect.

*Learn more about our policies for apps that offer paid digital content and services.

Do you have solution  ?

A: The Apple Store Guidelines state this:

3.1.1 In-App Purchase:
[...] Apps and their metadata may not include buttons, external links, or other calls to action that direct customers to purchasing mechanisms other than in-app purchase.

As far as I am aware, there are no exceptions.
So the ONLY solution to your problem is to remove the code in your app that uses other payment mechanisms.


text:
Q: Unknown column error in where clause, using MySQL and Java Following is my code line :
ResultSet rs3 = stmt6.executeQuery("SELECT * FROM ShopSystem.Order where s_id="+s_id+" AND status="+Pending);

I am getting the following error :
Unknown column 'Pending' in 'where clause'

What could be the reason... I cant get through it..

A: No doubt, status is a string, so it needs to be compared to a string.  Use delimiters:
SELECT * FROM ShopSystem.Order where s_id="+s_id+" AND status='"+Pending+"'"

Or better yet, learn how to write code that uses parameter substitution for putting parameter values into SQL strings.

A: Change it to
AND status = '" + Pending + "'"

You need to put the string in quotes. Otherwise the DB thinks you mean a column name.
But actually you should use Prepared Statements. Then you don't need to patch the queries together like this and you don't worry about parameters and escaping them...

A: Don't make concatenation ! Use prepared statements
PreparedStatement stm = conn.prepareStatement("SELECT * FROM ShopSystem.Order where s_id = ? AND status = ?");
stm.setInt(1, s_id);
stm.setString(2, Pending.name());
ResultSet rs = stm.executeQuery();

A: you must use the PreparedStatement in this case
// use the ? for the 2 entries values
    String selectSQL = new String("SELECT * FROM ShopSystem.Order where s_id=? AND status=?")
    preparedStatement = dbConnection.prepareStatement(selectSQL);
// in order you must incialise them here
                 preparedStatement.setString(1, "s_id");
                preparedStatement.setString(2, "Pending");
//execute your resultset    `enter code here`
ResultSet rs = preparedStatement.executeQuery();


text:
Q: Azure DevOps CI agent error while excuting npm install I have configured Azure DevOps CI pipe for Angular 13 WEB APP. The Node version is 14.17
and NPM 6.14.13 used azure agent Ubuntu 20.04 LTS. Below you can see what I included to my build
resources:
  repositories:
  - repository: self
    type: git
    ref: refs/heads/development
jobs:
- job: Job_1
  displayName: Agent job 1
  pool:
    vmImage: ubuntu-20.04
  steps:
  - checkout: self
  - task: NodeTool@0
    displayName: Use Node 14.17.x
    inputs:
      versionSpec: 14.17.x
  - task: CmdLine@2
    displayName: Install Anguler
    inputs:
      script: npm install -g @angular/cli
  - task: Npm@1
    displayName: npm install
    inputs:
      verbose: false
  - task: CmdLine@1
    displayName: Run ng
    inputs:
      filename: ng
      arguments: build
  - task: PublishBuildArtifacts@1
    displayName: 'Publish Artifact: dist'
    inputs:
      PathtoPublish: dist
      ArtifactName: dist

The problem is when it comes to npm install returning following errror
2022-07-05T08:50:59.0085431Z npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
2022-07-05T08:50:59.0086707Z npm ERR! code ERESOLVE
2022-07-05T08:50:59.0087276Z npm ERR! ERESOLVE could not resolve
2022-07-05T08:50:59.0087839Z npm ERR!
2022-07-05T08:50:59.0088385Z npm ERR! While resolving: ng-select2@1.4.1
2022-07-05T08:50:59.0089028Z npm ERR! Found: select2@4.1.0-rc.0
2022-07-05T08:50:59.0089656Z npm ERR! node_modules/select2
2022-07-05T08:50:59.0090324Z npm ERR!   select2@"^4.1.0-rc.0" from the root project
2022-07-05T08:50:59.0091059Z npm ERR!
2022-07-05T08:50:59.0091557Z npm ERR! Could not resolve dependency:
2022-07-05T08:50:59.0092182Z npm ERR! peer select2@"^4.0.x" from ng-select2@1.4.1
2022-07-05T08:50:59.0092812Z npm ERR! node_modules/ng-select2
2022-07-05T08:50:59.0093479Z npm ERR!   ng-select2@"^1.4.1" from the root project
2022-07-05T08:50:59.0094043Z npm ERR!
2022-07-05T08:50:59.0094606Z npm ERR! Conflicting peer dependency: select2@4.0.13
2022-07-05T08:50:59.0095230Z npm ERR! node_modules/select2
2022-07-05T08:50:59.0095824Z npm ERR!   peer select2@"^4.0.x" from ng-select2@1.4.1
2022-07-05T08:50:59.0096597Z npm ERR!   node_modules/ng-select2
2022-07-05T08:50:59.0097203Z npm ERR!     ng-select2@"^1.4.1" from the root project
2022-07-05T08:50:59.0097691Z npm ERR!
2022-07-05T08:50:59.0098212Z npm ERR! Fix the upstream dependency conflict, or retry
2022-07-05T08:50:59.0098870Z npm ERR! this command with --force, or --legacy-peer-deps
2022-07-05T08:50:59.0099604Z npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
2022-07-05T08:50:59.0102846Z npm ERR!
2022-07-05T08:50:59.0103438Z npm ERR! See C:\npm\cache\eresolve-report.txt for a full report.
2022-07-05T08:50:59.0103769Z
2022-07-05T08:50:59.0104331Z npm ERR! A complete log of this run can be found in:
2022-07-05T08:50:59.0105127Z npm ERR!     C:\npm\cache\_logs\2022-07-05T08_50_56_733Z-debug-0.log
2022-07-05T08:50:59.1265632Z ##[warning]Couldn't find a debug log in the cache or working directory
2022-07-05T08:50:59.1289161Z ##[error]Error: Npm failed with return code: 1
2022-07-05T08:50:59.1322525Z ##[section]Finishing: npm install

Can anyone help me on this?

A: This has nothing to do with the Azure DevOps CI pipeline per se. You have a problem with https://nodejs.org/en/blog/npm/peer-dependencies. In summary, an upstream package relies on a supporting package being installed downstream by the hosting application and versions can be quite restricted. The workaround (as per the error message) is to use npm install --legacy-peer-deps https://docs.npmjs.com/cli/v7/using-npm/config#legacy-peer-deps . You can find out what the peer dependencies for a package are by using the command npm info ng-select2 peerDependencies or specific version npm info ng-select2@1.4.1 peerDependencies.
Result below. Notice that ng-select2@1.4.1 relies on select2@^4.0.x.
Have you installed select2@^4.0.x ?
{
  '@angular/common': '^13.0.0',
  '@angular/core': '^13.0.0',
  '@types/jquery': '3.5.x',
  '@types/select2': '^4.0.x',
  select2: '^4.0.x',
  jquery: '3.5.x'
}

Installing the correct version of npm install select2@^4.0.0 should solve your problem.
In your package.json:
"select2": "^4.0.0"


text:
Q: Simulating SMS on Android Devices when developing Is there a way to send an SMS from te DDMS in Eclipse to my Android phone. The emulator control is disabled when I'm running my physical phone. I can only sent a SMS to the emulator.

A: Yeah it doesn't seem like it is possible. With the emulator you can do:
telnet localhost 5554
sms send +12345 A quick brown fox.

But if you try it with a real phone (well I tried a Galaxy S2) it just closes the connection. Of course it's always possible Samsung screwed up the code somewhere, but as common as that is, I think in this case the functionality is probably disabled for non-debug ROM builds.

A: The following few steps should get you up into simulating an incoming sms in an Android Emulator.
Requirements:
1.Make sure that you have the telnet client in you PC whether it is Windows or Linux.Google around on how to install one if it is not already installed on your PC.
Steps To Emulating an incoming sms
(a) open you CMD prompt and Enter the command:
telnet
For now I am Demonstrating using  Windows 7 ,so you will get

Welcome to Microsoft Telnet Client
Escape Character is 'CTRL+]'
Microsoft Telnet>

(b)Assuming that your Emulator is already started.And while still on the CMD,type:
 o localhost 5554

this should open a connection to the emulator.
(c)To Emulate an incoming sms from a number say 0123456  type:
sms send 0123456 Your Message

You should be able to get the message in your android emulator inbox.Thats all Folks.

A: I am not sure about what versions of android or adb support this you can try
adb emu sms send [from] [message]

so for example
adb emu sms send "+1555....." "Your message goes here....."

Hope this helps.
PS: I think this only works with emulators.

A: The newest way in 2019:
I hope in 2020 we'll be able to simulate SMS on real devices (if it's legal)

A: Use some free SMS sending website to get the Intent of android.provider.Telephony.SMS_RECEIVED. means send a SMS to your mobile number using free sms service.

A: telnet localhost 5554
sms send +905xxxxxxxxx "Type your message here, between quotes"

A: Indeed, it is quite easy with Android emulator to simulate an incoming sms,there are loads of tutorials for that for example: http://www.anddev.org/video-tut_-_simulating_incoming_phone_calls_-_sms_via_cmd-t135.html
But i'm not sure that you can do that with a phone. Using the Command line is only for emulator purposes. Though you could try to find the port on which your phone is connected and use the procedure with telnet to test it.


text:
Q: Jquery function does not work after press the space button once I am working on a simple jquery example. I want to sum all numbers that typed by user. The user must press enter after typed the number and if user presses the spacebar the result will be shown on the screen. My problem is, after i pressed the spacebar once no more summation process is executing. I have try the possibles ways that i thought but i could not fix it. Anyone one can help me please ?
<script type="text/javascript">
var typedNumber=0;
var sum = 0;
var textValue = $('#textbox').val();

$(document).ready(function(){
    $('#textbox').keyup(function(event){

            if(event.keyCode == 13){
                textValue = $('#textbox').val();
                typedNumber = parseInt(textValue);
                sum = sum + typedNumber;
                $('#textbox').val("");
            }

            if(event.keyCode == 32 ){
                alert("Summation has been finished!, Sum = "+sum);
                $('#resultMessage').html(sum);
                sum = 0;
                typedNumber = 0;
            }

    });

});
</script>

A: I'll suggest to check if the value in the input field is a number.
sum = 0;
$(document).ready(function(){
    $('#textbox').keyup(function(event){
        if(event.keyCode == 13){
            var value = parseInt($('#textbox').val());
            if(!isNaN(value)) {
                sum = sum + value;
            }
            $('#textbox').val("");
        }
        if(event.keyCode == 32 ){
            alert("Summation has been finished!, Sum = "+sum);
            $('#resultMessage').html(sum);
            $('#textbox').val("");
            sum = 0;
        }
    });
});

A: You must first define the sum variable before you use it. Also, you should use preventDefault within the keyup handler
Example:
http://jsfiddle.net/9Q3dJ/


text:
Q: Dynamically change the text direction in ace editor I am trying to update the text direction dynamically in the ace editor to "LTR" or "RTL"  depending on what is entered by the user.
I am listening to change event on the ace editor and writing the following code after going through the ace.js
scope.editor.session.$bidiHandler.setTextDir(_isNewValueRTL);
scope.editor.session.$bidiHandler.updateBidiMap();

_isNewValueRTL is a boolean. I don't see it working.
Any help will be appreciated

A: Ace currently doesn't have setTextDir method, it has support for line based direction
https://github.com/ajaxorg/ace/pull/3400 that works by adding 'RIGHT-TO-LEFT EMBEDDING' (U+202B) to the line
to use that include ext-rtl.js
editor.setOption("rtlText", true)

then to change the direction of cursor line call

<script src=https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.1/ace.js ></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.1/ext-rtl.js ></script>

<script>
debugger
editor = ace.edit(null, {
  value: " left\n\u202B right\n\n try press ctrl-alt-shift-r or ctrl-alt-shift-l ",
  rtlText: true,
})
document.body.appendChild(editor.container)
editor.container.style.cssText = "height: 150px; width: 400px; outline: solid"

</script>

editor.session.$bidiHandler.setRtlDirection(editor, true)

If you need some other functionality then open a feature request to ace https://github.com/ajaxorg/ace/issues/new

A: Try adding this CSS to your ace_line class
.ace_line {
    direction: ltr;
    unicode-bidi: bidi-override;
}

This sould change the direction of the text

A: editor.setOption("rtlText", true)
if rtlText doesn't work, just use rtl
editor.setOption("rtl", true)