text:
Q: Регулярные выражения: поиск подстроки если после неё нет определённого выражения У меня есть следующее регулярное выражение:
(?:\d+[-, \.]*)+\s*(?:нед|н)?[\. ]*, оно применяется к строке: 3-4 нед. Математический анализ 1 гр
При поиске подстроки находится 2 результата: 3-4 нед.  и 1  (часть от "1 гр"). Я бы хотел узнать, как мне искать подстроку таким образом, чтобы оно находило только ту часть, после которой не идёт выражение (подгруппа|подгруп|подгр|п\/г|группа|гр)?
Я пробовал использовать Negative Lookahead:
(?:\d+[-, \.]*)+\s*(?:нед|н)?[\. ]*(?!.*(подгруппа|подгруп|подгр|п\/г|группа|гр))

но при данном выражении у меня при совпадении с 'гр' все другие совпадения тоже становятся ненайденными, а если в нём убрать поиск всех символов в начале (.*), то оно вообще почему-то перестаёт работать.

A: Вместо .* нужно использовать только такой шаблон, который может встретиться до исключаемых слов.
Вы можете использовать
\d+(?:[-,\s.]\d+)*\s*н(?:ед)?(?![.\s]*(?:подгруппа|подгруп|подгр|п\/г|группа|гр))[.\s]*

См. пример работы регулярного выражения. Подробности:

*

*\d+ - одна или более цифр

*(?:[-,\s.]\d+)* - ноль и более последовательности -, , .` или пробельного символа, за которым следует одна или более цифр

*\s* - ноль и более пробельных символов

*н - буква н

*(?:ед)? - опциональная подстрока ед

*(?![.\s]*(?:подгруппа|подгруп|подгр|п/г|группа|гр)) - сразу справа не должно быть ноля и более точек и пробельных символов, после которых идёт подгруппа, подгруп, подгр, п/г, группа и гр

*[.\s]* - ноль и более пробельных символов и точек.


text:
Q: Open() is used for creating a file and opening a existing file.Could someone tell the difference? I have created a file name c.txt with open() and if I want to make changes in the file then I am going to open with open() then what is the difference?
Could someone please help me out.
#include "stdafx.h"
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ofstream myfile;
    myfile.open("c.txt");

    myfile << "gm all";
    myfile.close();
}

A: It's very simple!
ofstream: Output stream.
ifstream: Input stream.
Create the file with ofstream, and open it with ifstream.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stable webcomponent-like templating engine with data binding? I'm looking for good frontend "template engine" of some sort. I've spent 2 days researching. I've looked into Polymer (by Google), Reactjs (by Facebook), Skatejs (by Atlassian), Rivet (used by Dell) and Angularjs directives (by Google).
Now, I need some help.
Desired features:

*

*data binding (one or two directional)

*parsing custom elements, ex: <my-element></my-element> that output some predefined html

*the custom elements should have the ability to wrap around nested elements, ex: <my-element>
My title
</my-element> that output the predifed html with the nested tag at the specified location inside that html (similar to webcomponents and Polymer)

*minimum abstraction and no new syntax if possible (except some mustache-like templating may be)

*a bonus would be html imports

Additionally:

*

*should be stable

*should be simple to use, simply drop in (not-in-the-way), not requiring some certain app structure

*should do just template-engine things (bad example: Angular does abstract things too much, also include some jquery-like thing, etc)

My findings so far:
I found that Polymer is unstable with the shadow-dom and not working properly without it. Reactjs defines its own language which is unnecessary for me, react also requires nested components to be react components again, and don't allow to be html (limitation due to the custom language). Skatejs doesn't have data binding. Rivet has unstable custom elements and no ability to wrap nested elements. Angular directives are introducing the whole angular js abstraction, which is a bit too much only to get nice templating working.
My question
Is there alternative to the libraries I've tried that match the desired features listed above? If not, can you think of a way to mash some libraries together and achieve such functionality?


text:
Q: Pagination with condition from form in laravel I want to make pagination with condition from form in laravel. but when I click page 2, there's nothing in there. the sketch is like this
pagination page 1
pagination page 2
my code in controller is like this
 public function search(Request $request){

    if($request->emotion=="all"){
        $data = Dataset::select('*')->where([
            ['category', '=', $request->category]
        ])->paginate(15);
    }
    else{
        $data = Dataset::select('*')->where([
            ['category', '=', $request->category],
            ['label', '=', $request->emotion]
        ])->paginate(15);
    }

    return view('dataset.search', [
        'data' => $data,
        'label' => $request->emotion
    ]);
}

and in route is like this
Route::post('/dataset-detail', [DatasetController::class, 'search']);
Route::get('/dataset-detail', [DatasetController::class, 'search']);

and in view like this

                                @if($data==NULL)
                                NO DATA FOUND IN HERE !
                                @else
                                    @foreach ($data as $datas)

                                        {{ $loop->iteration }}
                                        {{ $datas->tweet }}
                                        {{ $datas->text_processing }}
                                        {{ $datas->akurasi_naive }}
                                        {{ $datas->akurasi_svm }}
                                        {{ $datas->akurasi_knn }}
                                        {{ $datas->label }}
                                        @if($datas->category=="train_test")
                                            Training and Testing
                                        @else
                                            Validation
                                        @endif

                                    @endforeach
                                @endif

                    {{ $data->links() }}

how to make the paginate works with condition that I input before in form like in function search ?


text:
Q: SQL Server query: I need to increment an integer based on queries and set it I am facing the following challenge: I have a SQL command in VB.NET that is used to set unique IDs on a SQL Server table.
It looks like this:
Public Async Function CreateWiedervorlagenID() As Threading.Tasks.Task

    Dim sqlquery As String = "select distinct [id_doc], [label], [date] from [reminder]"
    Dim i As Integer = 0

    Using dbConn As New SqlConnection With {.ConnectionString = conStr}
        If Not dbConn.State.Equals(ConnectionState.Open) Then Await dbConn.OpenAsync()
            Using dbCommand As New SqlCommand With {.CommandText = sqlquery, .Connection = dbConn}
                Using dbReader As SqlDataReader = Await dbCommand.ExecuteReaderAsync
                    If dbReader.HasRows.Equals(True) Then
                        While Await dbReader.ReadAsync
                            i += 1

                            Await DoChanges(i, CInt(dbReader.Item(0)), dbReader.Item(1).ToString(), dbReader.Item(2).ToString())
                        End While
                    End If

                    dbReader.Close()
                End Using
            End Using

            If Not dbConn.State.Equals(ConnectionState.Closed) Then dbConn.Close()
        End Using
End Function

Private Async Function DoChanges(id_wv As Integer, id_doc As Integer, label As String, r_date As String) As Threading.Tasks.Task
    Dim sqlquery As String = $"update [reminder] set [id_wv] = {id_wv} where [id_doc] = {id_doc} and [label] = '{label}' and [date] = '{r_date}'"

    Using dbConn As New SqlConnection With {.ConnectionString = conStr}
        If Not dbConn.State.Equals(ConnectionState.Open) Then Await dbConn.OpenAsync()

        Using dbCommand As New SqlCommand With {.CommandText = sqlquery, .Connection = dbConn}
            Try
                Await dbCommand.ExecuteScalarAsync
            Catch ex As DbException
                Debug.WriteLine($"Fehler bei DoChanges; Fehlerbeschreibung: {ex.Message}")
                MsgBox($"Fehler bei DoChanges; Fehlerbeschreibung: {ex.Message}")
            End Try
        End Using

        If Not dbConn.State.Equals(ConnectionState.Closed) Then dbConn.Close()
    End Using
End Function

And if possible, I should rewrite this code to SQL. Unfortunately, I am still in training and have little knowledge of SQL, especially since this seems to be a rather difficult SQL command. I would definitely be very grateful for any help.

A: You can use row_number method to get the index and then you can simply update your id_wv column
update [reminder] set [id_wv] = IndexNumber from [reminder] as table1 inner join
(select [id_doc], [label], [date], ROW_NUMBER() over(order by id_doc) as IndexNumber from [reminder]
group by [id_doc], [label], [date]) as table2 on  table1.[id_doc] = table2.[id_doc]
and table1.[label] = table2.[label] and table1.[date] = table2.[date]


text:
Q: ¿alguien sabe de un script para limitar cantidad de datos traídos de una base de datos? buen dia, me gustaria saber si alguien sabe de algun script que me permita consultar solo cierta cantidad de datos de la base de datos y que le permita al usuario decidir con un botón o algo cargar mas datos, ya que al hacer el SELECT * FROM me trae todo pero  quiero que solo de entrada me muestre solo una pequeña cantidad de datos, les agradeceria me pudiesen ayudar con ese script, gracias

A: Como bien dice @OscaR en su comentario puedes utilizar LIMIT para obtener un número determinado de registros de una consulta. Para efectos de MySQL sería algo así:
$sql = "SELECT * FROM Ordenes LIMIT 30";

La consulta anterior se lee: "Selecciona toda los campos de la tabla Ordenes sólo 30 registros"

Generalmente se combina el LIMIT con ORDER BY para obtener los últimos
  "n" registros.

Lo puedes hacer de la siguiente forma:
$sql = "SELECT id FROM Ordenes ORDER BY id DESC LIMIT 30";

La consulta anterior se lee: " Selecciona el id de los últimos 30 registros de la tabla Ordenes según su id. Suponiendo que tengas 50 registros en tu tabla ordenes (id 1-50) entonces esta consulta te traería como resultado:
id
50
49
48
...
...
...
20

Si quisieras empezar "saltando" ciertos registros podrías hacerlo de la siguiente manera:
$sql = "SELECT id FROM Ordenes ORDER BY id LIMIT 30 OFFSET 10";

La consulta anterior se leería: "Selecciona el id de los últimos 30 registros después de los primeros 10 obtenidos". Entonces nuevamente si tienes un total de 50 registros (id máximo 50) entonces el resultado sería:
id
40
39
38
...
...
...
10

Para más información podrías chequear: PHP MySQL LIMIT
Actualización: En vista que no queda muy claro lo que necesitas en tu descripción de preguntas y a la sugerencia que dió en comentarios el Sr. Cedano explicaré como puedes lograr mostrar registros de manera "externa a la base de datos o al SGBD" con paginación.
La paginación consiste en tomar cierto número de registros provenientes (por ejemplo) de una consulta a base de datos y organizarlos de manera tal que no todos se muestren a la vez sino de forma segmentada.
Por ejemplo si tienes un total de 50 registros obtenidos de la consulta a base de datos puede que quieras mostrar de 10 en 10 registros en la vista bien sea por comodidad, para mejorar la interacción del usuario con tu sitio, responsividad, entre otros.

Para ello te propongo una herramienta bastante extendida denominada
  Datatables de las cuales utilizan la librería jQuery. Para más
  información puedes chequear lo siguiente: jQuery datatables

A continuación un ejemplo de implementación de las datatables:

        CÓDIGO
        PLAZAS
        ORIGEN
        DESTINO
        PRECIO
        MODIFICAR
        ELIMINAR

    <?php foreach($resultado as $result => $viaje){ ?>

            <?php echo $viaje['id'];?>
            <?php echo $viaje['numero_plaza'];?>
            <?php echo $viaje['origen'];?>
            <?php echo $viaje['destino'];?>
            <?php echo $viaje['precio'];?>

    <?php } ?>

Básicamente lo que te muestro en mi ejemplo anterior es una tabla común y corriente en HTML cuyo contenido (cada fila despues de la primera que muestra el título) será generado mediante PHP extrayendo de la variable $resultado (que es la variable que guarda el resultado de nuestra consulta a base de edatos) la información necesaria registro a registro.
Ahora donde entra la parte de paginación? En el  que se encuentra al final del archivo. Es bastante simple sólo haces referencia al id de tu tabla para inicializar la Datatable y le pasas los parametros. El parametro en particular que te interesaría (el número de filas por página) sería "lengthMenu": [4,8,12]. En mi ejemplo muestro 4, 8 o 12 registros (según lo que seleccione el usuario) por página. La datatable generará automáticamente la paginación según este parametro.
Espero sea de ayuda. Un Saludo


text:
Q: Error Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it I am getting an error

Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

I have tried everything, but nothing seems to work
After Run project, my app stopped on this method:
getPriceDataByNameProductAndSupplier

Code:
/*_____________________________ My query _______________________*/
public double getPriceDataByNameProductAndSupplier(int product_id,int supplier_id)
{

Product product=null;
double  Price_for_every_one=0.0;
String query= "select max(price_for_every_one) from product_Multi_Value where _id ="+ product_id +" and _idSupplier="+ supplier_id ;
Cursor cursor = sqLiteDatabase.rawQuery(query,null/*ew String[] {String.valueOf(product_id),
        String.valueOf(supplier_id)}*/); /*("product_Multi_Value",
                                     new String[] {"MAX(price_for_every_one) AS MAX"},"_id=? and _idSupplier=?",
                                     new String[] {String.valueOf(product_id),String.valueOf(supplier_id)},
                                     null,null,null)*/;// cursor.moveToFirst();
if (cursor !=null)
{
    cursor.moveToFirst();
    do
    {
        Price_for_every_one = cursor.getDouble(cursor.getColumnIndexOrThrow("price_for_every_one") );
        product = new Product(Price_for_every_one);
    }
    while (cursor.moveToNext());
}
return Price_for_every_one;
}

Table Creation
/_______________________ (My Table) _______________________/
   String Crete_Table_Product_For_Multi_Value = "CREATE TABLE IF NOT EXISTS product_Multi_Value(
                   Product_Type TEXT NOT NULL,product_date TEXT NOT NULL,supplier_date TIMESTAMP
                   DEFAULT CURRENT_TIMESTAMP,exp_date TEXT NOT NULL, quantity_package REAL NOT NULL,
                   number_quantity_ber_package INTEGER NOT NULL, total_of_quantity REAL NOT NULL,
                   price_for_Allquantity REAL NOT NULL, price_for_every_one REAL NOT NULL,
                   price_for_sales REAL,_id INTEGER NOT NULL, idSupplier INTEGER NOT NULL, FOREIGN
                   KEY( _idSupplier) REFERENCES Supplier(_id), FOREIGN KEY(_id) REFERENCES
                   product(_id));";
Error Log:
The error:

E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 1 columns.
  D/AndroidRuntime: Shutting down VM
  E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.ans.accouting_s_p, PID: 1349
  java.lang.IllegalStateException: Could not execute method for android:onClick
at  androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
          at android.view.View.performClick(View.java:5623)
          at android.view.View$PerformClick.run(View.java:22433)
          at android.os.Handler.handleCallback(Handler.java:751)
          at android.os.Handler.dispatchMessage(Handler.java:95)
          at android.os.Looper.loop(Looper.java:154)
          at android.app.ActivityThread.main(ActivityThread.java:6316)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
       Caused by: java.lang.reflect.InvocationTargetException
          at java.lang.reflect.Method.invoke(Native Method)
          at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
          at android.view.View.performClick(View.java:5623)
          at android.view.View$PerformClick.run(View.java:22433)
          at android.os.Handler.handleCallback(Handler.java:751)
          at android.os.Handler.dispatchMessage(Handler.java:95)
          at android.os.Looper.loop(Looper.java:154)
          at android.app.ActivityThread.main(ActivityThread.java:6316)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
       Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
          at android.database.CursorWindow.nativeGetDouble(Native Method)
          at android.database.CursorWindow.getDouble(CursorWindow.java:543)
          at android.database.AbstractWindowedCursor.getDouble(AbstractWindowedCursor.java:87)
          at com.ans.accouting_s_p.databaseTable.DataSourceProduct.getpriceDataByNameProductAndSupplier(DataSourceProduct.java:322)

A: The issue is you are trying to access the column price_for_every_one in the cursor and it doesn't exist because when you use aggregation method like MAX, MIN, SUM etc
it changed the name of the column in the result unless you use AS keyword
in your SQL  query
String query = "select max(price_for_every_one) from product_Multi_Value where _id ="+ product_id +" and _idSupplier="+ supplier_id ;

column name in the result will be
max(price_for_every_one)

not
price_for_every_one

so you can't use the column name in
Price_for_every_one = cursor.getDouble(cursor.getColumnIndexOrThrow("price_for_every_one") );

since you are selecting only one column you can access the column by its index
cursor.getDouble(0)

or you can use AS keyword in your query like this
String query = "select max(price_for_every_one) As price_for_every_one from product_Multi_Value where _id ="+ product_id +" and _idSupplier="+ supplier_id ;```

