text:
Q: Linq To SQL Attach/Refresh Entity Object In Linq To Sql, when updating one of my entities, Faculty, I am creating a new instance of the Faculty object, then initializing some of the properties with values supplied by the user.
If I attach this new object to the entity set, and submit changes, the properties that I didn't set take on the default value of whatever datatype they are.
How can I refresh the new object so that the properties that have been set keep their values and the properties that haven't been set get the values from the database?
Thanks

A: Did you try
context.Refresh(RefreshMode.OverwriteCurrentValues, faculty);
after submit changes where context is your linq2sql datacontext and faculty is the entity you want to refresh?

A: What about retrieving the object from the database, then changing the appropriate values, then submitting the update?


text:
Q: web-component-tester fails for yeoman generator-polymer With the default Polymer app setup provided from Yeoman generator-polymer 0.7.2 with Gulp selected, Web Component Tester (gulp test:local) is failing with the following error when testing Chrome versions 42 and 43:

Cannot read property 'querySelector' of null
      at   Context. at /app/test/yo-greeting-basic.html:22:0

Line 22 of yo-greeting-basic.html looks like this:
    var header = el.shadowRoot.querySelector('h1');

so it seems the problem is a lack of shadow DOM support.
I also get the error

Cannot read property 'push' of undefined
      at   Context. at /app/test/yo-list-basic.html:23:0

where lines 22-23 of yo-list-basic.html are
    var el = document.querySelector('yo-list');
    el.items.push('Foo');

and yo-list is the name of the Polymer element defined in yo-list.html. I'm guessing it's the same issue -- the items aren't found because they're in the shadow DOM.
I'm on OS X Yosemite 10.10.3 and I have Chrome 42 and 43 installed.
I understand that Chrome Driver 2.14 has shadow DOM support but I haven't been able to find documentation for setting it up with web-component-tester.
Can someone tell me what I need to do to get these tests to work?

A: The error you're seeing is probably because WCT is running its own server and 404ing on the resources coming from bower_components. A recent change moved the bower_components dir out of app and it looks like that broke wct. I'll fix this in the next release which should be going out very soon. I'll update this answer when the new release lands.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disable "Purchase" Button in Android in app purchase Activity I am working on a in App Purchase Project: Here is a code of In app purchase. When i click on "Purchase Item" Button Google In app purchase Dialog box show and after successful payment i get "Payment IS Successful".
Now i want when payment is success full the "Purchase Item" Button Auto Disable when i open this application.
Here is the code of MainActivity:
public class MainActivity extends Activity {

    IInAppBillingService mservice;
    ServiceConnection connection;
    String inappid = "android.test.purchased"; // replace this with your in-app
                                            // product id

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.purchase);

        connection = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {
                mservice = null;
            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mservice = IInAppBillingService.Stub.asInterface(service);
            }
        };

        bindService(new Intent(
            "com.android.vending.billing.InAppBillingService.BIND"),
            connection, Context.BIND_AUTO_CREATE);

        Button purchaseBtn = (Button) findViewById(R.id.purchase);
        purchaseBtn.setOnClickListener(new OnClickListener() {

            @Override
                public void onClick(View v) {
                    ArrayList skuList = new ArrayList();
                    skuList.add(inappid);
                    Bundle querySkus = new Bundle();
                    querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
                    Bundle skuDetails;
                    try {
                        skuDetails = mservice.getSkuDetails(3, getPackageName(),
                        "inapp", querySkus);

                        int response = skuDetails.getInt("RESPONSE_CODE");
                        if (response == 0) {
                            ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");

                            for (String thisResponse : responseList) {
                                JSONObject object = new JSONObject(thisResponse);
                                String sku = object.getString("productId");
                                String price = object.getString("price");
                                if (sku.equals(inappid)) {
                                    System.out.println("price " + price);
                                    Bundle buyIntentBundle = mservice.getBuyIntent(3, getPackageName(), sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
                                    PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
                                    startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
                                }
                            }
                        }
                    }
                    catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    catch (SendIntentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1001) {
            String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");

            if (resultCode == RESULT_OK) {
                try {
                    JSONObject jo = new JSONObject(purchaseData);
                    String sku = jo.getString(inappid);
                    Toast.makeText(MainActivity.this, "You have bought the " + sku + ". Excellent choice,adventurer!", Toast.LENGTH_LONG).show();
                }
                catch (JSONException e) {
                    System.out.println("Failed to parse purchase data.");
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (connection != null) {
            unbindService(connection);
        }
    }
}

A: i think you get result of purchase on onActivityResult, so in that code set clickable your  button to false with following code:
purchaseBtn.setEnabled(false);

you can change background of your button too , that make better visual for disabling button like GrayOut
so your code must be like following:
if (resultCode == RESULT_OK) {
            try {
                JSONObject jo = new JSONObject(purchaseData);
                String sku = jo.getString(inappid);
                Toast.makeText(
                        MainActivity.this,
                        "You have bought the " + sku
                                + ". Excellent choice,adventurer!",
                        Toast.LENGTH_LONG).show();

             // added this two line /////

             purchaseBtn.setEnabled(false);
             purchaseBtn.setBackGroundColor(Color.GRAY);

            } catch (JSONException e) {
                System.out.println("Failed to parse purchase data.");
                e.printStackTrace();
            }
        }

and define purchaseBtn top of your class that you can reach that on this method.
if you want disable button for all time you need save one flag to Share preference or DataBase or Check from internet, i wrote code with SP for you:
 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  SharedPreferences.Editor editor = preferences.edit();
  editor.putBoolean("isPurchase",true);
  editor.commit();

and in onCreate method you need get that to check value:
 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(etApplicationContext());
  boolean isPurchase = preferences.getBoolean("isPurchase",false);
  if(isPurchase )
  {
    // disable your button
  }

A:
"Purchase Item" Button Auto Disable when i open this application

Means you need to first know item is already purchased or not for disable or enable purchase button.For this use mService.getPurchases which return you all the items already purchased by user:
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);

Now if item is already present in ownedItems then disable purchase Button otherwise enable it.
for more information see Querying for Purchased Items


text:
Q: how does return statement work in a void function? This function works fine in a program. But can I get the explanation of the work of return statement in preorder function... if statement?
struct myNode{
    int data;
    myNode *prev, *next;
};

void preOrder(myNode *node) {
    if (node == NULL)
        return;

    cout << node->data << " ";
    preOrder(node->prev);
    preOrder(node->next);
}

A: If the function returns void, return still governs control flow.
In this case, if node is NULL, the function exits immediately, and subsequent code in the function is not executed. By doing so, this particular function ensures that the data member cannot be accessed on a null pointer. This is a common pattern you will see in many functions.
Nitpick: as this is C++ rather than C, nullptr would be more idiomatic than NULL.

A: return means the execution of the function will stop at this line and below lines of code will not be executed. Since below we have node->data and we don't want to access data of node if node is null so we wrote return command there.

A: Void is a valid return result just like anything else. The only difference is there is no object being returned (simply return nothing).
In general whatever the return type of a function, the return statement causes the function to exit, which will cause the return value to be copied (or moved) to the destination location of the call and all local objects (currently initialized) to be destructed. The only difference between void and any other type that copying or moving a non object is very cheap.
void myFunc1()
{
    if (condition) {
        return;   // return nothing (same as void).
    }

    // Do Stuff;

    // Don't need an explicit return for void.
    // But you can have one if you want.
    return;
}

You can also return the result of a void call from another void function.
void myFunc2()
{
    return myFunc1();   // If myFunc1 returns a void.
                        // and this function returns a void.
                        // you have a valid return.
}

I know it does not seem useful. But when you start playing with templates and the return type is not always obvious, it is useful to know that void behaves exactly like other types being returned from a function (except there is no void object itself so is very cheap to construct :-) ).


text:
Q: performance of random forest with the size of dataset? I have two datasets (with 17 features) for the same domain. the first is smaller in size than the second, and a prediction task. I've first tried with several Neural networks configurations, the results were as expected, NNs performed better with the second dataset (the larger one). When I have tried the Random Forest, I've found that it performed much better with the smallest dataset, which I can not understand or explain, because they said that random forest is data-hungry and that Bootstrap resampling is not a cure for small samples.
Can someone explain to me these results?


text:
Q: How to ignore/handle Line Feed (0A) while using fread? I'm currently trying to write a function that will translate each byte of input data into a define constant byte (assembly instruction).
void toASM(FILE *inputFile, FILE *outputFile) {
    char buffer[16 + sizeof(char)] = "";
    int bytes = 0;
    while ((bytes = fread(buffer, sizeof(char), 16, inputFile))) {   // start reading block of data from stream
        for (int i = 0; i < bytes; i++) {
            if (i == bytes - 1) {
                if((buffer[i] != '\r') && (buffer[i] != '\n')) {
                    fprintf(outputFile, "$%.2X\n", buffer[i]);
                } else {
                    printf("\n");
                }
            } else {
                fprintf(outputFile, "$%.2X,", buffer[i]);
            }
        }
    }
}

This function is working correctly the only issue I can't seem to solve is that at the end it will produce a '$0A' which I assume is a Line Feed or maybe a New Line.
My best guess is that my while loop is reading the last line of the input which in result returns '$0A'
Current Output for ABCDEFGHIJKLMNOPQRSTUVWXYZ
$41,$42,$43,$44,$45,$46,$47,$48,$49,$4A,$4B,$4C,$4D,$4E,$4F,$50
$51,$52,$53,$54,$55,$56,$57,$58,$59,$5A,

Output without the check for the Line Feed or New Line
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A, $0A

My desired Output
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A

The current issues is the extra ',' but the bigger issue is that if the input file contains multiple lines of data the ASM output will contain random new lines. This is due to my else statement doing the printf("\n");
So I'm wondering if there is a better alternative to do this?

A: This code shows the technique I usually use.  It considers the comma-space as a prefix to items except the first; the first has an empty string as the prefix (or leading indentation if you want the data indented, or a label, or …).
#include <stdio.h>

static inline int iseol(unsigned char c) { return (c == '\n' || c == '\r'); }

static
void toASM(FILE *inputFile, FILE *outputFile)
{
    unsigned char buffer[16];
    int bytes;
    while ((bytes = fread(buffer, sizeof(buffer[0]), sizeof(buffer), inputFile)) > 0)
    {
        const char *pad = "";
        for (int i = 0; i < bytes; i++)
        {
            if (!iseol(buffer[i]))
            {
                fprintf(outputFile, "%s$%.2X", pad, buffer[i]);
                pad = ", ";
            }
            else if (pad[0] != '\0')
            {
                printf("\n");
                pad = "";
            }
        }
        if (pad[0] != '\0')
            putchar('\n');
    }
}

int main(void)
{
    toASM(stdin, stdout);
    return 0;
}

The iseol() function is probably overkill; using the original test was OK.  Formally, it is a reserved identifier — using is_eol() would be safe, as would isEOL().
The program source was asm67.c, compiled to program asm67.
I test with an input file input with contents:
ABCDEFGHIJKLMNOPQRSTUVWXYZ

The simplest test case yields:
$ asm67 < input
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$

That looks like what you requested.  The following shows the output from 4 lines of input each containing the alphabet plus a newline.  If that's not what you want, you should specify the desired output for such cases in the question.  The futzing required to get the desired output is probably not very complex.
$ cat input input input input | asm67
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$41, $42, $43, $44, $45
$46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50, $51, $52, $53, $54, $55
$56, $57, $58, $59, $5A
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A
$4B, $4C, $4D, $4E, $4F, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F
$50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$

Note that with the 4 lines of input, one of the 16-byte blocks starts with a newline character; the code's logic with if (pad[0] != '\0') prevents that leaving a blank line in the output.
Providing a function that takes an input file stream and an output file stream is a good idea.  And the test program shows how simple it becomes to make use of standard input and standard output for testing.


text:
Q: Translation invariant operators in $L^p$ spaces I am reading the following paper:
Hormander, L., $\textit{Estimates for translation invariant operators in }L^p\textit{ spaces}$, Acta Math. $\textbf{104}$ (1960), no. 1-2, 93-140.
In this paper, the following is the first theorem.
Let $T:L^p(\mathbb{R}^n)\to L^q(\mathbb{R}^n)$ be a translation invariant bounded linear operator ; where $p>q$. Then we have $T=0$ if $p<\infty$ and if $p=\infty$ then the restriction of $T$ to $L_0^{\infty}(\mathbb{R}^n)$ is $0$. (Here, $L_0^{\infty}(\mathbb{R}^n)$ is the space all functions in $L^{\infty}(\mathbb{R}^n)$ which vanishes at infinity.)
I understood the proof for $p<\infty$ but I am stuck for $p=\infty$
.
Here is the sketch of the proof.
Let $f\in L^{p}(\mathbb{R}^n)$. The $\textbf{key step}$ is to prove the following for $p<\infty$.
$$ \|f+\tau_yf\|_p\to2^{\frac{1}{p}}\|f\|_p \text{ as }y\to\infty.$$
In order to establish the above claim, we uses the fact that $C_c(\mathbb{R}^n)$ is dense in $L^{p}(\mathbb{R}^n)$ and so that $f$ can be written as $g+h$ ; where $g\in C_c(\mathbb{R}^n)$ and $\|h\|_p$ is very small. Once we establish the above claim, we can get the desired result very easily by using the fact that the operator norm $\|T\|$ is the smallest such non-negative constant for which $T$ is bounded.
Hormander wrote that the same key step is true for $p=\infty$ when we take $f\in L_0^{\infty}(\mathbb{R}^n)$, i.e.,
$$ \|f+\tau_yf\|_{\infty}\to\|f\|_{\infty} \text{ as }y\to\infty\text{ for }f\in L_0^{\infty}(\mathbb{R}^n).$$
I am unable to prove this key step for $p=\infty$. We don't have this fact that $C_c(\mathbb{R}^n)$ is dense in $L^{\infty}(\mathbb{R}^n).$ But do we say that $C_c(\mathbb{R}^n)$ is dense in $L_0^{\infty}(\mathbb{R}^n)$ ?
Thanks in advance.

A: As a commenter noted, one way to prove this is to observe that $L^{\infty}_c$ is dense in $L_0^{\infty}$. To prove this density take $f\in L^{\infty}_0$ and approximate it by $f_n:=f\cdot \chi_{|x|\leq 2^n}$, where $\chi_{A}$ is the indicator function of the set.
Another way is to argue directly, noting that if $f\in L^{\infty}$ for every $\epsilon>0$ there is an $R$ such that $|f(x)|\leq \epsilon$ for $x\geq R$. Then, if $|y|\geq 2R$, for any point $x$, either $x$ or $x+y$ will be outside the ball of radius $r$ centered at the origin, so
$$
|f(x)+\tau_y f(x)|=|f(x)+f(x+y)|\leq ||f||_{L^{\infty}}+\epsilon.
$$
Thus, $\limsup_{|y|\to \infty}||f+\tau_y f||_{L^{\infty}}\leq ||f||_{L^{\infty}}$.
Also, for any $\epsilon>0$ there exists a point $x$ s.t. $|f(x)|\geq ||f||_{\infty}-\epsilon$. Thus, for $R$ as above, if $|y|\geq R$ then $|\tau_y f(x)|\leq \epsilon$, so
$$
||f(x)+\tau_y f(x)||\geq ||f(x)|-|\tau_y f(x)||\geq ||f||_{L^{\infty}}.
$$
Because of this, $\liminf_{|y|\to \infty}||f+\tau_y f||_{L^{\infty}}\geq ||f||_{L^{\infty}}$ which finishes the proof.


text:
Q: character to date in R using as.Date() but the answer that gives is the same date again and again I'm trying to make my column named Date18 from character to date but the answer that I can get by using the function as.Date() is something very different. Also, I have a large sample of values.
str(coo)
'data.frame':   7698 obs. of  2 variables:

 $ Date18: chr  "1/3/2018 9:06" "1/3/2018 10:14" "1/3/2018 10:19" "1/3/2018 10:30" ...

 $ Amount: num  21 16.8 10.5 43.7 4.2 ...

coo$Date18=as.Date(coo$Date18)
str(coo)

'data.frame':   7698 obs. of  2 variables:

 $ Date18: Date, format: "0001-03-20" "0001-03-20" ...

 $ Amount: num  21 16.8 10.5 43.7 4.2 ...

You can see that the format of the date changed. How can I transform the date but my values will not change?

A: With as.Date, we need to specify the format if it is not the default format ("%Y-%m-%d")
as.Date(coo$Date18, "%m/%d/%Y %H:%M")

NOTE: Here it seems that it is month then day. If it is day then month, use as.Date(coo$Date18, "%d/%m/%Y %H:%M"). Additionally, keep in mind that the Y has to be capitalized if the year is four numbers long e.g. 2001 and lowercase if the year is two numbers long e.g. 01.


text:
Q: ubuntu 12.04 - keep getting "Server not found" for some websites  ever since last week , i've noticed that many websites cannot be accessed , and it doesn't matter if i use firefox or chromium as a web browser .
as an example of such a website is:
http://tutorials-android.blogspot.co.il/2011/05/layout-animation-in-android.html
all i get is a "Server not found" error page . sometimes after a few refreshes it works just fine .
i've checked it on a windows OS machine that is connected to the exact same LAN network , and the website is shown just fine .
i've also checked the /etc/hosts file and it doesn't contain anything suspicious .
what is going on? how can i fix it?


text:
Q: Laravel Migration is not creating the table in different database I have this migration file:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::connection('DB1')->create('feed_mappings', function (Blueprint $table) {
            $table->bigIncrements('id_feed')->autoIncrement();
            $table->string('id_project', 255);
            $table->string('import_field_slug', 155);
            $table->string('internal_field_slug', 155);
            $table->tinyInteger('import');
            $table->tinyInteger('custom_field')->default(0);
            $table->dateTime('date_add');
            $table->dateTime('date_upd');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('feed_mappings');
    }
};

And I have this config in the database.php file:
'mysql' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => 'InnoDB',
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

'DB1' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '8889'),
    'database' => env('DB_DATABASE', 'DB1'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', 'root'),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => 'InnoDB',
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

Now, I have run this command :

php artisan migrate:refresh --seed

Now, All the migration file is creating a tables on default database but I want this feed_mappings should go to DB1 database.
BUT this feed_mapping is not going to DB1 database. Can you tell me why?

A: So the issue is in your database.php file where you are using the same variables for connections 1 and 2
'mysql' => [
    'driver' => 'mysql',
    ***'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),***
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => 'InnoDB',
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

'DB1' => [
    'driver' => 'mysql',
    **'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '8889'),
    'database' => env('DB_DATABASE', 'DB1'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', 'root'),**
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => 'InnoDB',
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

what you need to do is create separate variables for db connections e.g:
DB_HOST // for connection 1
DB_HOST_2 // for connection 2

and use these in your config files for more info visit: https://codelapan.com/post/how-to-use-multiple-database-connections-in-laravel-8

A: config/database.php
'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

        'mysql2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST_2', '127.0.0.1'),
            'port' => env('DB_PORT_2', '3306'),
            'database' => env('DB_DATABASE_2', 'forge'),
            'username' => env('DB_USERNAME_2', 'forge'),
            'password' => env('DB_PASSWORD_2', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

Setup .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_multiple_database1
DB_USERNAME=root
DB_PASSWORD=

DB_CONNECTION_2=mysql
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=laravel_multiple_database2
DB_USERNAME_2=root
DB_PASSWORD_2=

in Model example Post
protected $connection = 'mysql2';

in migration file
public function up()
 {
    Schema::connection('mysql2')->create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->timestamps();
    });
}

public function down()
{
    Schema::connection('mysql2')->dropIfExists('posts');
}


text:
Q: Flutter: How to declare HashMap of StreamSubscription I have declared hash map for subscriptions, like this:
HashMap<String, StreamSubscription<Event>> = subscriptions

But when i am filling values, it show for me, that types doesn't match. Error tells that Argument of type StreamSubscription<Event> can't be assigned to parameter of type StreamSubscription<Event> Function().
When i am creating dirrectly variable like this:
StreamSubscription<Event> e = subscription.eventStream.listen((event) {
  print(event.arguments[0]);
});

It shows that type is correct.
So how should i declare hashmap of HashMap<String, StreamSubscription<Event>>, if
_subscriptions.putIfAbsent(uri, e);

doesn't work.


text:
Q: I am trying to refer a "Box" object to another "Box" object via a method declared inside the "Box" class I am trying to write a method where a reference to an object will refer to another object.
Here I created two "Box" objects, now if I want box and box2 both to refer to box2, I could have written box=box2, but I want to do the same thing via a method which I wrote as "public void change(Box b) {}", but it isn't working.
As far I know Java passes argument to parameters as "call by reference". But when I write "box2.change(box);" the "box" object still refers to original "box" instead of "box2"
public class Main {
    public static void main(String[] args) {
        Box box = new Box(50, 50);
        box.show();

        Box box2 = new Box(100, 100);
        box2.show();

        box2.change(box);
        // After applying method
        box.show();
    }
}

class Box {
    int height;
    int width;

    Box(int h, int w) {
        this.height = h;
        this.width = w;
    }

    public void change(Box b) {
        b = this;
    }

    public void show() {
        System.out.println("H: " + this.height + " " + "W: " + this.width);
    }
}


text:
Q: Vue: Async Apollo mixin function prints a value, but returns undefined Async/return undefined queries are common on here but I've tried all permutations of answers and seem to be getting nowhere... Apologies if I couldn't find it.
I have taken all Apollo mutations out of my main Vue code into a global mixin so I can reuse, however I'm clearly not getting the async/promise syntax correct for one of the queries.
This is the mixin function:
async DBgetGroupName(id) {
      if (id == null) {
        return process.env.VUE_APP_DEFAULT_GROUP_NAME;
      } else {
        await this.$apollo
          .query({
            query: GET_GROUP,
            variables: {
              id: id,
            },
          })
          .then((data) => {
            let ret = data.data.groups[0].group_name;
            return new Promise((resolve, reject) => {
              if (ret !== undefined) {
                console.log("Return value is " + ret);
                resolve(ret);
              } else {
                reject("Error");
              }
            });

      })
    }}

And this is the calling watcher.
watch: {
     selected: async function() {
      let vars = {
        id: null,
        name: "",
      };

      vars.id = this.selected;
       this.DBgetGroupName(vars.id).then((data) => {
        console.log("Name is " + data);
      });
    },
  }

Other permutations I've tried are simply returning the 'ret' value without wrapping in a promise, and using
let data = await this.DBgetGroupName(vars.id)

in the watcher instead of the then block. The result in the console is always
Return value is Test Group [or whichever group I've selected, ie the correct value]
Name is undefined

What am I missing? Why isn't the value coming through to the watcher?
Thank you for any advice.

A: It turns out that I'm dealing with nested promises. What I didn't realize is that the Apollo query itself is a promise, and anything returned within that block is actually returning to that promise, rather than to any calling function.
So
     async DBgetGroupName(id) {
      if (id == null) {
        return process.env.VUE_APP_DEFAULT_GROUP_NAME;
      } else {
        await this.$apollo. // this call returns a promise
          .query({
            query: GET_GROUP,
            variables: {
              id: id,
            },
          })
          .then((data) => {
            let ret = data.data.groups[0].group_name;
            console.log("Return value is "+ret)
            return ret // this returns to the above promise, not the overall function
          });
    }},

Doesn't return anything, hence undefined.
So therefore to get it to work I just needed to return the initial promise, which would then return the ultimate return value when it is resolved.
Consequently, the calling function can just use await, rather than the then block.
Final, correct code:
     async DBgetGroupName(id) {
      if (id == null) {
        return process.env.VUE_APP_DEFAULT_GROUP_NAME;
      } else {
        return await this.$apollo  //return this promise
          .query({
            query: GET_GROUP,
            variables: {
              id: id,
            },
          })
          .then((data) => {
            let ret = data.data.groups[0].group_name;
            console.log("Return value is "+ret)
            return ret. //value provided to above promise for returning
          });
    }},

and calling watcher:
     selected: async function() {
      let vars = {
        id: null,
        name: "",
      };
      vars.id = this.selected;
      let data = await this.DBgetGroupName(vars.id)
      console.log("Name is " + data);
    },


text:
Q: Woocommerce Cart won't update after changing quantity and clicking Update Cart When I change the cart quantity and then click the Update Cart button, the price does not update. If I click the Update Cart button again, then it works as it should. Anyone have an idea as to why this might be occurring?
http://cmscolorado.staging.wpengine.com/cart/

A: There's an error appearing in the console when I try and update the product quantity on the cart page.
Failed to load https://cmscolorado.staging.wpengine.com/cart/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://cmscolorado.staging.wpengine.com' is therefore not allowed access.

Research how to fix that and your cart should work again.


text:
Q: SQL - Separate Out Text From String I have a table (in SQL Server) that has 2 columns. One column contains multiple server names separated with a tilda ~. This column could or could not contain the actual server name. The other column has the actual server name.
I am looking for a way to separate the first column values into their own separated column. The number of aliases range from 1 to ?.
Server_Alias_Names                              Actual_Server_Name
------------------------------------------------------------
Server1~ROSCO24~Server3~Server4~~~~~            ROSCO24
STEVETESDB26~~~~~~~~~                           STEVETESDB26
RALPHPRD117~RALPHPRD117-adm~Server0025~Server0025a1~Server0025a2~Server0025a3~~~~~        RALPHPRD117
Server1001~Server1001R1~Server1001-adm~~~~~~~   DBTEST1001

I have the first two servers extracted from the string, I am having trouble on the next few.  Any help is appreciated!!!
SELECT
    LEFT(Server_Alias_Names, CHARINDEX('~', Server_Alias_Names) - 1) as 'First_Server',
SUBSTRING(Server_Alias_Names,len(LEFT(Server_Alias_Names, CHARINDEX('~', Server_Alias_Names)+1)),LEN(LEFT(Server_Alias_Names, CHARINDEX ('~', Server_Alias_Names)))) as 'Second_Server'
FROM
    TBL_NAME

A: The easiest way to accomplish this is with a string splitter. Aaron Bertrand has fairly complete list of viable options here. http://sqlperformance.com/2012/07/t-sql-queries/split-strings. Notice that none of these have any loops or recursion. I am not quite sure what you are trying to do with this information but you stated you just wanted to parse the strings.

A: WITH splitit
AS
(
    SELECT Actual_Server_Name,  len(Actual_Server_Name) - len(replace(Actual_Server_Name, '~', '')) as TildaCount,
    CONVERT(XML,'<X><x>'
    + REPLACE(Server_Alias_Names,'~', '</x><x>') + '</x></X>') AS xmlname
      FROM table
)
SELECT Actual_Server_Name,
       CASE TildaCount > 0 THEN xmlname.value('/X/x[1]','varchar(100)') ELSE '' END AS s1,
       CASE TildaCount > 1 THEN xmlname.value('/X/x[2]','varchar(100)') ELSE '' END AS s2,
       CASE TildaCount > 2 THEN xmlname.value('/X/x[3]','varchar(100)') ELSE '' END AS s3,
       CASE TildaCount > 3 THEN xmlname.value('/X/x[4]','varchar(100)') ELSE '' END AS s4,
       CASE TildaCount > 4 THEN xmlname.value('/X/x[5]','varchar(100)') ELSE '' END AS s5,
       CASE TildaCount > 5 THEN xmlname.value('/X/x[6]','varchar(100)') ELSE '' END AS s6,
       CASE TildaCount > 6 THEN xmlname.value('/X/x[7]','varchar(100)') ELSE '' END AS s7
FROM splitit

You can also remove extra ~ from the end if you want, but I think it will work even if you don't.

A: @Hogan - I ended up combining your script with some help from the link that @Sean Lange put in his comment.  Here is what I came up with.
WITH splitit
AS
(
SELECT
y.i.value('(./text())[1]', 'nvarchar(4000)') as Separated_Server,
Actual_Server_Name
FROM
          (
            SELECT x = CONVERT(XML, ''
            + REPLACE(Server_Alias_Names,'~', '')
            + '').query('.')
            , Actual_Server_Name
            FROM TBL_NAME
          ) as a cross apply x.nodes('i') as y(i)
)

SELECT DISTINCT
Actual_Server_Name,
Separated_Server
FROM splitit
Where Separated_Server is not null
ORDER BY 1,2

--Some of the separated items were also sorted by a comma so I added another step to separate those as well.
--Uncomment the code below for an additional and replace the comma after Separated_Server with the special character you want to use for separation

--,splitit_2
--AS
--(
--SELECT distinct
--ServerName,
--y.i.value('(./text())[1]', 'nvarchar(4000)') as Server_Alias

--FROM
--          (
--          SELECT x = CONVERT(XML, ''
--          + REPLACE(Separated_Server,',', '')
--          + '').query('.')
--          ,[ServerName]
--          FROM splitit
--        ) as a cross apply x.nodes('i') as y(i)
--)

--SELECT DISTINCT
--Actual_Server_Name,
--Separated_Server
--FROM splitit_2
--Where Separated_Server is not null
--ORDER BY 1,2


text:
Q: vim script leaves characters in stdin I'm trying to use vim with -s option to run a script that replaces some lines in a file like this (text.txt):
test1
ab
ac
ae
test2
sd

Script file is like this (script):
:silent %s/test1\zs\_.\+\zetest2/\=substitute(submatch(0), '\n\(\w\)', '\n#\1', 'g')/g
:wq

It comments out lines between test1 and test2. Which is what I want. What I don't want though is output before and after prompt. I run it and get:
user@hostname: ~/vimtest$ vim -s script text.txt
^[[?1;2cuser@hostname: ~/vimtest$ 1;2c

So this ^[[?1;2c is bad news already but 1;2c is in the input as if I already typed it. If I hit enter it gives me a bash error. So I have to remove these symbols each time the script is used. Any ideas?

A: It seems like vim (or some vim startup script) is trying to figure out what type of terminal you are using. The ^[[?1;2c, with the last few characters left in the input buffer, is almost certainly part of your terminal emulator's response to a DA (Device Attributes) query. You can see this yourself by typing in bash:
printf '\033[c'

or, to see the complete return, pause a bit:
printf '\033[c'; sleep 0.1; echo

The response \033[?1;2c means "I'm a VT100 with Advanced Video Option.", which is what xterm and many other console programs respond. (The Linux console itself responds \033[?6c, which means "I'm a VT102.")
The reason that only 1;2c is left in the console input buffer, by the way, is that the initial escape code \033[? was ignored when it was read. The readline library will ignore it without echoing it, whereas normal console input will echo it and then ignore it; that's why the two shell commands above differ.
I can't reproduce this problem with my vim installation, so I don't really even know where to start looking. But you might try to see if disabling all startup files helps:
vim -u NONE -s script text.txt

If that helps, start disabling installed extensions one by one until you find the one which is causing the problem.

A: :%s/test1\zs\_.\+\ze\ntest2/\=substitute(submatch(0), '\n', '\n#', 'g')/g
:wq

this is tested here, it changed the input file in required way.
Some changes done based on your command:

*

*add \n after \ze

*in substitute() function we can just handle the \n, we don't need to capture the word after the \n

A: I noticed that you tagged the question with bash, so I thought a shell-solution should be accepted too.
awk '/test1/{p=1;print;next}/test2/{p=0;print;next}{$0=(p?"#":"")$0}7' file

this awk oneliner should do that for you. vim is very powerful editor, I love vim. But if you want to do some automatic transformation, I prefer a script or a proper text processing tool. On a linux box you can always find one. It is easier to test and debug.
Test with your input:
kent$  cat f
test1
ab
ac
ae
test2
sd

kent$  awk '/test1/{p=1;print;next}/test2/{p=0;print;next}{$0=(p?"#":"")$0}7' f
test1
#ab
#ac
#ae
test2
sd

If you want to save the text back to your file, you can :
awk '...' file > tmp.file && mv tmp.file file


text:
Q: Testing if $p(A|X,Y) \le p(A|X)$ holds Consider three events $A$, $X$ and $Y$. My intuition tells me, for a specific problem that I am working on, that the following inequality may always hold:
$p(A|X,Y) \le p(A|X)$
How do we go about proving (or disproving) it using  probability axioms, Bayes rule, or an intuitive example
My attempt using Bayes rule takes me to:
$$p(A|X,Y) = \frac{P(A,X,Y)}{p(X,Y)}$$
$$p(A|X) = \frac{\sum_Y{P(A,X,Y)}}{\sum_Y{p(X,Y)}}$$
so the question is, why would the following satisfy?
$$\frac{P(A,X,Y)}{p(X,Y)} \le \frac{\sum_Y{P(A,X,Y)}}{\sum_Y{p(X,Y)}}$$

A: If your claim holds, you can take $X$ to be the universal event, and you are implying that $P(A|Y) \le P(A)$ for all $A$ and $Y$, which is false.

A: Consider $X=$ "it is Wednesday", $Y=$ "it is raining" and $A=$ "I am carrying an umbrella"
Are you still confident that $P(A|X,Y)\leq P(A|X)$?
[The trick when coming up with an intuitive idea is not to seek confirmatory examples - our natural tendency - but to try to identify examples that would show it to be wrong. It wasn't hard to think of one where $A$ was more likely to be the case when $Y$ held.]

A: I would suggested going over Chapter 1 and 8 of Bishop's Pattern Recognition and Machine Learning book to understand why exactly this does not hold. I would start from page 372 onwards and get back to Chapter 1 if I didn't understand any of the concepts there.


text:
Q: Test automation Google Apps Script Gmail Add-ons I am working on Gmail Add-on using Google Apps Script. I am using Clasp to develop it on locally then using this I am pushing it to script.google.com.
In local, I can do Unit testing using any JavaScript testing framework.
But is there any way to do Integration testing and automate it?

A: You may refer with this link on how to do Automated Tests for Google Apps Script. You may also check the code and an example of how to use it. There is also a node-google-apps-script package to allow using standard JavaScript packages and automated testing tooling based from this post.


text:
Q: Inertia of a falling weight I use a standard device (penetrometer) that uses a 10 kg weight that is dropped a constant distance to cause a probe to penetrate soil. The penetration distance after 4 blows is recorded. If I were to use a 9 kg weight and increase the distance by 10% would the force being exerted be the same?

A: Well then we know $v=\sqrt{2gh}$ when you throw the weight. The impulse is $mv/\delta t = m\sqrt{2gh}/\delta t$ where $\delta t$ is time of contact regarded as same in both cases. Now in first case $10\sqrt{2gh}$ and in second $9\sqrt{2.2gh}$ [h*110/100= 1.1h] so clearly $10\sqrt2 >9\sqrt{2.2}$ so in the first case the probe will feel more fore hence more soil entering. And as well as the soil would offer a resistance of a then the penetration is $u^2/2g$ which would be more in first case rather than the second even after 4 blows. **** in case if you want to get at what height the 9 kg and the 10 kg make the same impact( or give the same force). then: $momentum_1=momentum_2${as $\delta t $ is same in both cases. $10\sqrt{2gh}= 9\sqrt{2g(h+x)}$  upon solving this we get $x=\frac{19h}{81}$ so for example if you make the 10 kg fall from 81 cm then 9kg has to fall from a height of 81+ (19/81)*81=100 cm to have same force on the probe. ******Now in case if your 9kg hammer falls 510mm then $h\times (1+19/81)= 510$ upon calculating for height of 10 kg i get 413.1 mm. So by making the 10 kg hammer  fall 413.1 mm would apply same force as you 9kg hammer galling from 510mm.


text:
Q: c prog of tcp/ip client server .in server counts how many clients visited to the server.it works for multiple clients at same time I already tried the server prog  but server can't distinguish between the clients please help me.
A client server program in which server counts the no of client's visited to the server.
Server handles the multiple client at same time.

A: A connection is always uniquely identified by two things: The "clients" address/port, and the "servers" address/port. The most common way to uniquely identify a client is to use its address/port pair.
Or if you just want to have a simple but unique small integer value, you can use the fact that the most common implementations use just a small integer value for the actual socket.
In C++ you could, for example, use a std::unordered_map to store the data for each connection. Use the socket as the key, and a structure containing the needed data for the map data.
In C you most likely use a simple single-link list for the connection data, each structure containing the socket. To find the data corresponding to a specific socket just iterate over the list to find it.


text:
Q: Formatting HTML tables populated using AMPscript, loop and lookup ordered rows I'm attempting to fill out a table in an email with a DE contact's order info, using AMPscript/HTML. Am working in an HTML block. I have two sets that work in different circumstances but not all. Goal is to send one email, even if there are multiple orders per contact, and break each order into its own table labelled by order number.
Here's the first:
  %%[
var @rows, @row, @rowCount, @numRowsToReturn, @contactid, @i, @prevOrderNo

set @contactid = AttributeValue("Contact ID")
set @numRowsToReturn = 0 /* 0 means all */
set @rows = LookupOrderedRows("Order Follow Up", @numRowsToReturn, "Order Number", "Contact ID", @contactid)

set @rowCount = rowcount(@rows)

if @rowCount > 0 then

    set @prevOrderNo = ""

    for @i = 1 to @rowCount do

        var @OrderNo, @itemid, @price, @qty
        set @row = row(@rows,@i)

        set @OrderNo = field(@row,"Order Number")
        set @itemid = field(@row,"Item ID")
        set @price = field(@row,"Price")
        set @qty = field(@row,"Qty")

 if empty(@prevOrderNo) or @prevOrderNo != @OrderNo then
           outputline(concat("
Order #", @OrderNo, "
"))
           outputline(concat('

               QTY
               ITEM
               PRICE
'))
           set @prevOrderNo = @OrderNo
        endif

          outputline(concat("
", @qty, "	"))
          outputline(concat("", @itemid, "	"))
          outputline(concat("", @price, "

"))
next @i
outputline(concat("
"))
else

    outputline(concat("
No transactionsList rows found"))

endif
]%%

The above works when the recipient has more than one item on an order, but when they have more than one order per email, it breaks down. The tables for both orders get misplaced below the second order number.
Below is the second I tried. Before making you scan it all, note the main difference is the placement of the closing
 tag. I suspect this is the culprit but am not sure how else to fix it within constraints of the AMPscript, specifically the loop.
  %%[
var @rows, @row, @rowCount, @numRowsToReturn, @contactid, @i, @prevOrderNo

set @contactid = AttributeValue("Contact ID")
set @numRowsToReturn = 0 /* 0 means all */
set @rows = LookupOrderedRows("Order Follow Up", @numRowsToReturn, "Order Number", "Contact ID", @contactid)

set @rowCount = rowcount(@rows)

if @rowCount > 0 then

    set @prevOrderNo = ""

    for @i = 1 to @rowCount do

        var @OrderNo, @itemid, @price, @qty
        set @row = row(@rows,@i)

        set @OrderNo = field(@row,"Order Number")
        set @itemid = field(@row,"Item ID")
        set @price = field(@row,"Price")
        set @qty = field(@row,"Qty")

 if empty(@prevOrderNo) or @prevOrderNo != @OrderNo then
           outputline(concat("
Order #", @OrderNo, "
"))
           outputline(concat('

               QTY
               ITEM
               PRICE
'))
           set @prevOrderNo = @OrderNo
        endif

          outputline(concat("
", @qty, "	"))
          outputline(concat("", @itemid, "	"))
          outputline(concat("", @price, "

"))
next @i

else

    outputline(concat("
No transactionsList rows found"))

endif
]%%

This one works in reverse: if there are multiple orders in an email, it's great. But if there are multiple items in one order, it fails to place subsequent line items in the same table as the first.

A: In the second example, your table is closing at the end of the first @i rotation, so none of the other @i's will display. Try putting the closing table tag outside of the ampscript loop after the next i. You will need to have this section of ampscript in the relevant HTML section of the page itself, not just in the header.

A: Call it a matter of personal tastes, but I would avoid outputline in favor of actual html with inline ampscript. at least to me, all sense of indentation is lost in your examples, and the code gets much harder to read. I think as a result, logical connections get blurred that a normally formatted HTML would visualize better.
So by restructuring the code in that manner, I think I found a reason why you do not see the intended behavior: your s and the different parts of the table are inside and outside of an IF condition, and that condition changes during your loops. So you might get stuck with unmatched pairs, e.g. an unclosed table. See below for my untested attempt. For each order with an order #,  is always there. All content inside of the table(s) is shown if your prevOrder condition is met. Might not be 100% accurate but this is where I would start.
%%[

set @contactid = AttributeValue("Contact ID")
set @numRowsToReturn = 0 /* 0 means all */
set @rows = LookupOrderedRows("Order Follow Up", @numRowsToReturn, "Order Number", "Contact ID", @contactid)
set @rowCount = rowcount(@rows)

IF @rowCount > 0 THEN

  set @prevOrderNo = ""
  FOR @i = 1 to @rowCount do
    set @row = row(@rows,@i)
    set @OrderNo = field(@row,"Order Number")
    /* create a table for each order */

    If not empty(@orderNo) THEN
    ]%%

      Order #%%=v(@OrderNo)=%%

      %%[
      set @itemid = field(@row,"Item ID")
      set @price = field(@row,"Price")
      set @qty = field(@row,"Qty")
      IF empty(@prevOrderNo)
      or @prevOrderNo != @OrderNo
      THEN
        /* if condition for order display is met, show table content */
        ]%%

         QTY
         ITEM
         PRICE

          %%=v(@qty)=%%
          %%=v(@itemid)=%%
          %%=v(@price)=%%

      %%[
        set @prevOrderNo = @OrderNo
      ENDIF
      ]%%
      /*close each table unconditionally*/

      %%[
    ENDIF
  NEXT @i
ELSE
  ]%%

No transactionsList rows found
  %%[
ENDIF
]%%


text:
Q: Where is dovecot installed on Mac? I am attempting to set up pop3 and smtp server on my mac mini (OS X 10.15.7, Catalina).
I found postfix already installed based on the fact that "com.apple.postfix.master.plist" and "com.apple.postfix.newaliases.plist" files in /System/Library/LaunchDaemons/ directory. In addition, "main.cf" and "master.cf" files are in /etc/postfix/ directory.
I then searched dovecot on my mac and I cannot find .plist nor any configure files.
However, "_dovecot" user exists as a result of the command "dscl . list /Users."
Could anyone tell me how I can find pre-installed dovecot on mac?
Or, should I install dovecot by myself, for example, through Homebrew or something?
I am asking this question in order to avoid any discrepancy or confusion caused by installing dovecot other than the preinstalled one.
Thank you in advance for any reply.

A: Used to come bundled with OS X Server but that was ages ago and you mentioned that you are running Catalina, so not likely.
The user you found is present on a clean Big Sur installation as well, probably remnant from the past.
You can safely brew install dovecot.


text:
Q: How to print only Machine Accounts with pdbedit? Using pdbedit, I can use --list to list all Samba entities in the NT4 domain - users and computers. What I need to do is list only the Machine accounts - accounts that end in a $ (i.e. Computer-01$).
How can I do that? Using Samba 4.2.14 on Debian Jessie.

A: What I need to do is list only the Machine accounts - accounts that end in a $
You can do this with grep:
pdbedit --list | grep "\$$"

This will match all lines ending in a literal $ character.


text:
Q: Truncate similar lines to discard difference in sorted file Lets assume I have a log file full of errors. but of just a handful of types.
com.company.exception.ExceptionOne: customer cart is empty for customerId: QWEDSA
com.company.exception.ExceptionOne: customer cart is empty for customerId: fdsadf
com.company.exception.ExceptionOne: customer cart is empty for customerId: ...
com.company.exception.ExceptionOne: customer cart is empty for customerId: ---
com.company.exception.ExceptionTWO: ITEM NOT FOUND on purchase: ---
com.company.exception.ExceptionTWO: ITEM NOT FOUND on purchase: ...
com.company.exception.ExceptionTWO: ITEM NOT FOUND on purchase: ---
com.company.exception.ExceptionTWO: unknown error.
com.company.exception.ExceptionTHREE: error found while requesting from service A {requestId: 1, ...}
com.company.exception.ExceptionTHREE: error found while requesting from service A {requestId: 2, ...}

Ideal output:
4 com.company.exception.ExceptionOne: customer cart is empty for customerId:
3 com.company.exception.ExceptionTWO: ITEM NOT FOUND on purchase:
2 com.company.exception.ExceptionTHREE: error found while requesting from service A {requestId:
1 com.company.exception.ExceptionTWO: unknown error.

It'd be easy if similar lines were identical with uniq -c | sort -bgr

A: Looking at your sample log entries, you are lucky, all the fields you want to ignore are located after the second :.  You could therefore do:
cat log | cut -d':' -f1-2 | uniq -c | sort -bgr

Where log is the filename of your log file.  Replace to match your reality.


text:
Q: Upper bound on complement of tail event for a normal distribution Let $X\sim N(0,1)$. I know about Chebyshev's to find an upper bound on $P(X>x)$. I also know about this concentration inequality which is sharper than Chebyshev's for a normal distribution: $P(X>x)\leq \phi(x)/x$ where $\phi(\cdot)$ is the density of standard normal distribution and $x>0$.

But how can I find an upper bound, preferably tight, on $P(0<X<x)$ where $x>0$?

A: There is a corresponding lower bound for your sharper inequality: $$\frac{x}{1+x^2} \phi(x) \le P(X > x) \le \frac{1}{x} \phi(x).$$ [See Wikipedia]
This can then be converted into an upper bound for $P(0 < X < x)$.


text:
Q: How can I redirect to an exact URL with Serenity + cucumber? I'm making automation test and in one step I want to redirect to an exact page but not through a button or some UI action, just like when you write an URL in the explorer. I'm using serenity.conf and not Driver myDriver = new Driver();

A: If I understand truly;
This should be your page class with @DefaultUrl annotation;
@DefaultUrl("https://google.com ")
public class GoogleHomePage extends PageObject {

   // Some Code
}

After that you can call that like;
public class NavigateTo {

    GoogleHomePage googleHomePage;

    @Step("Open google homepage")
    public void googleHomePage() {

        googleHomePage.open();
    }
}

A: @NameUrls(
         {
           @NameUrl(name = "OrangeHRM_Page", url = "/index.php/auth/{1}")
         }
)

public class HomePage extends PageObject{

}

public class NavigatePage extends PageObject{
HomePage homePage;

@Steps("Open Home Page")
public void goToHomePage(){
     //with parameter will helpful to redirect to specific page mentioned
    homePage.open("OrangeHRM_Page", withParameters("requestPasswordResetCode"));
}
}

In the serenity.properties file:
webdriver.driver = chrome
webdriver.base.url = https://opensource-demo.orangehrmlive.com/


text:
Q: Changing php form to submit a styled email (HTML email) When I submit my form, I receive the email in plain text and not quite in the format I'd like it to be. I'd like it to at least have color to the body and arrange the email so that its neater.
on the contact.php form ... this is what I currently have:
     $msg  = "You have been contacted by $name with regards to Accommodation.
They passed verification and their message is as follows." . PHP_EOL . PHP_EOL;
     $msg .= "$comments" . PHP_EOL . PHP_EOL;
     $msg .= "You can contact $name via email, $email or via phone $phone." .
PHP_EOL . PHP_EOL;
     $msg .= "We want to stay from the $dayin to the $dayout" . PHP_EOL .
PHP_EOL;

Why is this form using $msg? I've seen in other forms, they use $message.
Can I add CSS styling to the above form?
I also see:
        $headers = "From: $email" . PHP_EOL;
    $headers .= "Reply-To: $email" . PHP_EOL;
    $headers .= "MIME-Version: 1.0" . PHP_EOL;
    $headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
    $headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;

Would I need to change "plain" to "HTML"?
Any suggestions or examples would be great!

EDIT:
Ok so now my header are:
    $headers = "From: $email" . PHP_EOL;
    $headers .= "Reply-To: $email" . PHP_EOL;
    $headers .= "MIME-Version: 1.0"  . "\r\n" . PHP_EOL;
    $headers .= "Content-type: text/html;charset=iso-8859-1" . "\r\n" .
 PHP_EOL;
    $headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;

Do I need PHP_EOL in each header?
My $msg looks like:
$msg  = '

Submission / Enquiry from your website

 ........................................................................

Date Submitted

    '. date("F j, Y, g:i a") .'

Name

    '.$_POST['name'].'

Email

    '.$_POST['email'].'

Phone

    '.$_POST['phone'].'

Day in

    '.$_POST['dayin'].'

Day out

    '.$_POST['dayout'].'

Comments

    '.$_POST['comments'].'

';

EDIT:
MY NEW HTML EMAIL DESIGN:

Submission from

Your website

Name:
'.$_POST['name'].'

Email:
'.$_POST['email'].'

Phone:
'.$_POST['phone'].'

Day in:
'.$_POST['dayin'].'

Day out:
'.$_POST['dayout'].'

Comments:

'.$_POST['comments'].'

Now when I add this form in my php and submit my form ... I receive my submission that doesn't look like the table layout like above.

A: You can use the following headers. These will allow you to just put normal HTML in your message.
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";

// More headers
$headers .= 'From: <example@example.com>' . "\r\n";
$headers .= 'Cc: example two@example.com' . "\r\n";

A: Yep you are going to have to use
Content-type:text/html;charset=iso-8859-1\r\n

It might be a good idea to provide your email in both HTML and text formats as not all email applications support HTML, and many others support it poorly.
To do so use this header instead. The boundary thing is what separates the HTML and text versions in the email, the line below generates a unique code which is suitable for this purpose
$boundary = md5(date('r', time()));
$headers .= "\r\nContent-Type: multipart/alternative; boundary=$boundary."\"";

Before the text version of the email post this code, note the "--" at the begging. You use the same boundary throughout the email.
--<?php echo $boundary; ?>

Before the HTML version post the same code again
There is a good template you can use here
http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php


text:
Q: Appending large data files using first few observations I am appending in Stata several data sets in a folder using this code:
! dir *.dta /a-d /b >"${cleandata}/$year/filelist.txt"

file open myfile using "${cleandata}/$year/filelist.txt", read
file read myfile line

use `line'
save "${outcomedata}/master_$year.dta", replace

file read myfile line

while r(eof)==0 {
    append using `line'
    file read myfile line
}

file close myfile

save master_data, replace

However, I want to try this with the first 10 observations in each dta file because I want to make sure that this works before appending every file.

A: You can modify your code as follows:
! dir *.dta /a-d /b >"${cleandata}/$year/filelist.txt"

file open myfile using "${cleandata}/$year/filelist.txt", read
file read myfile line

use `line' in 1/10
save master_data

file read myfile line

while r(eof) == 0 {
    use `line' in 1/10, clear
    append using master_data
    save master_data, replace
    file read myfile line
}

file close myfile


text:
Q: Organizing repeated measures data with a grouping variable for MLM I just started reading about multilevel modeling so I can apply the method to my research data. However, I have yet to come across an illustrative example or even discussion how to organize and set up a model for a repeated-measures design with a grouping variable to counterbalance across materials.
For example, let's say I want to look at the effect difficulty level of paragraph has on time to read a target sentence embedded within each paragraph. To test this, I create 6 paragraphs, in which there are three versions of each paragraph: Difficult (D), Moderate (M), Easy (E). Participants get exposed to all three levels of difficulty but only read one version of each paragraph. So, reading material is repeated-measures, but the specific paragraph participants get differs. To counterbalance across difficulty levels, participants also get different orders of conditions with the restriction that each condition appears in each position an equal number of times (this is the grouping variable; order is a between subjects variable)
So, for the sake of counterbalancing, I administer three different orders of the six paragraphs for the following participants: Beth: DME EDM (order 1) John: MED DME (order 2) Mary: EDM MED (order 3)
So, you can see that everyone gets all levels of difficulties but for different paragraphs.
The dependent measure is the time to read a target sentence for each paragraph. Here is a tabular display of fictitious data of reading time laid out by the experimental design:

So, my first question is, how do I organize the data to prepare for MLM to reflect the order grouping variable and three levels of difficulty, repeated measures? Then how should I start thinking about incorporating random effects into the model?

A: The way you have presented the data in the table is a start but needs some additions and changes in order to analyze the data using a mixed modeling framework. The most important thing is that each subject has multiple rows corresponding to a repeated measure. The time to read measure needs to be in its own column. Then you want to create categorical variables representing each of the conditions: version with three categories, and potentially order with three categories (assuming there are only three of them). Your dataset would look something like this:
subject read_time version order
1        1800        1      1
1        1500        1      1
1        1200        2      1
1        1400        2      1
1        1100        3      1
1        1000        3      1
2        1600        1      2
2        1550        1      2
2        1600        2      2
2        1350        2      2
2        1000        3      2
2        1100        3      2

And so on. If I understand your design, version changes within subjects (although all subjects are exposed to all versions) whereas order is a between-subjects factor that is constant within subject.
In terms of modeling this with a mixed model, that depends on your research questions, but the basic model I would set up would regress read_time on the fixed categorical predictors version and order with a random intercept for subject given that we expect responses from the same subject to be more highly correlated than responses from different subjects. In R, you can set up the model using lme4 as such:
library(lme4)
base <- lmer(read_time ~ version + order + (1|subject), data=df)

This fixed effect coefficients from this model will give test the read_time contrasts between the base category for version (presumably 1) against version 2 and version 3 and then provide a set of read_time contrasts between the base category of order (presumably 1) against order 2 and order 3.
You can get the ANOVA F test for this model if you want using anova(base). You may want to subsequently test whether version 2 is different from version 3 and likewise whether order 2 is different from order 3. You can use the multcomp package in R for this. See https://stats.idre.ucla.edu/r/faq/how-can-i-test-contrasts-in-r/


text:
Q: Where are minimized windows in naked Xvnc4? How to restore minimized windows? I am running VNC server as described here: No windows frames on VNC screen
I am running only few applications, so I have empty desktop and terminal in the beginning. If I run some application, like Eclipse, I am getting it's window normally. Unfortunately, when I minimize it, it goes somewhere down and no way to find it anymore.
Where are they? How to restore minimized windows in Xvnc4? May be I need to run some extra program for taskbar functionality?


text:
Q: Firebase and facebook login So here is my issue,
I am working on a service using firebase.
You login with your email and password.
You then can connect a page account by email user.
You do so by logging in through facebook, getting the page accounts through the fb.api and associating the page to the email.
My issue is as follow:
- In order to sign in, you need to disconnect from your personal one, then connect, disconnect and login again.
Is there anyway I can do all the operations I need to do without having to disconnect them from their account, using some type of sandbox or something?
Cheers,
Haytham


text:
Q: PHP checking if all inputs were set doesn't function? So I started using MVC.  I don't use a framework.  It's just self-practice.
So this is my register part:
    protected function _instance()
    {
        if ($_POST != null)
        {
            /**
            * Validating if forms are not empty
            **/

            if (self::validateForms())
            {
                echo 1;
            }
            else
            {
                new Error("One of the forums was empty..");
            }
        }
    }

    private static function validateForms()
    {
        $inputs = array (
            'username', 'password', 'repassword',
            'email', 'password_f', 'repassword_f',
            'display'
        );

        $i = 0;

        foreach ($inputs as $key)
        {
            if (isset($_POST[$key]) && !empty($_POST[$key]))
            {
                $i++;
                if ((int) $i == count($inputs))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }

Now it only must check if inputs were set, if not, throw error.
But it seems like it doesn't work as it always runs that error.
$i must grow everytime a input was full, but I don't think it does.
When I do echo $i, it only echoing "1".
Why is it only looping through it once?

A: The problem is you are returning within your loop after the first test.
    foreach ($inputs as $key)
    {
        if (isset($_POST[$key]) && !empty($_POST[$key]))
        {
            $i++;
            if ((int) $i == count($inputs))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

should be
    foreach ($inputs as $key)
    {
        if (isset($_POST[$key]) && !empty($_POST[$key]))
        {
            $i++;
        }
    }
    if ((int) $i == count($inputs))
    {
       return true;
    }
    else
    {
        return false;
    }

or more concisely
    foreach ($inputs as $key)
    {
        if (!isset($_POST[$key]) || empty($_POST[$key]))
        {
            return false;
        }
    }
    return true;

A: You need to take the checking of $i out of the loop so that it checks how many were actually set once all the inputs have been cycled through.  Otherwise, it is checking on the first time, seeing that it is not equal and returning false.
foreach ($inputs as $key)
{
    if (isset($_POST[$key]) && !empty($_POST[$key]))
    {
        $i++;
    }
}
if ((int) $i == count($inputs))
{
    return true;
}
else
{
    return false;
}


text:
Q: jquery datepicker not display on my django project I am trying to display a datepicker on my web little project with the help of django frame.
The case is that when I do the request to my page it displays everithing ok, but the datepicker calendar do not pop-up.
Could you help me? My code is:
My class:-----------------------------------------------------------------------------------
class clientcheckform(ModelForm):
class Meta:
    model = client
    fields = ('checkin',)
    widgets = {
        'checkin': forms.DateTimeInput(format='%d%m%Y',attrs={
            'class':'input',
            'readonly':'readonly',
            'size':'15',
        })
    }

My view.py --------------------------------------------------------------------------------
def index(request):
    client_check = clientcheckform()

template = loader.get_template('booking/index.html')
context = Context({
    'client_check': client_check,
     })
return HttpResponse(template.render(context))

To display I am using this template:---------------------------------------------------

Select CheckIn Day:

<link type="text/css" href="/media/css/jquery-ui-1.8.16.custom.css" rel="Stylesheet" />

{{client_check}}

I would greatly appreciate your help.
Thanks. Victor.

A: Mistake is on jquery function. Your date fields class is 'input', then jquery should be something like:
$(function() {
    $(".input").datepicker({ dateFormat: 'dd/mm/yy' });

A: If anyone else is following this trail, I had this same issue and resolved it.  Like the original poster, I was loading the JS in the
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/flick/jquery-ui.css" />

A: "jQuery is not defined" means jQuery.js is not loaded.
From looking at your code, it is probably one of the following two reasons:

*

*The incorrect HTML markup. Try to take away the  tag around


text:
Q: Getting a resource using another resource's id naming in REST API I am defining a REST API and am not sure about naming an endpoint.
I have the following method already
GET /users/{user_id}

This returns the following:
{
    "user_id": "some id",
    "username": "some username (1:1 with user_id)",
    ...
}

I want an endpoint to retrieve the resource by username, and I am not sure if it should be
GET /users/username/{username}

or rather
GET /usernames/{username}/user

or something else?

A: Usually a resource is uniquely identified by one single identifier. In your case that would be the user_id. So your GET /users/{user_id} RESTful route makes perfect sense if the user_id is what uniquely identifies a user in your system.
On the other hand if you want to be searching users by some other criteria (like a username) you could just use query string parameters:
GET /users?username=foo_bar

which will obviously return an array of users whose username matches this criteria and if in your case the username is unique this array will always contain at most one element:
[
    {
        "user_id": 123,
        "username": "foo_bar"
    }
]

On the other hand if you decide that user_id is some internal system identifier for the user resource in your system (for example that could be the primary key in your SQL database) and you want to expose some friendlier unique id in your RESTful facade to the users, then you might consider using GET /users/{username}. Of course in this case you should very well define what a username is and what are the allowed characters for it because things could quickly turn into a nightmare if you allow some special characters in a username. Here's a good read on this topic that I very strongly encourage you to go through and very well understand what are the allowed characters in the path segment of an URL.

A: I'd just add a query paramter
GET /users?username=john

A: Retrieving users by username does not really fit in the REST scheme, so I would either go with the already proposed solution /users?name=.... or [possibly more comprehensive] /users/<username>. I would use the latter only if the usernames do not need to be URI-encoded (in the best case - do not contain chars other than alpha-numeric and underscore)


text:
Q: Proving language is regular Let Σ be a finite alphabet and L ⊆ Σ
be a language. Let Σ0 ⊆ Σ. For each string
w = w1 · · · wn ∈ Σ
, define res(w, Σ
0
) = y1 · · · yn where yi = wi
if wi ∈ Σ
0
, and yi =  if
wi ∈ Σ \ Σ
0
, for each 1 ≤ i ≤ n. (For example res(abracadabra, {a, b}) = abaaaba.) Then
define res(L, Σ
0
) = {res(w, Σ
0
) : w ∈ L}
I have a very general direction and thought process for these problems, however, i am not completely sure i could construct a viable proof for the following problems. If anyone could point me in the right direction, that would be much appreciated.
(a) Show that if L ⊆ Σ*
?
is regular and Σ0 ⊆ Σ, res(L, Σ
0
) must be regular.
i know for this one, a DFA cannot be made for this language. So i will have to figure out a different way. A subset of any regular language is not necessarily regular.
(b) Show that if L ⊆ Σ*
is context-free and Σ0 ⊆ Σ, res(L, Σ
0
) must be context-free.
I know that for this problem, one way to solve it would be to provide a context free grammar
(c) Show that if L ⊆ Σ*
 and res(L, Σ
0
) is regular whenever Σ0 ⊂ Σ, L need not be regular.
For this question, we can say that even if L is not regular, that the empty language is a regular subset of this language. This would be true in all languages (whether it is regular or not)

A: I'm working on this question as well, here were my thoughts
for a:  if L is regular, it can be represented by a regular expression, so it should be possible to make a regular expression for L'.
for b: make a CFG where the terminals found in V and R of {V,E',R,S} just includes the terminals of E'
for c: assume that res(L, E') is regular, so as long as the alphabet is a true subset in that it can not equal the alphabet of L. L does not need to be regular.
These are just my initial thoughts, so take them with a grain of salt (maybe someone else can provide feedback)

A: While its evident that this is a homework assignment, a suggestion for part (a) is to look into closure properties for regular languages.
Take a look at L, the provided language in res(L, Σ'). Now take a look at the language (lets call it L') over the alphabet Σ'.
Now lets look at your example:
res(abracadabra, {a, b}) = abaaaba

In this scenario, L ∈ { abracadabra } and L' ∈ { abaaaba }
Between these two languages, L and L', what standard set operation can we use to create a set of only the elements each language has in common?
If you took a look at closure properties for regular languages, I'm sure you'll see the perfect fit!


text:
Q: Creating similar Activities I have a general question about the creation of multiple similar activities. Suppose we have an app in which you could order several different dishes (let's say we have 20 dishes). For every dish there is an activity for customizing (with regard to the size) and  ordering it. So basically all the activities are quite similar. My question now is, do I have to create a separate activity for all the 20 dishes or is there a more elegant way of doing this by only creating one activity and passing the individual values of the dishes to it?
I know that there are abstract classes in Java. But even if I use them I will still have to create an activity for every dish and a separate XML file for the layout, right?

A: You do not need to create a seperate activity for each dish! All you need is to do is use a getIntent() method to know where the the click is coming from and populate your view with the corresponding values.
Lets say you want to Order dish 1, on the button to order the dish, attach the intent to open the activity and attach the extras, do this for the other dishes. On the activity to display the dish info, obtain the extras and use them to populate the views for the XML. This means you can reuse an activity for many dishes.
Edit: Forgot to add code snippets. Assume that you are in the activity where you get to choose the dish.
In this case I am assuming the user wants tacos, I package the name of the dish in an extra and send to the DishInfo activity as seen below.
Intent intent = new Intent(this, DishInfo.class);
String dish = "Tacos";
intent.putExtra("DISH_NAME", dish);
startActivity(intent);

In the DishInfo activity, I get the intent that opened the activity by calling the getIntent() method and get the String with the getStringExtra() in this case because what I passed was a string. I set the text I got from the Intent to the textview.
TextView dishDisplayed = findViewById(R.id.TextView);
Intent intent = getIntent();
String dish = intent.getStringExtra("DISH_NAME");
dishDisplayed.setText(dish);

I made this example assuming that the important info you want to send to the new Activity is the simple name of the dish. I also assumed you would use the traditional findViewById() rather than bindings.
Intents are more powerful than this, you can read more about them here https://developer.android.com/guide/components/intents-filters


text:
Q: Are JavaScript error messages consistent across browsers and locale settings? Are JavaScript error messages the exact same across all browsers and will they always be reported in English (regardless of the client's locale settings)?
I have done minimal testing on Chrome, Safari, Firefox, and IE on desktop and mobile devices and the answer to my question appears to be "Yes". However, I would like to know if there is an official answer to my question that we can trust.


text: Q: Use AngularFire Auth Guard redirectUnauthorizedTo and then redirect to original URL I'm currently using redirectUnauthorizedTo(['login']) guard utility from @angular/fire/auth-guard, but now I want to redirect users to the original route they were trying to access after a successful login. It seems that it's not possible to access the original route from the Router module inside the LoginComponent, so I wanted to know if it's possible to use this same Guard to include the original route in the router object that arrives at my LoginComponent.


text:
Q: Issue Reading from a file and using a 2D array to sort the data I'm making a province sorter, and the requirement is that I must leave the main class as is, and make a private class called Munge, i've been at this for hours and changed my code hundreds of times, basically it reads from a text file that looks like this

Hamilton, Ontario
  Toronto, Ontario
  Edmonton, Alberta
  Red Deer, Alberta
  St John's, Newfoundland

and needs to be output like this

Alberta; Edmonton, Red Deer
  Ontario; Hamilton, Toronto
  Newfoundland; St John's

my main class is unchangeable and looks like this
public class Lab5 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    if(args.length < 2) {
        System.err.println("Usage: java -jar lab5.jar infile outfile");
        System.exit(99);
    }

    Munge dataSorter = new Munge(args[0], args[1]);

    dataSorter.openFiles();
    dataSorter.readRecords();
    dataSorter.writeRecords();
    dataSorter.closeFiles();
    }
}

and the Munge class i've made looks like this
package lab5;

import java.io.File;
import java.util.Scanner;
import java.util.Formatter;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

public class Munge
{

private String inFileName, outFileName;
private Scanner inFile;
private Formatter outFile;
private int line = 0;

private String[] data;

public Munge(String inFileName, String outFileName)
{
    this.inFileName = inFileName;
    this.outFileName = outFileName;

    data = new String[100];
}

public void openFiles()
{
    try
    {
        inFile = new Scanner(new File(inFileName));
            File file = new File("input.txt");
            SortedMap<String, List<String>> map = new TreeMap<String, List<String>>();
            Scanner scanner = new Scanner(file).useDelimiter("\\n");
        while (scanner.hasNext()) {
            String newline = scanner.next();
            if (newline.contains(",")) {
            String[] parts = newline.split(",");
            String city = parts[0].trim();
            String province = parts[1].trim();
            List<String> cities = map.get(province);
            if (cities == null) {
                cities = new ArrayList<String>();
                map.put(province, cities);
            }
            if (!cities.contains(city)) {
                cities.add(city);
            }
            }
        }
            for (String province : map.keySet()) {
                StringBuilder sb = new StringBuilder();
                sb.append(province).append(": ");
                List<String> cities = map.get(province);
                for (String city : cities) {
                    sb.append(city).append(", ");
                }
                sb.delete(sb.length() - 2, sb.length());
                String output = sb.toString();
                System.out.println(output);
            }
    }
    catch(FileNotFoundException exception)
    {
        System.err.println("File not found.");
        System.exit(1);
    }
    catch(SecurityException exception)
    {
        System.err.println("You do not have access to this file.");
        System.exit(1);
    }

    try
    {
        outFile = new Formatter(outFileName);
    }
    catch(FileNotFoundException exception)
    {
        System.err.println("File not found.");
        System.exit(1);
    }
    catch(SecurityException exception)
    {
        System.err.println("You do not have access to this file.");
        System.exit(1);
    }
}

public void readRecords()
{
    while(inFile.hasNext())
    {
        data[line] = inFile.nextLine();
        System.out.println(data[line]);
        line++;
    }
}

public void writeRecords()
{
    for(int i = 0; i < line; i++)
    {
        String tokens[] = data[i].split(", ");
        Arrays.sort(tokens);

        for(int j = 0; j < tokens.length; j++)
            outFile.format("%s\r\n", tokens[j]);
    }
}

public void closeFiles()
{
    if(inFile != null)
        inFile.close();

    if(outFile != null)
        outFile.close();
}
}

you'll have to excuse my brackets, there formatted correctly in netbeans but i had to move the bottom ones over to keep it in the codeblock

A: As I think this is homework I'll avoid giving you a solution but give some hints of what to do.
When you have read a line it consists of City, Province. So the first thing you need to do is split the string into two parts. The second part is the province and the first is the city. You need to make a collection for each province and store the city in the correct province collection.
Once you have that you sort the names of the found provinces, and iterate through them. Sort the cities for the province and then output the province name and each city name.
Useful classes could be will be HashMap, TreeMap, List, Collections (has sort methods).
Hope that helps to get you further, otherwise try to be more specific where you are stuck.


text:
Q: Caffe - multi-class and multi-label image classification I'm trying to create a single multi-class and multi-label net configuration in caffe.
Let's say classification of dogs:
Is the dog small or large? (class)
What color is it? (class)
is it have a collar? (label)
Is this thing possible using caffe?
What is the proper way to do so?
What is the right way to build the lmdb file?
All the publications about multi-label classification are from around 2015, something in this subject changed since then?
Thanks.

A: The problem with Caffe's LMDB interface is that it only allows for a single int label per image.
If you want multiple labels per image you'll have to use a different input layer.
I suggest using "HDF5Data" layer:
This allows for more flexibility setting the input data, you may have as many "top"s as you want for this layer. You may have multiple labels per input image and have multiple losses for your net to train on.
See this post on how to create hdf5 data for caffe.

A: Thanks Shai,
Just trying to understand the practical way..
After creating 2 .text files (one for training and one for validation) containing all the tags of the images, for example:
/train/img/1.png 0 4 18
/train/img/2.png 1 7 17 33
/train/img/3.png 0 4 17

Running the py script:
import h5py, os
import caffe
import numpy as np

SIZE = 227 # fixed size to all images
with open( 'train.txt', 'r' ) as T :
    lines = T.readlines()
# If you do not have enough memory split data into
# multiple batches and generate multiple separate h5 files
X = np.zeros( (len(lines), 3, SIZE, SIZE), dtype='f4' )
y = np.zeros( (len(lines),1), dtype='f4' )
for i,l in enumerate(lines):
    sp = l.split(' ')
    img = caffe.io.load_image( sp[0] )
    img = caffe.io.resize( img, (SIZE, SIZE, 3) ) # resize to fixed size
    # you may apply other input transformations here...
    # Note that the transformation should take img from size-by-size-by-3 and transpose it to 3-by-size-by-size
    # for example
    transposed_img = img.transpose((2,0,1))[::-1,:,:] # RGB->BGR
    X[i] = transposed_img
    y[i] = float(sp[1])
with h5py.File('train.h5','w') as H:
    H.create_dataset( 'X', data=X ) # note the name X given to the dataset!
    H.create_dataset( 'y', data=y ) # note the name y given to the dataset!
with open('train_h5_list.txt','w') as L:
    L.write( 'train.h5' ) # list all h5 files you are going to use

And creating train.h5 and val.h5 (is X data set containing the images and Y contain the labels?).
Replace my network input layers from:
layers {
 name: "data"
 type: DATA
 top:  "data"
 top:  "label"
 data_param {
   source: "/home/gal/digits/digits/jobs/20181010-191058-21ab/train_db"
   backend: LMDB
   batch_size: 64
 }
 transform_param {
    crop_size: 227
    mean_file: "/home/gal/digits/digits/jobs/20181010-191058-21ab/mean.binaryproto"
    mirror: true
  }
  include: { phase: TRAIN }
}
layers {
 name: "data"
 type: DATA
 top:  "data"
 top:  "label"
 data_param {
   source: "/home/gal/digits/digits/jobs/20181010-191058-21ab/val_db"
   backend: LMDB
   batch_size: 64
 }
 transform_param {
    crop_size: 227
    mean_file: "/home/gal/digits/digits/jobs/20181010-191058-21ab/mean.binaryproto"
    mirror: true
  }
  include: { phase: TEST }
}

to
layer {
  type: "HDF5Data"
  top: "X" # same name as given in create_dataset!
  top: "y"
  hdf5_data_param {
    source: "train_h5_list.txt" # do not give the h5 files directly, but the list.
    batch_size: 32
  }
  include { phase:TRAIN }
}

layer {
  type: "HDF5Data"
  top: "X" # same name as given in create_dataset!
  top: "y"
  hdf5_data_param {
    source: "val_h5_list.txt" # do not give the h5 files directly, but the list.
    batch_size: 32
  }
  include { phase:TEST }
}

I guess HDF5 doesn't need a mean.binaryproto?
Next, how the output layer should change in order to output multiple label probabilities?
I guess I need cross- entropy layer instead of softmax?
This is the current output layers:
layers {
  bottom: "prob"
  bottom: "label"
  top: "loss"
  name: "loss"
  type: SOFTMAX_LOSS
  loss_weight: 1
}
layers {
  name: "accuracy"
  type: ACCURACY
  bottom: "prob"
  bottom: "label"
  top: "accuracy"
  include: { phase: TEST }
}


text:
Q: Windows - Use default python rather than Anaconda installation my problem is before I installed Anaconda, my python with python and py commands shows the same versions. After I installed Anaconda, my python version is using Anaconda installation. How to prevent this, because I don't want to use Anaconda python version on my Windows.

*

*I already put my python PATH on the top

*When I check the PATH, there's no anaconda PATH anywhere when I done my installation

My python version will use the default python version, not the Anaconda's version

A: You need to change the default opener for the .py files on your computer.
try to right-click on the .py file, select "open with" and look for python.
You can always use cmd and run the following:
python <path_to_file>

or
python3 <path_to_file>

It depended on your python version
(as long as you set your python path in windows Path)


text:
Q: Loop between dates I created below macro to generate few datasets based on date macro.
%macro pull(date);

proc sql;

create table new&date as

select * from acct

where date=&date.;

quit;

%mend;

So if i want to create dataset for 20170101 20170201 20170301 20170401 20170501, all i can do is use below macro
%macro pull(20170101)

%macro pull(20170201)

%macro pull(20170301)

%macro pull(20170401)

%macro pull(20170501)

What i am planning now is create two macro variables
%let begin=20170101;

%let end =20170501;

and create datasets based on begin and end using loop. Is it possible to do that.So what i am trying to do is give start and end date as macro variable and pull records between begin and end date from acct dataset and create separate datasets for each month between start and end dates
Note dataset have monthly dates for each year.
Below is the code i am trying
%let beg="01jan2000"d;
%let end="01jan2001"d;
%macro Test;
%do date=&beg. %to &end.;
proc sql;
create table IPw_&date. as
select *
from sample
where date=&date. quit;
%end;
%mend;
%Test;

A: When date information must be inferred from values that are not SAS date values you will need to input the information to get a date value, and put the values iterated over to get the desired non date representation.
This example demonstrates

*

*INPUTN function to parse the YYYYMMDD arguments into date values using informat YYMMDD8.

*INTNX function to compute 1st of the month of the date values

*PUTN function to convert a date value to a YYYYMMDD representation using format YYMMDDN8.

*%DO %WHILE statement for iterating

*INTNX function to advance the iteration variable to the start of the next month

Code
%macro pull(yyyymmdd);
  %local out;

  %let out = pull_&yyyymmdd;

  data &out;
    pull_date = input ("&yyyymmdd", yymmdd8.);
    format pull_date yymmdd10.;
  run;
%mend;

%macro pull_each_month(begin=, end=);
  %local
    begin_date end_date
    begin_month end_month
    pull_date pull_ymd
  ;

  %put NOTE: &=begin &=end;

  %let begin_date = %sysfunc(inputn(&begin,yymmdd8.));
  %let end_date   = %sysfunc(inputn(&end,yymmdd8.));

  %put NOTE: &=begin_date &=end_date;

  %let begin_month = %sysfunc(intnx(month,&begin_date,0));
  %let end_month   = %sysfunc(intnx(month,&end_date,0));

  %put NOTE: &=begin_month &=end_month;

  %let pull_month = &begin_month;
  %do %while (&pull_month <= &end_month);
    %let pull_ymd = %sysfunc(putn(&pull_month,yymmddn8.));
    %put NOTE: Invoking pull for &=pull_month &=pull_ymd;

    %pull (&pull_ymd)

    %let pull_month = %sysfunc(INTNX(MONTH,&pull_month,1));

  %end;
%mend;

%pull_each_month (
  begin = 20170101
, end   = 20170501
)

%macro pull_each_month(begin=, end=);
  %local
    begin_date end_date
    begin_month end_month
    pull_date pull_ymd
  ;

  %put NOTE: &=begin &=end;

  %let begin_date = %sysfunc(inputn(&begin,yymmdd8.));
  %let end_date   = %sysfunc(inputn(&end,yymmdd8.));

  %put NOTE: &=begin_date &=end_date;

  %let begin_month = %sysfunc(intnx(month,&begin_date,0));
  %let end_month   = %sysfunc(intnx(month,&end_date,0));

  %put NOTE: &=begin_month &=end_month;

  %let pull_month = &begin_month;
  %do %while (&pull_month <= &end_month);
    %let pull_ymd = %sysfunc(putn(&pull_month,yymmddn8.));
    %put NOTE: Invoking pull for &=pull_month &=pull_ymd;
    %let pull_month = %sysfunc(INTNX(MONTH,&pull_month,1));
  %end;

%mend;

%pull_each_month (
  begin = 20170101
, end   = 20170501
)

A: %macro pull(begin,end);
%let i=0;
%let begin=%sysfunc(inputn(&begin,anydtdte9.));
%let end=%sysfunc(inputn(&end,anydtdte9.));
%do %until (&begin=&end);
    %let begin=%sysfunc(intnx(month,&begin,&i));
    %let date=%sysfunc(putn(&begin,yymmddn8.));
    proc sql;
    create table new&date as
    select * from acct where date=&date.;
    quit;
    %let i=%eval(&i+1);
%end;
%mend;

%pull(20170101,20170501)


text:
Q: Cardinality calculation How to simplify the following:
$$2^{\aleph_0}(\aleph_0+\aleph_0)^{2^{\aleph_0}}$$
Thank you for every help.

A: Use that
(i) For cardinals $\kappa$ and $\lambda$ with $\kappa \le \lambda$ and $\lambda$ infinite you have that $\kappa + \lambda = \lambda$ and hence $\aleph_0 + \aleph_0 = \aleph_0$
(ii) For cardinals $\kappa \le \lambda$ where $\lambda$ is infinite you have $\kappa \cdot \lambda = \lambda$
(iii) For an infinite cardinal $\lambda$ and $2 \le \kappa \le \lambda$ you have $\kappa^\lambda = 2^\lambda$
Then
$$2^{\aleph_0}(\aleph_0+\aleph_0)^{2^{\aleph_0}} \stackrel{(i)}{=} 2^{\aleph_0}\aleph_0^{2^{\aleph_0}} \stackrel{(ii)}{=} \aleph_0^{2^{\aleph_0}} \stackrel{(iii)}{=} 2^{2^{\aleph_0}}$$

A: Hint: Prove that $(\aleph_0)^{2^{\aleph_0}}=2^{2^{\aleph_0}}$.