I hope this helps you


text:
Q: Incorrect use of a property or a bad init method? I'm not sure I'm using the property function correctly.
@synthesize generated;

-(id)initWithNumber:(int)FirstNumber toSecond:(int)SecondNumber;
{
    self = [super init];
    if (self) {
        generated = FirstNumber + SecondNumber;
    }
    return self;
}

The property generated is just an int. Shouldn't I be able to use a property as a global value that I can access?
Is that a valid init method?

A: You got two choices:
1) self.generated  = FirstNumber  + SecondNumber;
2)
_generated = FirstNumber + SecondNumber;

A: you have to use properties with a self. qualifier.
just replace generated = FirstNumber + SecondNumber; with
self.generated = FirstNumber + SecondNumber;


text:
Q: Puma is not working on server I have rails 5 app running on my ubuntu 14.04 server on top of nginx. But when I am trying to start the rails app its throwing error
/usr/local/lib/ruby/gems/2.3.0/gems/puma-3.6.0/lib/puma/binder.rb:266:in initialize': Cannot assign requested address - bind(2) for "example.com" port 3000 (Errno::EADDRNOTAVAIL)

A: While RAILS is not my area, this sounds like either port 3000 is already in use, or DNS is failing to resolve the hostname example.com (which I'm aware is not the actual hostname)
Check that this same system can ping the hostname, which is a quick way to tell if DNS is resolving it. If not, you can make an entry for it in the systems /etc/hosts file


text:
Q: Let $M$ be a non-zero $3\times 3$ matrix satisfying $M^3=O$ Let $M$ be a non-zero $3\times 3$ matrix satisfying $M^3=0$, where $0$ is the $3\times 3$ zero matrix. Then
$(A)\det(\frac{1}{2}M^2+M+I)\neq0$
$(B)\det(\frac{1}{2}M^2-M+I)=0$
$(C)\det(\frac{1}{2}M^2+M+I)=0$
$(D)\det(\frac{1}{2}M^2-M+I)\neq0$
This is a multiple correct choice type question.More than one may be correct answers.

My attempt:
Let $M$ be a non-singular matrix,therefore its inverse exists.
$M^3=0$
Multiply both sides by $M^{-1}$ to get,$M^2=0$.
Again multiply both sides by $M^{-1}$ to get,$M=0$
But this is a contradiction.So $M$ is a singular matrix.Its inverse does not exist.
But i dont know how to solve further.Please help me.Thanks.

A: $M^3=0$ implies $\det(M-xI)=-x^3$ (since $M$ satisfies its own characteristic equation). Decompose expression in question into linear factors:
$$\det(\frac 1 2M^2\pm M+I)=\frac 1 8\det(M-x_{\pm1}I)\det(M-x_{\pm2}I)=\frac 1 8x_{\pm1}^3x_{\pm2}^3=\frac 1 82^3=1$$ where $x_{\pm}1,x_{\pm2}$ are roots of $x^2\pm2x+2=0$ and hence $x_{\pm1}x_{\pm2}=2$.

A: If we put $M$ in Jordan canonical form, for some invertible matrix $Q$ we will have $$M=QAQ^{-1}$$
where $$A=\left(\begin{smallmatrix}0&a&0\\0&0&b\\0&0&0\end{smallmatrix}\right)$$
where $a,b$ are each $0$ or $1$ (not both $0$ since $M\neq 0$).
Hence, we write $$0.5M^2+M+I=0.5QAQ^{-1}QAQ^{-1}+QAQ^{-1}+QIQ^{-1}=$$
$$=Q(0.5A^2+A+I)Q^{-1}$$
Taking determinants, we get $$det(Q)det(0.5A^2+A+I)det(Q)^{-1}=det(0.5A^2+A+I)=1$$ since $$0.5A^2+A+I=\left(\begin{smallmatrix}1&a&\frac{ab}{2}\\0&1&b\\0&0&1\end{smallmatrix}\right)$$
The other three questions are similar.

A: All of above is really not necessary
 $$\left(\frac{M^2}{2}+M+I\right)\left(\frac{M^2}{2}-M+I\right)=I$$
It is easy from here onwards


text:
Q: Is there an iOS4 app that when clicked will perform the same function as Settings->Airplaine Mode on/off? I have issues with my iPod Touch 4G where it disconnects from the access point for no apparent reason, and I need to go into the settings app and toggle the airplane mode to get the wifi working again.
Is there an app that I could run to automatically turn the wifi off and then turn it on again so that I don't have to waste so much time opening the settings and toggling airplane mode?  I haven't been able to find one in the appstore.

A: Not without a jailbreak.  If you get a jailbreak there are various ways to do things such as switch airplane mode on/off, adjust screen brightness, turn wifi/3G on or off.  The app SBSettings is one such example.  You'd be better off diagnosing your AP problem than jailbreaking your phone for just this feature though in my opinion.


text:
Q: Set the AWS console password for IAM user with Terraform I am newbie to the Terraform and just want to ask that is there anyway to set the AWS console password for IAM user with Terraform. I am able to configure the IAM users, group, their access and secret key but couldn't find the way to set the console password. Please point me to where I can get it work. Thanks

A: Its possible to get console password for IAM USER using terraform :
Using below command :
terraform output password | base64 --decode | keybase pgp decrypt
Follow below instructions :

*

*Store password in outputs.tf file

*terraform output password > would give your encrypted password

*Now before install nodejs and node on your server and set PATH

*Now to decrypt password we need one more concept that is KEYBASE :                      https://keybase.io/

*Go this site create a account in KEYBASE from console then under Docs go to Linux/Ubuntu  and follow instructions :
Now in shell
keybase login
enter all details.

*Point to be noted :

resource "aws_iam_user_login_profile" "user_login" {
user    = "${aws_iam_user.user.name}"
pgp_key = "keybase:username"  ------------ username means: user you
created in keybase account
password_length = 10                       }

Now terraform plan
terraform apply
keybase pgp list
terraform output password | base64 --decode | keybase pgp decrypt
You would get your password :) :)

A: You can now do so by using the iam_user_login_profile resource
resource "aws_iam_user_login_profile" "foo" {
    user    = "${aws_iam_user.bar.name}"
    pgp_key = "${var.key}"
}

Note that the pgp_key is required and can be either a PGP public key or a reference to a keybase.io profile (say foobar) by passing keybase:foobar in the pgp_key variable.
The iam_user_login_profile resource exports a password attribute which is the encrypted password for an aws_iam_user.
Check the official documentation for more.

A: Setting the password via Terraform isn't really possible. Even if it were, it wouldn't be ideal practice because you'd have a password in the configuration. The better option is to let AWS set/use/create a default password that is given to the specific user in a secure way and ensure that they change it.


text:
Q: Is it possible to call Ms Graph API from an Azure AD B2C app using local accounts? I have created an App under Azure B2C tenant.
The app is using a custom sign-in/sign-up policy to log in to local users.
However, my app has an admin view, where I would want the log-in users to be able to create accounts for whoever needs access within the app. I have seen that this is possible using Azure Ms Graph API.
However, I keep getting an InvalidAuthenticationToken Error, when I try to call Ms Graph API.
 error:
    code: "InvalidAuthenticationToken"
    innerError: {date: "2021-08-11T14:25:09", request-id: "8a49ae82-a669-4bb4-af6e-b698e095dadc", client-request-id: "8a49ae82-a669-4bb4-af6e-b698e095dadc"}
    message: "Invalid x5t claim."

I couldn't find any solution online. Is this even possible? And if there's a way around it, how can I do it?
Thank you!.

A: It would help if you went into more detail on your use case.
You have a B2C local account and you want to create users in AAD or in B2C?
If in B2C, yes you can do this as per this article.
If in AAD, see here.
Make sure that your application has the correct permissions.


text:
Q: access violation writing to 2d array in c I'm trying to initialise a 2d array, and for some reason I'm getting an exception whenever I try to enter a value into the array.
I'm passing it to the function in a struct, if that makes a difference?
Here's the code:
#define board_size 10

typedef struct {
    int b[board_size][board_size];
} board;

board dead_state();     // initialise a dead board state

void main() {
    board test_board = dead_state();

    for (int i = 0; i < board_size - 1; i++) {
        for (int j = 0; j < board_size - 1; i++) {
            test_board.b[i][j] = 0;
        }
    }
}

board dead_state() {
    // generate the matrix, set all values to 0, return
    board deadboard;

    for (int i = 0; i < board_size - 1; i++) {
        for (int j = 0; j < board_size - 1; i++) {
            deadboard.b[i][j] = 0;
        }
    }

    return deadboard;
}

edit: problem solved, thanks to hyde's comment: i am blind and cannot see, apparently.

A: You have what looks like a typo.
    for (int i = 0; i < board_size - 1; i++) {
        for (int j = 0; j < board_size - 1; i++) {
            test_board.b[i][j] = 0;
        }
    }

Both loops increment i, which means i goes out of bounds. You likely meant for the inner loop to increment j, but I don't know why you're only incrementing i and j up to 8, instead of 9.


text:
Q: How to add categories to products in woocommerce programatically? I have studies the database intensively and know which all tables are updated when a category is added to a product. Is there any inbuilt woocommerce function to add categories? It updates  2 or 3 tables but want to leave it to woocommerce.
Thanks for your help.

A: I think the function you are looking for is called wp_insert_term() in WordPress core.
Woocommerce uses WordPress-taxonomy called product_cat
So if you want to add some categories for example phones:
function wpse_insert_term()
{
    wp_insert_term(
      'phones',
      'product_cat', // the taxonomy
      array(
        'description'=> 'A yummy phone.',
        'slug' => 'phone',
      )
    );
}
add_action('init', 'wpse_insert_term');


text:
Q: How long CAN account recovery take? I don't know if anyone has had a similar situation going on with their account recovery if you ever tried to use this Apple feature but this is what happened:
I was locked out of my Apple ID account because I had been hacked. Because of this, I changed my passwords numerous times, even my Apple ID for safety measures and for some reason I got a notification that someone from New York (I live in Missouri) was trying to access my account, thanks to two-step authorization, I declined the access BUT then a few days later my Apple ID said it needed me to put my password into my iPad for security purposes and my password didn't work! I write all my passwords down in a secure place and somehow my password had been changed!! I quickly tried account recovery and it said it would take a few days for Apple to send me a text message on my phone of instructions on how to fix the issue and I have yet to receive the message (it has been exactly 2 weeks and 3 days) I called Apple Support and they said all I can do is wait, because sometimes it does take more than 10 days.
Well now my iPad keeps sending me a notification on my screen EVERY 20 SECONDS saying "APPLE ID VERIFICATION, enter password" but I can't because I'm still locked out of my Apple ID and I don't know the password. I understand waiting more than 10 days, but this is ridiculous. I called Apple Support again and all they had to say was "I'm sorry but we can't help you. It does take more than 10 days sometimes for account recovery to activate." SERIOUSLY?! I also can't go to an Apple Store for help because I'm currently on vacation out of country and there is not one near by and I won't be home for another 3 weeks, and I can't wait that long since I use my iPad for work and almost everything else.
Does anyone have any information that could help me with my issue? Any information at all. Please. I am begging!


text:
Q: Consequence of the Chinese Remainder Theorem We want to prove the following:

For any $n+1$ distinct real numbers $a_0, a_1, ..., a_n$ and any $n+1$ real numbers $b_0, b_1, ..., b_n$, there exists a polynomial of degree at most $n$ taking the value $b_i$ at $a_i$ for all $i=0, 1, ..., n$.

This was discussed in a class as a follow-on from the Chinese Remainder Theorem, but I can't see how so.
Real numbers have unique prime factorisations, so I thought about considering ideals of the form $p_i \mathbb{Z}$ where $p_i$ is the $i$th prime.
Then let $p_n$ be the greatest prime that features in the prime factorisations of the $a_i$.
Then applying the CRT, but I'm not sure if this approach is misguided.
I'd be interested to see an answer/guidance on how this can be done.

A: Hint: apply CRT to the system $\ f(x) \equiv b_i \pmod{x-a_i},\,$ using that the $\,x-a_i\,$ are pairwise comaximal, since the $\,a_i\,$ are distinct.
It deserves to be much better known that Lagrange interpolation is a special case of CRT.


text:
Q: How do I tell if there are unwanted remote guests on my computer?
Possible Duplicate:
What to do if my computer is infected by a virus or a malware?

Why do I always find the strangest programs and the strangest text files all the time? All kinds of weird things happen, like my screen changes and the address line doesn't change in IE, just weird stuff. Is it me or could there really be something going on? I've never had so much trouble with any computer before and I am on a public access point where I live.
Any advice will be greatly appreciated. I either need peace of mind, or a good defence, because this is getting out of hand.

A: Firstly, Never use public access points without WPA2 encryption!!!
If you are infected (on Windows), and assuming that the infection hasn't disabled stuff, you could try running this in a command window (start->run->cmd)
netstat -ano

it should hopefully return a list of listening and active tcp/udp ports and remote addresses.
No one nowadays wants to infect your machine and not be able to communicate with it, either to control it or to siphon information from you, so this command is quite revealing, though it only shows active connections, and you might have a hard time deciphering and resolving the addresses, so shut down all other active programs such as skype first, which usually has loads of connections open.
If they only communicate once a day, then you might miss it.
Many viruses now block access to sites such as http://housecall.trendmicro.com which is a good first port of call for a scan. If you can't reach it then you are almost certainly infected with something.
Currently a nasty root kit is going around called TDSS or TD4, very difficult to remove but kaspersky.com has some useful information about it.
I don't have or use any antivirus for a decade and don't get infected.
Keep windows up to date, run behind a real firewall, don't click on unknown links or answer questions that lead to unreputable sites, and don't install stuff you can't be sure about - especially antivirus programs!
I recommend using Firefox or Chrome instead of IE, but any are OK as long as they are kept up to date.

A: It helps to know what OS you use.  But I assume you are using Windows because you are using IE.   Most of the characteristics you describe  are kind of vague.

*

*Random Text files? You should post the names and where they are located. Generally, text files are just a symptom of a bigger situation, if any.

*Screen changes? like your resolution changing? Color changing? Does it just shut off?

In general, a public access point isn't the most ideal method.  I don't think it invites criminals like parking in the wrong neighborhood however. Probably want to get the router configured to use protected wireless(WPA). They ask that you use a password of 8 or more characters.  10 or more would be my recommendation.
The best way to protect your identity is to restrict what you download. Harmless facebook games, little widgets, etc are what I'm talking about.  Keep in mind, while these folks who wrote the program are probably not after your money, the programs have that capability.
I'd also advise you download a separate internet browser for your banking, shopping, etc.  It's a small measure but anything is better than nothing.
Lastly, if you are in the US, pay the 10 dollars and get a quick copy of all your credit reports from the Big Three agencies.  Scan them annually and you should be fine.

A: Furthermore, if anyone wants to be sure they are not infected with anything while doing any online shopping or banking transactions, then I cannot recommend this highly enough:
Go to http://fedoraproject.org/en/get-fedora
Download and burn to a CD or pendrive.
Reboot the computer and configure to boot off the CD or USB pendrive into what you just created.
Every time you boot into it you'll have a brand new, free Linux operating system with a browser and firewalled connection to the net through your router or WIFI (but still only use WPA2!), and windows malware can't touch it.
(It is completely separate and won't touch the installed Windows, but you can mount the hard disks and use it to fix Windows problems without any active viruses trying to stop you.)
This is the ONLY way you can be absolutely sure that you don't have anything nasty running in the background.


text:
Q: two divs side by side with one responsive I have the following html and css.
I want the div class="webpushPowered" to have a responsive width with a min-width 35px. I want to be responsive to the buttons size.
Basically I want the div class="webpushPowered" to adjust based on the width of the div class="webpushButtons" that can increase or decrease if I have more or less texts inside the buttons.
I am only using HTML and CSS, no external code.
This code is for desktop, my problem is in mobile so please resize it so you can see what I am talking about.
The image I attached is the result of this code in a samsung galaxy S6.
this is the image of the mobile result
Thank you!

body {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 13px !important;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background: none !important;
  margin: 0;
}

.webPushIframe {
  position: absolute;
  z-index: 999999999;
  display: block;
  border: none;
  background-color: transparent;
  width: 100%;
  max-width: 450px;
  min-width: 320px;
  min-height: 130px;
  height: 100%;
}

.webPushSolicitation {
  max-width: 450px;
  min-width: 350px;
  min-height: 130px;
  background: none;
  border: 0 !important;
  box-shadow: 2px 2px 2px 2px rgba(0, 0, 0, 0.06) !important;
  -webkit-box-shadow: 2px 2px 2px 2px rgba(0, 0, 0, 0.06) !important;
}

.webPushSolicitation .webPushContainner {
}

.webPushSolicitation .webPushContainner .webPushImage {
  width: 85px;
  height: 85px;
  display: block;
  float: left;
  text-align: center;
}

.webPushSolicitation .webPushContainner .webPushImage img {
  width: 65px;
  margin: 20px;
}

.webPushSolicitation .webPushContainner .webPushTexts {
  display: block;
  float: right;
  max-width: 320px;
  min-width: 320px;
  padding: 20px 20px 0 0;
}

.webPushSolicitation .webPushContainner .webPushTexts .webPushTitle {
  font-weight: 700;
  font-weight: bold;
  margin-bottom: 10px;
}

.webPushSolicitation .webPushContainner .webPushTexts .webPushText {
  word-break: break-word;
  margin-right:10px;
  max-height: 62px;
  overflow: hidden;
}

.webPushSolicitation .webPushContainner .webPushPowered {
  width: 80px;
  height: 10px;
  display: block;
  float: left;
  font-size: 9px;
  margin-top: 28px;
  margin-left: 18px;
}

.webPushSolicitation .webPushContainner .webPushPowered a,
.webPushSolicitation .webPushContainner .webPushPowered a:link,
.webPushSolicitation .webPushContainner .webPushPowered a:hover,
.webPushSolicitation .webPushContainner .webPushPowered a:visited,
.webPushSolicitation .webPushContainner .webPushPowered a:active {
  font-size: xx-small;
  text-decoration: none;
}

.webPushSolicitation .webPushContainner .webPushPowered img {
  width: 80px;
  margin: 25px 20px 20px 20px;
}

.webPushSolicitation .webPushContainner .webPushButtons {
  display: block;
  float: right;
  margin: 20px;
}

.webPushSolicitation .webPushContainner .webPushButtons .confirm,
.webPushSolicitation .webPushContainner .webPushButtons .deny {
  border-radius: 3px;
  padding: 6px 10px;
  display: block;
  float: right;
  margin-left: 5px;
  cursor: pointer;
}

.webPushConfirmation {
  max-width: 450px;
  min-width: 160px;
  background: none;
  border: 0 !important;
  box-shadow: 0 0 7px 2px rgba(0, 0, 0, 0.25) !important;
  -webkit-box-shadow: 0 0 7px 2px rgba(0, 0, 0, 0.25) !important;
}

.webPushConfirmation .webPushConfirmationImage {
  text-align: center;
  padding: 50px 0;
}

.webPushConfirmation .webPushConfirmationImage img {
  max-width: 400px;
  max-height: 100px;
}

.webPushConfirmation .webPushConfirmationTexts {
  display: block;
  text-align: center;
  padding: 10px;
}

.webPushConfirmation .webPushConfirmationTexts .webPushConfirmationTitle {
  font-weight: bold;
  margin-bottom: 10px;
}

.webPushConfirmation .webPushConfirmationPowered {
  text-align: center;
  display: block;
  padding: 20px 0;
}

.webPushConfirmation .webPushContainner .webPushConfirmationPowered img {
  width: 80px;
}

@media (max-width: 430px) {
  .webPushIframe {
    min-height: 250px;
  }
  .webPushSolicitation .webPushContainner .webPushImage {
    width: 100%;
  }
  .webPushSolicitation .webPushContainner .webPushTexts {
    max-width: 100%;
    padding: 20px 10px;
  }
}
<!DOCTYPE html>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="https://dev-egoiapp2.com/wp/css/wp.css">
        <title>WebPush App</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">

Novidades? Nós avisamos!

Sempre que tivermos coisas novas para si, vai ver uma mensagenzinha no seu ecrã :)

                    <input type="email" placeholder="E-mail" id="email" name="email" style="display:none;">

                        Powered by test

Agora não

Quero receber alertas!

A: That happens because of margin: 20px in .webPushSolicitation .webPushContainner .webPushButtons. You can set margin-left: 0, for example


text:
Q: React Native createContext() and useContext() returning null I have tried looking at other posts with similar errors but I can't manage to find one that makes it work as expected.
AuthContext.js
import React from "react";

const AuthContext = React.createContext();
export default AuthContext;

const AuthContextProvider = ({ children }) => {
    const authContext = React.useMemo(
        () => ({
          signIn: async (data) => {
            await AsyncStorage.setItem('userToken', data.token);
            await AsyncStorage.setItem('user', JSON.stringify(data));
            dispatch({type: 'SIGN_IN', token: data.token, user: data});
          },
          signOut: async () => {
            await AsyncStorage.removeItem('userToken');
            await AsyncStorage.removeItem('user');
            dispatch({type: 'SIGN_OUT'});
          }
        }),
        []
      );
    return (
      <AuthContext.Provider
        value={{
          authContext
        }}
      >
        {children}
      </AuthContext.Provider>
    );
  };

Then in App.js
import { AuthContextProvider } from './AuthContext';

....

  return (
    <PaperProvider theme={theme}>
      <AuthContextProvider>
        <SafeAreaProvider>
          <NavigationContainer>
           <DetailsScreen />
          </NavigationContainer>
        </SafeAreaProvider>
      </AuthContextProvider>
    </PaperProvider>
  );

Then in DetailsScreen.js
import { AuthContext } from "../AuthContext";

constructor(props) {
    const {context} = useContext(AuthContext);
    console.log("-----------------------------", context); // returns undefined
    super(props, context);
  }

The error this block of code is causing is:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

I am out of ideas as to what could be wrong.

A: The context AuthContext that you created in AuthContext.js exports the context as default, but you import it as named-import, ie using import {} from. So the useContext hook takes as an argument a null instead of the actual context created by React.createContext()
Then be careful that const {context} = useContext(AuthContext); is also wrong as the hook will return the object {authContext: {...}} which means that you have to do const {authContext} = useContext(AuthContext);
In the Provider you can avoid passing value={{authContext}} and instead pass value={authContext} then you can just const authContext = useContext(AuthContext);


text:
Q: Create Reload Button with Path Markup Geometry I want to create a reload icon using wpf path markup syntax. The icon shall look like this:

The problem is that i dont know how to create an open circle properly with for example Elliptical Arcs.
A similar button i already created is the following. My reload button shall be in the same scale.
   <ControlTemplate TargetType="Button" x:Key="buttonCustomDelete">
        <ControlTemplate.Resources>
            <Style TargetType="Path">
                <Setter Property="Fill" Value="Transparent"/>
                <Setter Property="StrokeThickness" Value="2"/>
            </Style>
        </ControlTemplate.Resources>

        <Canvas >
            <Path x:Name="circle">
                <Path.Data>
                    <EllipseGeometry Center="7,7" RadiusX="7" RadiusY="7"/>
                </Path.Data>
            </Path>
            <Path x:Name="cross">
                <Path.Data>
                    <GeometryGroup>
                        <LineGeometry StartPoint="3,3" EndPoint="11,11"/>
                        <LineGeometry StartPoint="11,3" EndPoint="3,11"/>
                    </GeometryGroup>
                </Path.Data>
            </Path>

        </Canvas>
        <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter TargetName="cross" Property="Stroke" Value="White"/>
                <Setter TargetName="circle" Property="Fill" Value="#DB4437"/>
            </Trigger>
            <Trigger Property="IsMouseOver" Value="False">
                <Setter TargetName="cross" Property="Stroke" Value="LightGray"/>
                <Setter TargetName="circle" Property="Fill" Value="Transparent"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>

A: As allready mentioned - you can use Inkscape to let the programm draw your Path - check Tutorial here
If you feel ok with third party librarys - I would recommend you Font Awesome for WPF
It is a pretty sick NuGet package and includes Reload Icon like showed in your question. It also has pretty much downloads - so don't fear to use it. It also has a MIT license - what is pretty cool.
You can also check out their Repository - it is open source.
Additional Information: How to use Path in a Button:
    <Button Height="55"
            Width="55">
        <Button.ContentTemplate>
            <DataTemplate>
                <Rectangle Width="35"
                           Height="35">
                    <Rectangle.Fill>
                        <VisualBrush Stretch="Fill"
                                     Visual="{StaticResource my_fontawesome_icon}" />
                    </Rectangle.Fill>
                </Rectangle>
            </DataTemplate>
        </Button.ContentTemplate>
    </Button>

Please don't forget to add ressources. You can also just paste the path into the VisualBrush.Visual.


text:
Q: How do I use this function for saving and loading with pickle? I am trying to save content for my small project I am doing and wanted to test out saving. I get quite far until I make my loading function. I'll show both saving and loading:
    def saving(slot1, slot2, slot3) :

     if saving == slot1 :
       pickle.dump(name, open("save1.sav", "wb"))
     elif saving == slot2 :
      pickle.dump(name, open("save2.sav", "wb"))
     elif saving == slot3 :
      pickle.dump(name, open("save3.sav", "wb"))

    def loading(file1, file2, file3) :

     if loading == file1 :
      loading = pickle.load(name, open("save1.sav", "rb"))
     elif loading == file2 :
      loading = pickle.load(name, open("save2.sav", "rb"))
     elif loading == file3 :
      loading = pickle.load(name, open("save3.sav", "rb"))

My saving function is fine and works, but when I call my loading and specify
    loading(file1)

It tells me:
    NameError: name 'file1' is not defined

If this is just a simple misunderstanding of how Python functions work, lead me to a place where I can learn about them. If you have no issues, let me know and I'll see what I can redo in my program.

A: try to do all the define the file1 inside __main__ function. To be honest, This question is still lack of information on where you create the file1.
Also try to remove the empty line between your def loading and the content. OR add one more empty line AFTER the def saving content
Python code runs from top to bottom. If you call the the loading before the file1 it will said that the file1 is not defined. It also line sensitive as well. The more you create an empty line it may considered it out of scope.
Your pickle code is fine, but the way you define the file1 from outside the function may cause the problem.
Try to debug from this link I've found.
Here


text:
Q: How to Find the Sum of 'Add or Keep Sequence' I have a sequence.
$a_{n}=a_{\lfloor\frac{n}{2}\rfloor}+\dfrac{1+(-1)^{n+1}}{2}$ where $a_{0}=0$ and $n\in\{0\}\cup\mathbb{N}$.
So, it's
$a_{2k-1}=a_{k-1}+1$ or $a_{2k}=a_{k}$ for nonnegative integer $k$.
If I perform a continued divided by 2, and if the number $n$ lies in $2^{i}\leq n<2^{i+1}$,
$n=2(2(\dots(2(2+\_)+\_)+\dots)+\_)+\_$
There would be $i+1$ spaces, and by choosing where I put $0$ and $1$, the value changes accordingly.
So, there would be $P(i+1,j)$ choices if I want to put $1$ for $j$ times.
Then, it would be $a_{n}=j$.
I tried evaluating the sum of $a_{n}$ for an interval $2^{i}\leq n<2^{i+1}$, and I get $\displaystyle \sum^{i+1}_{j=0}\{j\cdot P(i+1,j)\}$.
I can't process it further because I'm stuck simplifying the expression. Please suggest a method.

A: Apparently you want to evaluate $S_i=\sum_{n=2^i}^{2^{i+1}-1}a_n$. Every number in the summation for $S_{i+1}$ refers to a number $a_n$ in the summation for $S_i$, and the latter number $a_n$ (contributing to $S_i$) is so referenced precisely twice, namely by $a_{2n}=a_n$ and by $a_{2n+1}=a_n+1$. So while $a_n$ contributes its value to $S_i$, it contributes its value twice to $S_{i+1}$ (and all contributions to $S_i$ are so accounted for). But there are also contributions to $S_{i+1}$ of the $+1$ term in for the odd-index $a_{2n+1}$, and there as many of such contributions as there are $n$ with $2^i\leq n<2^{i+1}$, namely $2^i$. Therefore one gets the recurrence relation $S_{i+1}=2S_i+2^i$, with initial value $S_0=a_1=a_0+1=1$. From the initial values $1,4,12,32,80,192,\ldots$ it is not so hard to guess the general formula $S_i=(i+1)2^i$, and it is easy to check that this indeed satisfies the recurrence and the initial condition.


text:
Q: Multiple elements with same name in XML and want to change value of one specific element only based on one condition using xslt Input XML
<?xml version="1.0"?>
<Response>
  <TroubleResponse>
    <Check>
      <DStatus>
        <GID>123456789</GID>
        <FLAG/>
      </DStatus>
      <DStatus>
        <GID>222233333</GID>
        <FLAG/>
      </DStatus>
      <DStatus>
        <GID>5555777788</GID>
        <FLAG/>
      </DStatus>
    </Check>
    <RAM>
      <Details>
        <RAMID>5555777788</RAMID>
      </Details>
    </RAM>
  </TroubleResponse>
</Response>

My question is:
I want to update the element FLAG value as TRUE where element RAMID value matches with element GID value.
How can I achieve this using XSLT?

A: Use the identity template in combination with this template
<xsl:template match="FLAG[../GID = ../../../RAM/Details/RAMID]">
    <xsl:copy>TRUE</xsl:copy>
</xsl:template>

The identity template for XSLT-1.0 is
<!-- Identity template -->
<xsl:template match="node()|@*">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*" />
  </xsl:copy>
</xsl:template>

The combination of both achieves the desired result.
If you can XSLT-2.0 or above, you can replace the identity template with
<xsl:mode on-no-match="shallow-copy"/>


text:
Q: Insert multiple values in a text field using a "delimiter"? Let's say I have a Text field called "description" inside "products" table.
Inside this field I will store 3 values. I will separate them with two pipes ( || ):
requirements:
- bla bla.. (a text)
||
info:
- bla bla.. (a text)
||
specifications:
- bla bla.. (a text)

I am doing this because it looks better than having 3 different Text fields to do the job (which will increase the table's size).
Is this a bad idea? Should I use 3 different fields? Does 3 text fields really affect database performance?

A:
Is this a bad idea?

Almost certainly. If code only ever treats that column as single un-parsed continuous string then it may be OK1. As soon as you want to pull one of the three values it is definitely a bad idea. Even if the parsing happens in the application it is additional complexity that need not be there.

Should I use 3 different fields?

Yes.

Does 3 text fields really affect database performance?

Not in any way you will ever notice. Depending on your particular DB software those "text" columns may be treated just like any other data type. Also you must consider how optimized your code to handle this will be compared to that written by a room full of PhD's who built the DBMS and do just this for a living.

1 Even then I'd say have separate columns.

A: I agree with Michael Green and have some additional points to add.

Is this a bad idea?

Yes. It might seem like it's the more convenient option for you right now, but a bit later you may come to regret this. Anyone else who has to query or report on this will use "many swear words" when they find it. The time you save now will be lost everytime you have to parse unpack and check these in the future.

Should I use 3 different fields?

Yes, or alternatively consider an XML (or JSON) field. I don't like XML, but at least it has some concept of structure, and can be queried with some confidence. It will also be easier to extend when you realise you need 4 parameters.. or don't want the 2nd any longer.
A clear advantage of using separate table fields is that you now rely upon data typing and can now relying upon the database to enforce rules such as whether a value can be NULL or not.

Does 3 text fields really affect database performance?

Not significantly, especially as it's the same amount of text so its taking up the same amount if space, or even less if you consider the delimiters. By using separate fields with indexes query performance is very likely to improve.
Relational databases have a lot of power and capability, which you will not be able to exploit if you cludge it all together. What might seem like a shortcut now will come back to haunt you later.


text:
Q: How to set bounds for spinal line with axisartist? How can I set the bounds of axisartist.axis[].line?
With the normal API, its possible to set bounds of the axis spine with:
ax.spines['right'].set_bounds(low=0.01,high=0.1)

But axisartist does not have a spines object. Instead, spinal lines are implemented with ax.axis['left'].line, which does not have a get_bounds and set_bounds method.
Example:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist
import seaborn as sns

use_artist = True

x = np.random.random(10)
y = np.random.random(10)

x.sort()
y.sort()

if use_artist:
    fig = plt.figure()
    ax = fig.add_subplot(axes_class=axisartist.Axes)
else:
    fig, ax = plt.subplots()

ax.scatter(x, y, marker="o")

if use_artist:
    ax.axis['right'].set_visible(False)
    ax.axis['top'].set_visible(False)

    # HOW TO SET BOUNDS OF ax.axis['left'].line here?

else:
    sns.despine()
    ax.spines['left'].set_bounds(ax.get_yticks()[1], ax.get_yticks()[-2])
    ax.spines['bottom'].set_bounds(ax.get_xticks()[1], ax.get_xticks()[-2])

plt.tight_layout()
plt.draw()
plt.show()

Here are examples without and with axisartist:

A: Use axes.set_xbounds() or axes.set_xlim() (docs found here and here respectively). Both methods appear identical in function, but set_xlim has more functionality, should you require it. So your new modified code using only axisartist is:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist

# Data
x = np.random.random(10)
y = np.random.random(10)
x.sort()
y.sort()

# Creating figure, plot
fig = plt.figure()
ax = fig.add_subplot(axes_class=axisartist.Axes)
ax.scatter(x, y, marker="o")

# Formatting axes
ax.axis['right'].set_visible(False)
ax.axis['top'].set_visible(False)
ax.axis['left'].major_ticklabels.set_pad(10)
ax.axis['bottom'].major_ticklabels.set_pad(10)

# Setting axis limits
ax.set_xlim(left=0.2, right = 0.5)
ax.set_ylim(bottom=0, top = 0.7)

plt.tight_layout()
plt.draw()
plt.show()


text:
Q: Immutable data structure replacement for arrays What do you use when you need a immutable list with the fastest access/update? LinkedList can be slow if you have to access an element from the middle, and it's prohibitive to create and repopulate it. Binary trees? quadtrees?

A: If updating is very rare (or the collection is small), an array which you don't write to after intialization is worthwhile. The much lower constant factors (both in time and space) outweigh the linear time update in these cases.
Apart from that, there are a number of purely functional data structures which provide better bounds for these cases. 2-3 Finger Trees (the data structure behind Haskell's Data.Sequence) are one example. Another option are Clojure's vectors and related data structures (e.g. Relaxed Radix-Balanced Trees), which use trees with high fan-out (32 or more) to keep reads cheap and structural sharing to avoid too many copies.
All of these are moderately tricky to implement manually though, especially if performance is important, and I'm not aware of existing implementations (I don't think Clojure's vectors are easy or convenient to use from Java).

A: I'm not sure I understand what you're looking for but I'll try to give a couple of pointers based on some things I've seen in the standard classes:

*

*CopyOnWriteArrayList is a mutable yet threadsafe list because it duplicates the internal array on updates. Perhaps you could adapt some ideas from that, although it's obviously not efficient for large lists.

*ConcurrentHashMap implements similar ideas on a much more complicated structure. It divides the internal hash table into separate partitions, so that changes only need to lock access to the relevant partition.
For an immutable list you could do something similar: divide the list's internal array into several partitions and treat them all as immutable. When you need to change the list, you only need to clone one partition and the index of the partitions, which will be cheaper than duplicating the whole list.

*AWTEventMulticaster achieves similar goals, but duplicates the absolute minimum. It's a clever binary tree. See the source.
With a smaller size of internal partition or block, you can get faster updates, but slower access in general. With a larger block (e.g., the entire array) you get slower updates but faster access.
If you really need fastest access and update, you have to use a mutable array.


text:
Q: How can I batch-copy pages from one Wordpress directory to another on the same domain? I have a directory type site in which I have thousands of pages advertising local businesses. I wish to duplicate those pages under another directory.
So for example, say I was pursuing a keyword of 'guitar strings' with thousands of vendors under the directory http://my-site.com/guitarstrings/'1000's_of_vendor_pages'.
I now wish to go after the keyword 'guitar straps' and so I create a new directory or parent page http://my-site.com/guitarstraps/'1000's_of_vendor_pages_copied_here'.
Don't worry about duplicate content as I have a trick for that.
However, it WOULD be useful if in some instances I could batch change some item or items on the new pages to suit the new keyword so if anybody knows how to do this that would be great.
Can anybody help? Try and keep the answer as non-technical as you can. :-)


text:
Q: javax.crypto.BadPaddingException: Given final block not properly padded while decryption I am trying to decrypt a file in java. The first 16 bytes of decrypted file are IV (initialization vector). Please help in resolving the above exception.
I am trying to prepend the IV in the output file in AESFileEncryption() and then reading it while decryption.
Thank You.
public class AESFileEncryption {
public static void encrypt(String path,String pwd) throws Exception {

    FileOutputStream outFile;

    try (
            FileInputStream inFile = new FileInputStream(path)) {

        String fileName=path;

        System.out.println(path);

        outFile = new FileOutputStream(fileName+".aes");
        // password to encrypt the file
        String password = pwd;
        byte[] salt = {
        (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
        (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
       };

        SecretKeyFactory factory = SecretKeyFactory
                .getInstance("PBKDF2WithHmacSHA1");
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(),salt,65536,128);// user-chosen password that can be used with password-based encryption (PBE).
        SecretKey secretKey = factory.generateSecret(keySpec);
        SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");//Secret KeySpec is a class and implements inteface SecretKey

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[16];
        random.nextBytes(bytes);
     IvParameterSpec ivspec = new IvParameterSpec(bytes);
        cipher.init(Cipher.ENCRYPT_MODE, secret,ivspec);//opmode,key
        outFile.write(bytes);
        byte[] input = new byte[64];
        int bytesRead;
        while ((bytesRead = inFile.read(input)) != -1) {
            byte[] output = cipher.update(input, 0, bytesRead);
            if (output != null)
                Files.write(Paths.get(fileName+".aes"), output, StandardOpenOption.APPEND);

        }   byte[] output = cipher.doFinal();
        if (output != null)
            Files.write(Paths.get(fileName+".aes"), output, StandardOpenOption.APPEND);
    }
    outFile.flush();
    outFile.close();
    File f=new File(path);
    boolean x=f.delete();
    if(x){
        System.out.println("File deleted");
    }
    JOptionPane.showMessageDialog(null,"File Encrypted.");

}
}

Decryption code
public class AESFileDecryption {
public static void decrypt(String path,String pwd) throws Exception {

    String password = pwd;
    String fileName=path;
    File file=new File(path);
        //System.out.println(inFile.toString());
        String fileNameWithOutExt = path.replaceFirst("[.][^.]+$", "");
        System.out.println(fileName);
        System.out.println(fileNameWithOutExt);
        byte[] salt = {
        (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
        (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
    };
    System.out.println("1");
    FileInputStream fis = new FileInputStream(path);
    SecretKeyFactory factory = SecretKeyFactory
            .getInstance("PBKDF2WithHmacSHA1");
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(),salt,65536,128);
    SecretKey tmp = factory.generateSecret(keySpec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    System.out.println("2");
    // file decryption
    Cipher cipher=null;
    byte bytes[]=new byte[16];
    fis.read(bytes, 0, 16);
    IvParameterSpec ivspec = new IvParameterSpec(bytes);

    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret, ivspec);
    System.out.println("3");
    FileOutputStream fos = new FileOutputStream(fileNameWithOutExt);
    System.out.println("4");
    byte[] in   = new byte[64];
    int read;
    while ((read = fis.read(in,16,(int)file.length()-16)) != -1) {
        byte[] output = cipher.update(in, 0, read);
        if (output != null)
            fos.write(output);
    }
    try{
    byte[] output = cipher.doFinal();
    if (output != null)
        fos.write(output);
    fis.close();
    fos.flush();
    fos.close();
    System.out.println("File Decrypted.");
}
catch(IOException | BadPaddingException | IllegalBlockSizeException e)
{
    System.out.println(e+"");
}
}
}

A: There are a few problems with the small example, but the one that is most immediately your problem is the line
while ((read = fis.read(in,16,(int)file.length()-16)) != -1) {

You seem to be confused about the meaning of the offset parameter to the read(). It is not the offset into the file, but rather the offset into the array (in) that is specified in the first parameter.
A non-exhaustive list of other problems that I see include:

*

*writing to the file using the two independent mechanisms (FileOutputStream.write() and Files.write()). This actually worked ok when I ran your program but it seems like it's asking for trouble. There's no reason to use Files.write() here.

*fis.read(bytes, 0, 16); does not check the return value.

It seems you are struggling with finding some IO idioms that you're comfortable with. Or perhaps just experimenting. At the risk of giving you even more options to juggle, you might consider investigating google's open source Guava library. Many people find it has just what they needed.


text:
Q: How do I make a column unique and index it in a Ruby on Rails migration? I would like to make a column unique in Ruby on Rails migration script. What is the best way to do it? Also is there a way to index a column in a table?
I would like to enforce unique columns in a database as opposed to just using :validate_uniqueness_of.

A: If you are creating a new table, you can use the inline shortcut:
  def change
    create_table :posts do |t|
      t.string :title, null: false, index: { unique: true }
      t.timestamps
    end
  end

A: The short answer for old versions of Rails (see other answers for Rails 4+):
add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name,
add_index :table_name, [:column_name_a, :column_name_b], unique: true

If you get "index name... is too long", you can add name: "whatever" to the add_index method to make the name shorter.
For fine-grained control, there's a "execute" method that executes straight SQL.
That's it!
If you are doing this as a replacement for regular old model validations, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.

A: Since this hasn't been mentioned yet but answers the question I had when I found this page, you can also specify that an index should be unique when adding it via t.references or t.belongs_to:
create_table :accounts do |t|
  t.references :user, index: { unique: true } # or t.belongs_to

  # other columns...
end

(as of at least Rails 4.2.7)

A: I'm using Rails 5 and the above answers work great; here's another way that also worked for me (the table name is :people and the column name is :email_address)
class AddIndexToEmailAddress < ActiveRecord::Migration[5.0]
  def change
    change_table :people do |t|
      t.index :email_address, unique: true
    end
  end
end

A:
rails generate migration add_index_to_table_name column_name:uniq

or

rails generate migration add_column_name_to_table_name column_name:string:uniq:index

generates
class AddIndexToModerators < ActiveRecord::Migration
  def change
    add_column :moderators, :username, :string
    add_index :moderators, :username, unique: true
  end
end

If you're adding an index to an existing column, remove or comment the add_column line, or put in a check
add_column :moderators, :username, :string unless column_exists? :moderators, :username

A: You might want to add name for the unique key as many times the default unique_key name by rails can be too long for which the DB can throw the error.
To add name for your index just use the name: option.
The migration query might look something like this -
add_index :table_name, [:column_name_a, :column_name_b, ... :column_name_n], unique: true, name: 'my_custom_index_name'
More info - http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index

A: add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name.

A: If you have missed to add unique to DB column, just add this validation in model to check if the field is unique:
class Person < ActiveRecord::Base
  validates_uniqueness_of :user_name
end

refer here
Above is for testing purpose only, please add index by changing DB column as suggested by @Nate
please refer this with index for more information


text:
Q: Remove Leading Zeros in a column in a sql server table, My question is very similar to this one:
SE Question
However I want to run a query on a table, and actually update the values in that table, not just Select them.
Im not sure how to select a value and then Update it without using a for loop.
What Query can I run to do this?
{Edit:}
I store number values as a varchar and an import I ran imported numbers such a 00233
I want it to be 233

A: So adapt the query for an update:
update table t
    set ColumnName =  substring(ColumnName, patindex('%[^0]%', ColumnName), 10);

A: You question is a little vague, since you don't elaborate on WHY you want to SELECT and then UPDATE, because of that this answer may be of no use to you. However..
In an UPDATE statement you can set a column value based on a column value. What I mean is, if you have "00001A" in ColA and want it to be "1A" you can (mostly taking answer from linked question)
UPDATE MyTable SET ColA =  substring(ColA, patindex('%[^0]%',ColA), 10)

First time through this code will change any occurance of 00001A to 1A and subsequent runs it won't match the PATINDEX so ignore the value.
If this isn't what you're after, please expand upon the question a little more and hopefully you'll get more assistance.

A: If all the columns are numeric use this:
UPDATE table
SET col =  cast(cast(col as int) as varchar(10))
WHERE col like '0%'

If some values are not numeric
UPDATE table
SET col = stuff(@a, 1, patindex('%[^0]%', @a) - 1, '')
WHERE col like '0%'


text:
Q: OpenUI5: Where is the data gone, loaded by sap.ui.model.odata.v2.ODataModel()? I have been googling and testing around for quite a few days with no success. If someone could give me a hint to point me into the right direction, then I would greatly appreciate that.
What is my target: to get some data from an OData service and show it in an UI5 oTable. Later on, I will have to do the CRUD-operations, but for now the aim is just to show the data successfully.
What I have got so far: I have an MVC project. I have created an OpenUI5Controller.cs, whose purpose is to represent an ODataService:
public class OpenUI5Controller : Controller
{
    private MyEntities myEntities = new MyEntities();

    public JsonResult GetAllContragents()
    {
        try
        {
            IQueryable<Contragent> contragents = myEntities.Contragent.OrderBy(x => x.Code);

            // for now, take the first 100 only
            contragents = contragents.Take(100);

            var jsonData = new
            {
                rows = contragents.ToList()
                //rows = "123"
            };

            var res = Json(jsonData, JsonRequestBehavior.AllowGet);
            return res;
        }
        catch (Exception e)
        {
            LoggingService.WriteLog("Error in OpenUI5Controller.GetAllContragents()", e);
            return null;
        }
    }
}

After that, I try to consume the data like this:
var oModel = new sap.ui.model.odata.v2.ODataModel('/OpenUI5/GetAllContragents', {
            //maxDataServiceVersion: '2.0',
            json: true,
            skipMetadataAnnotationParsing: true,
            // none of those callbacks is ever triggered, even the requestFailed...!?
            requestSent: function (a, b, c) {
                debugger;

                var trgrwg = oModel.getData();
                var vfewgvfewgv = oModel.getProperty('/');
                var vfewgvfewgv2 = oModel.getProperty('/rows');
                var vfewgvfewgv3 = oModel.getProperty('rows');
            },
            requestFailed: function (a, b, c) {
                debugger;

                var trgrwg = oModel.getData();
                var vfewgvfewgv = oModel.getProperty('/');
                var vfewgvfewgv2 = oModel.getProperty('/rows');
                var vfewgvfewgv3 = oModel.getProperty('rows');
            },
            requestCompleted: function (a, b, c) {
                debugger;

                var trgrwg = oModel.getData();
                var vfewgvfewgv = oModel.getProperty('/');
                var vfewgvfewgv2 = oModel.getProperty('/rows');
                var vfewgvfewgv3 = oModel.getProperty('rows');
            },
            batchRequestCompleted: function (a, b, c) {
                debugger;

                var trgrwg = oModel.getData();
                var vfewgvfewgv = oModel.getProperty('/');
                var vfewgvfewgv2 = oModel.getProperty('/rows');
                var vfewgvfewgv3 = oModel.getProperty('rows');
            },
            useBatch : false
        });

var trgrwg = oModel.getData();
        var vfewgvfewgv = oModel.getProperty('/');
        var vfewgvfewgv2 = oModel.getProperty('/rows');
        var vfewgvfewgv3 = oModel.getProperty('rows');
        var vfewgvfewgv4 = oModel.getProperty('contragents');
        var vfewgvfewgv5 = oModel.getProperty('/contragents');
        var vfewgvfewgv6 = oModel.getProperty('Contragents');
        var vfewgvfewgv7 = oModel.getProperty('/Contragents');
debugger;

When stopping at this breakpoint, I see this in the Chrome Developer Tools:

Moving further, I came accross this and tried to read() those contragents:
oModel.read('/Contragents', {
            success: function (event) {
                debugger;
                // event.root I guess should be the received data as jsonString

                // As I guess, I will have to get it and give it to oModel.oData manually, or am I wrong? I guess this would cause update(), delete()... calls to fail later on. Anyways...

                sap.ui.getCore().setModel(oModel); // https://archive.sap.com/discussions/thread/3746588 - seems not to work like this
                if (withJsonModel !== true) {               https://help.sap.com/saphelp_uiaddon20/helpdata/en/12/32241b99d7437ba3614698d53dfa4b/content.htm
                    oTable.setModel(oModel);
                    oTable.bindRows("/");
                    //oTable.bindRows("/rows");
                    oTable.placeAt('tblContragents', "only");
                }
            },
            error: function (event) {
                debugger;
            }
        });

Here, neither success, nor error callback gets ever triggered.
After this read() attempt, I have again:
var trgrwg = oModel.getData();
        var vfewgvfewgv = oModel.getProperty('/');
        var vfewgvfewgv2 = oModel.getProperty('/rows');
        var vfewgvfewgv3 = oModel.getProperty('rows');
        var vfewgvfewgv4 = oModel.getProperty('contragents');
        var vfewgvfewgv5 = oModel.getProperty('/contragents');
        var vfewgvfewgv6 = oModel.getProperty('Contragents');
        var vfewgvfewgv7 = oModel.getProperty('/Contragents');

and I see this:

After that, I have oTable = new sap.ui.table.Table(...);
Finally, I try this:
sap.ui.getCore().setModel(oModel);
        //oTable.setModel(oModel); // or maybe should be this one directly?
        oTable.bindRows("/Contragents");
        oTable.placeAt('tblContragents', "only");

As a result, I get an empty table.
I suppose I should tell you what I see in Fiddler as well: I see this request: 1    200 HTTP    localhost:55714 /OpenUI5/GetAllContragents/$metadata
As a result in the TextView of the response section, I see the data as json, that I need to show in the table.
How to make it work and show the data in the table?
edit from 02.02.2017: I have 1% of progress. After some more and more testing and googling, I decided to try it like this.
First of all, some time ago (can't really remember when), after seeing a good example for OdataServices, I decided to create a dedicated controller like this:
public class ContragentsController : ODataController
{
    private MyEntities db = new MyEntities();

    //public System.Web.Mvc.JsonResult GetContragents()
    public string GetContragents()
    {
        try
        {
            IQueryable<Contragent> contragents = db.Contragent.OrderBy(x => x.Code);

            // for now, give me first 100
            contragents = contragents.Take(100);

            var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            var rows = jsSerializer.Serialize(contragents.ToList());

            //var jsonData = new
            //{
            //    rows = model
            //};

            //var res = new System.Web.Mvc.JsonResult();
            //res.Data = jsonData;
            //res.JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet;

            return rows;
        }
        catch (Exception e)
        {
            //...some errorLogging
            return null;
        }
    }

After that, I changed the call to ODataModel() like this:
var oModel = new sap.ui.model.odata.v2.ODataModel(BASE_HREF + 'odata/', {
            //maxDataServiceVersion: '2.0',
            json: true,
            skipMetadataAnnotationParsing: true,
            // those callbacks still do not get called at all
            requestSent: function (a, b, c) {
                debugger;

                var trgrwg = oModel.getData();
                var vfewgvfewgv = oModel.getProperty('/');
                var vfewgvfewgv2 = oModel.getProperty('/rows');
                var vfewgvfewgv3 = oModel.getProperty('rows');
            },
            requestFailed: function (a, b, c) {
                debugger;

                var trgrwg = oModel.getData();
                var vfewgvfewgv = oModel.getProperty('/');
                var vfewgvfewgv2 = oModel.getProperty('/rows');
                var vfewgvfewgv3 = oModel.getProperty('rows');
            },
            requestCompleted: function (a, b, c) {
                debugger;

                var trgrwg = oModel.getData();
                var vfewgvfewgv = oModel.getProperty('/');
                var vfewgvfewgv2 = oModel.getProperty('/rows');
                var vfewgvfewgv3 = oModel.getProperty('rows');
            },
            batchRequestCompleted: function (a, b, c) {
                debugger;

                var trgrwg = oModel.getData();
                var vfewgvfewgv = oModel.getProperty('/');
                var vfewgvfewgv2 = oModel.getProperty('/rows');
                var vfewgvfewgv3 = oModel.getProperty('rows');
            },
            useBatch : false
        });

The whole drama is that SapUI5 runs a request for $metadata, before making the actual request to odata/Contragents and so on. As expected in this case, I see in Fiddler, that the server 404-s to that request: http://localhost:55714/odata/Contragents/$metadata and it doesn't reach the moment to make the request to Contragents. I know, that I will have to change the source of the library somewhere in order to prevent this $metadata request from running, which I don't want to do. So in Fiddler's Composer, I tried the following: localhost:55714/odata/$metadata and it returned some xml with the desired metadata (maybe indeed it is important, but I haven't understood yet why). Next step was to modify the call to sap.ui.model.odata.v2.ODataModel(); as shown above. The great thing after all that is the fact, that oModel.read('/Contragents', {...}); showed signs of life! Now, the success callback gets called and in event.root I get those contragents as json string. And then what? I tried oModel.setData(JSON.parse(event.root)); but it gave me this error:

Also, if I manage to get it working this way, I don't quite understand, will the CRUD methods of oModel work? oModel.setData()-ing is something familliar to me from the time when I was playing around with JSONModel():
oModel = new sap.ui.model.json.JSONModel();
oModel.setData(dataForGrid); // this works like a charm

But using JSONModel() means, that I cannot use the insert(), update()... methods of sap.ui.model.odata.v2.ODataModel(), because JSONModel(); does not provide us with them, which is normal, as long as I get dataForGrid via a standard $.ajax() call.
edit2: While debugging, I noticed, that the method ContragentsController.GetContragents(); gets called twice and in the console, I see this error message:

edit3: Following the good example for ODataService, I added a "selection" method to the controller like this:
// GET: odata/Contragents(5)
    [EnableQuery]
    public SingleResult<Contragent> GetContragents([FromODataUri] string key)
    {
        return SingleResult.Create(db.Contragent.Where(contragent => contragent.Code == key));
    }

In Fiddler, it 404-s and does not get called at all no matter if i Compose it like this: http://localhost:55714/Contragents(2) or like this: http://localhost:55714/odata/Contragents(2)
Couple of minutes later, I've got couple of % progress. I looked even closer in the tutorial and I noticed something, which made me change the "selection" method to this:
// GET: odata/Contragents(5)
    [EnableQuery]
    public SingleResult<Contragent> Get([FromODataUri] string key)
    {
        return SingleResult.Create(db.Contragent.Where(contragent => contragent.Code == key));
    }

Now, when I Compose this request: http://localhost:55714/odata/Contragents(2), it now does not 404, but does 406 Not Acceptable. I came across this error code some time ago and I didn't understand well what is the reason for it and how is it related to ODataServices.
I just reminded myself what does 406 mean and it turns out, that every method on the controller must return a json result as string. Because, SapUI5 sets Accept-Type to "application/json".


text:
Q: java regex to ignore the domain name in a URL and consider everything beyond Here is my case:
I need everything beyond the domain name in the URL, i.e, everything beyond the third occurence of /
Here is the sample URL:
https://test-qa-documents.ss-us-abc-2.mentor.com/thumbnail/58043233791488_testfit_image?X-Amz-Security-Token=xyz
I need the output as:
thumbnail/58043233791488_testfit_image?X-Amz-Security-Token=xyz
Any help on this?

A: The Java URL class has support many types of parsing URLs.  In this case, you can use URL#getFile() on your URL to obtain the string portion you want.
// import java.net.*
String url = "https://test-qa-documents.ss-us-abc-2.mentor.com/thumbnail/58043233791488_testfit_image?X-Amz-Security-Token=xyz";
URL theURL = new URL(url);
System.out.println(theURL.getFile());

Output:
/thumbnail/58043233791488_testfit_image?X-Amz-Security-Token=xyz

A: url.replaceFirst("https?://[^/]+/","")
Just replace http://.../ part to blank.


text:
Q: BigQuery Node.js api to create external table I am trying to create an external table from a google cloud function using the node.js API. The function will trigger from GCS bucket changes. I can create a native table but not an external table. In the node.js api for import here, the configuration.load metadata does not have a setting to specify this as external table. Here is my code for native table creation till now. My question is "How do I use the Node.js Api to create external table for a GCS bucket"
    const projectId = "N"
    const bigquery = BigQuery({
        projectId: projectId
    });
    const storage = Storage({
        projectId: projectId
    });

    const dataset = bigquery.dataset("dataset");

    const table = dataset.table("test_data");

    const bucket = storage.bucket("my-bucket");

    const file = bucket.file("2017/03/02/*");

    let job;

    // Imports data from a GCS file into a table
    return table.import(file,{"sourceFormat":"AVRO"})
        .then((results) => {
            job = results[0];
            console.log(`Job ${job.id} started.`);
            return job.promise();
        })
        .then((results) => {
            console.log(`Job ${job.id} completed.`);
            return results;
        });

A: I found out the solution after reading the docs a bit. Federated tables don't work by loading/importing them. They are just tabled with externalConfig set. So this code worked for me
const dataset = bigquery.dataset("dataset");
var options = {
    "externalDataConfiguration": {
        "sourceUris": ["gs://my-bucket/2017/03/20/*"],
        "sourceFormat": "AVRO",
        "maxBadRecords": 0,
        "autodetect": true
    }
}
dataset.createTable("test_data_20170320",options, function(err, table, apiResponse){
    console.log(err)
    console.log(table)
    console.log(apiResponse)
})


text:
Q: Is this passive sentence correct Is this passive sentence correct?

I hope you find this article as interesting, as writing it was to me!

If not, how can I rephrase it to sound correct?

A: The idiom

X as Y ... as Z

requires that Y and Z be comparable characteristics of X. In your sentence X=this article, Y=interesting, an Z=writing.  But the last two aren't comparable, and you're in danger of your reader expecting something like

I hope you find this article as interesting as I found it irritating!

This is clearly not what you mean. As a stylistic consideration, it helps if the syntax in both parts is parallel. In your version, the person who finds the article interesting is the subject (i.e., you), but the person doing the writing is the object of the preposition to (i.e., me).
Both syntax an style may be accommodated by

I hope you find this article as interesting to read as it was for me to write.


text:
Q: Java - Can calling System.gc two times release underlying object twice? I have a Java program which calls into my C++ library. JNI-C++ bridging is created using SWIG
 I am relatively new to Java & trying to understand the behavior of System.gc & System.runFinalization
 This code below causes a SIGABRT, killing my app (2 out of 10 runs)

public static void main (String[] args)
{
    try
    {
        doSomeStuff();
    } catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    } finally {
        System.runFinalization();
        System.gc();
    }

}

void doSomeStuff()
{
    try
    {
        sampleCppClass cppClass = new sampleCppClass();
        /*
        *   do some stuff with Cpp obj
        */
    } catch (Exception ex)
    {
        System.out.println(ex.getMessage());
    } finally {
        System.runFinalization();
        System.gc();
    }
}

 Whereas this one works fine
public static void main (String[] args)
{
    try
    {
        doSomeStuff();
    } catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    } finally {
        System.runFinalization();
        System.gc();
    }

}

void doSomeStuff()
{
    try
    {
        sampleCppClass cppClass = new sampleCppClass();
        /*
        *   do some stuff with Cpp obj
        */
    } catch (Exception ex)
    {
        System.out.println(ex.getMessage());
    }
}

 I know that System.gc() & System.runFinalization() are non-deterministic(Source-1, Source-2 and Source-3).
Can it so happen that the System.gc() in doSomeStuff gets executed & free's the obj.
Later on, the System.gc() in main runs & tries to free  the same obj causing a crash? If this is indeed the case, is there a way to prove it (logs/prints to show the order of object free'ed by gc)?
This SO post, explains causes of SIGABRT
 Since I am running in release mode, my C++ lib doesnt have any assert/abort. Hence I am concerned about double/multiple free's of the object in consideration.

A:
Can it so happen that the System.gc() in doSomeStuff() gets executed & free's the obj.

Yes, but it can also happen that it doesn't do anything.

Later on, the System.gc() in main runs & tries to free the same obj causing a crash?

No. Ths is garbage collection, not C++ destruction. It only happens once per object, or indeed never.
The underlying reason for your problem as far as this code is concerned is that you have your gc() and runFinalization() calls in the wrong order. runFinalization() does nothing if there has been no prior GC. It executes the finalizer queue, which is only populated by GC.
So when you do it all twice, only the second runFinalization() does anything. This presumably executes a finalizer in your SampleCPPClass, which appears to have a bug, evidently in native code.
But as you haven't posted the code concerned it is impossible to comment further.


text:
Q: How to fix ArgumentError: wrong number of arguments (given 0, expected 1) - RoR I'm beginner and in the mailer code Ruby on Rails I have an error "ArgumentError: wrong number of arguments (given 0, expected 1)" between my code and his test.
Error:
UtilisateurMailerTest#test_account_activation:

ArgumentError: wrong number of arguments (given 0, expected 1)
    app/mailers/utilisateur_mailer.rb:8:in `account_activation'
    test/mailers/utilisateur_mailer_test.rb:6

utilisateur_mailer_test.rb:
class UtilisateurMailerTest < ActionMailer::TestCase
  test "account_activation" do
           mail = UtilisateurMailer.account_activation
(line6)    assert_equal "Account activation", mail.subject
           assert_equal ["to@example.org"], mail.to
           assert_equal ["from@example.com"], mail.from
           assert_match "Hi", mail.body.encoded
  end

utilisateur_mailer.rb:
........
Line8:
  def account_activation(utilisateur)
    @utilisateur = utilisateur
    mail to: utilisateur.email, subject: "Activation du compte"
  end

I've tryed to delete ", mail.subject" and the subject: "Activation du compte" and it returns: ArgumentError: wrong number of arguments (given 1, expected 2..3)
I'm a novice.. thanks for your answers!

A: has you can see the error message is telling you that one of your method is waiting for an argument but nothing was passed to it.
In your utilisateur_mailer_test.rb, you can see that you are calling the method account_activation that you created in the utilisateur_mailer.rb.
As you can see this method needs an utilisateur parameter to be executed but when you are calling this method inside of your utilisateur_mailer_test.rb, you are not passing anything to it :
mail = UtilisateurMailer.account_activation
You must specify an utilisateur argument here by creating a user through a factory using FactoryBot with Faker for example.
Good luck ! :)

A: I faced this issue while upgrading from Rails v5.2.3 to v5.2.4 and fixed it by upgrading the following gem
gem 'awesome_nested_set', '~> 3.2.0'


text:
Q: directions api which provider to use I've got a question about directional services. There's a similar question on which I gave a reaction, but there's no response so I ask my question again. Sorry if this is double!
The post I'm talking about is Alternatives to google maps api
Now my question:
I need to make a route description for a courier that had to drive every day to deliver things. It's just a list with waypoints that needs to be in the right order for driving. I'm talking about 10 to 20 waypoints in a route. First I tried Google, I finished the script and they have max 8 waypoints. I can't take the pro account because it's way to expensive!!
Which provider is the best to do this. I'm building this in a cronjob that calculates the route every day, so I can't use javascript.
Thanks!

A: Maybe http://openstreetmap.org is something for you. There its also possible to set waypoints.

*

*An overview of php frameworks for openstreetmap

*PHProute


text:
Q: How to understand the instant state collapse in all references? When a subsystem A of an EPR pair AB is measured, it's usually said that the state of B collapse instantly, and also this is true for all observers according to relativistic quantum information.
Since different observers have different time lines, if A, B are spacelike located, the only possible explain for the 'instant collapse in all references' is that AB still occupies the same spacetime point.
Are there any work or evidence on this? Considering the current idea of the close relationship between entanglement and spacetime construction, is this possible?


text:
Q: $f(z) = w$ has n solutions $\forall w \in \mathbb{C} \iff f$ is a polynomial of degree $n$ Here is a conjecture that I came up with yesterday.
Conjecture: Suppose that $f:\mathbb{C} \to \mathbb{C}$ is entire. Then $f(z) = w$ has $n$ solutions $\forall w \in \mathbb{C} \iff f $ is a polynomial of degree $n$.
The converse follows immediately from the Fundamental Theorem of Algebra, but the forward implication is a lot more difficult. And after thinking about it more,  it seems to me that the forward implication is probably not true. Unfortunately, I can't immediately think of a counterexample.
I thought a little about the approach I might take to prove this. Suppose $f$ is as above. Then $f(z)=0$ has $n$ solutions, so we can write $f(z)=p(z)g(z)$ where $p$ is a polynomial of degree $n$ and $g$ is entire with $g\neq 0$. If $g$ is a constant, then we are done. Otherwise, by Liouville and Casaroti-Weierstrass, $g$ is unbounded and gets arbitrarily close to any value in $\mathbb{C}$. We can also write $g=e^h$ for some $h$ entire. (There is also Picard's theorem, but I am reluctant to use this as I don't know the proof.)
The above gets somewhere, but I am not sure it leads to a proof without another insight. If the conjecture is false, then it definitely doesn't lead to a proof.
So, is the conjecture true or false? And if it is true, am I on the right track to prove it? (I would appreciate small hints much more than a full answer.)

A: One can easily prove this without Picard as the assumptions imply that (if $f$ nonconstant so $n \ge 1$) then $f$ is a proper entire map since for any compact $K$ then $f^{-1}(K)$ is bounded
(pick $w \in K$ there is a small open neighborhood of it $B_w$ for which $f^{-1}(B_w)$ is a union of at most $n$ open bounded sets - there are exactly $n$ precisely when $w$ is not a critical value of $f$ - cover $K$ with finitely many such $B_w$ etc)
But any proper entire map is a polynomial since then $|f(z)| \to \infty$ as $z \to \infty$
(if there is $|z_n| \to \infty$ st $|f(z_n)|$ bounded, one can pick a subsequence and rename it $z_n$ also, for which $f(z_n) \to w$ and then for a small ball $B_w$ around $w$, one has $f^{-1}(\overline B_w)$ containing elements with unbounded absolute value, hence it is not compact)
Edited: as per comments more detail about why $f$ is proper:
If $w$ is not a critical value of $f$, then by the local form of holomorphic functions, for every $z_k, k=1,..n$ in its preimage, there is a small neighborhood $D_k$ of $z_k$ for which $f$ is injective and has image some open neighborhood $U_k$ of $w$ so one can take $B_w$ any ball in the intersection of the $U_k$ which is open and contains $w$ - and then the preimage of $B_w$ is included in the union of $D_k$ as each contains a root of $f(z)=y$ for every $y \in B_w$, so we account for all $n$ of them; if $w$ is a critical value then for every preimage for which $f'(z_k)=0$ the same applies except that now $f$ is a $m:1$ map from $D_k$ onto $U_k$ where $m$ is the order of the critical point $z_k$ so in other words the order of the zero for $f(z)-f(z_k)$
$K$ is compact and covered by the $B_w$ so by the property of compacity, it is covered by finitely many such.


text:
Q: Finding IAM SA Keys Older than 89 Days in Google Cloud I'm trying to write a script that will hunt out all IAM service keys that have existed longer than 89 days to meet our security requirements, but I'm typing myself into knots.
My best attempt so far:
gcloud iam service-accounts keys list --quiet --managed-by=user --iam-account $SERVICE_ACCOUNT_EMAIL --filter='createTime<=P89D' --format='csv[no-heading](KEY_ID)'

But this appears to catch all of the keys. I'm struggling to get my head around Google's filter configurations. Any pointers gladly accepted.

A: The underlying REST method is projects.serviceAccounts.keys.list and the result is a ServiceAccountKey which contains valid[Before|After]Time which are strings in the protobuf Timestamp.
So, I think this needs to either be a string comparison of dates (!) or comparing durations (but I'm unfamiliar with the duration format and how to compare).
You can convert the validAfterTime to a duration, i.e. --filter=validAfterTime.duration() (see duration) and then compare (!) but as Durations
Or construct a date that's within your scope and compare as-is. The following is hacky, please proceed with caution:
PROJECT=...
ACCOUNT=...

PAST=$(date -d "-90 days" +%Y-%m-%dT%H:%M:%SZ)

EMAIL="${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com"

gcloud iam service-accounts keys list \
--iam-account=${EMAIL} \
--project=${PROJECT} \
--filter="validAfterTime<${PAST}"

I think there's a better way to do this!

A: I've ended up using the above method with ISO dates generated in a script and it seems to be working now. It feels like the kind of thing that should be nicely handled with the filters, but getting it working is taking more time than a bash date


text:
Q: Prompt users to Upload Avatar on Registration I saw a WP site that had users fill in their basic info and then it directed them to upload and Avatar. The site looked nice because most users had a picture even if they were'nt registered with Gravatar.
Is there a plugin for this local Avatar upload?

A: Try this plugin, it adds a upload avatar in the profile edit page.
http://wordpress.org/extend/plugins/user-avatar/

A: You can take a look on this plugin Profile Builder that allows the users to upload their avatars on their registratration, and you can even build your own registration form.