text:
Q: php artisan migrate failed I have reinstall my ubuntu 1.04.3. First of all I installed php: 7.2.19, nodejs: 12.10.0, apache and mysql. After that I installed gloabally the composer and some php extentions that said that were needed to install Laravel and finished with the installation of laravel. I created a project with the command Laravel new ... When I try to do "php artisan migrate" I take this error and I dont know what to do.
Error:
*

Illuminate\Database\QueryException  : could not find driver (SQL:
  PRAGMA foreign_keys = ON;)
at
  /home/dbalaskas/Desktop/Laravel/myProject/vendor/laravel/framework/src/Illuminate/Database/Connection.php:665

    661|         // If an exception occurs when attempting to run a query, we'll format the error
    662|         // message to include the bindings with SQL, which will make this exception a
    663|         // lot more helpful to the developer instead of just the database's errors.
    664|         catch (Exception $e) {
  > 665|             throw new QueryException(
    666|                 $query, $this->prepareBindings($bindings), $e
    667|             );
    668|         }
    669|

Exception trace:

1   PDOException::("could not find driver")
        /home/dbalaskas/Desktop/Laravel/myProject/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
2
  PDO::__construct("sqlite:/home/dbalaskas/Desktop/Laravel/myProject/database/database.sqlite",
  [])
        /home/dbalaskas/Desktop/Laravel/myProject/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
Please use the argument -v to see more details.
  *

.env file:
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:aG05wMCXTkKQeBdTAZBGzjvyfY8gyhPmZs4qoKIiYU4=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

config/database.php:
<?php

use Illuminate\Support\Str;

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'url' => env('DATABASE_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        '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'),
            ]) : [],
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer body of commands than a typical key-value system
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],

        'cache' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_CACHE_DB', 1),
        ],

    ],

];

A: The following can be used to install the missing php extension.
apt install php-mysql

A: I was having same issue !!!
I was using sqlite (DB_CONNECTION=sqlite) in my project and came across this error while integrating that.
Run command this command to check what dependencies are installed on your php server
php -m

This will list all the dependencies that are installed. Check that pdo_mysql, pdo_sqlite and sqlite3 are installed or not. If not install those.
Make sure your have enable pdo extensions in ubuntu.
In my case, sqlite was not install for my php 7.2. So if thats the same with you run this command:
sudo apt-get install php7.2-sqlite

Just to make sure it works restart apache server too by running this command:
sudo service apache2 start

Then run migrate command in your laravel project:
php artisan migrate

Hope it helps....

A: your database seems to be using sqlite
sqlite:/home/dbalaskas/Desktop/Laravel/myProject/database/database.sqlite",

try changing the .env property DB_CONNECTION=mysql to DB_CONNECTION=sqlite


text:
Q: Form data not binding with Spring Controller Annotation getting new object after submit I am not getting form data in spring controller after submitting the form below is my code
@RequestMapping(value = "category/addCategory.htm" , method = RequestMethod.GET)
public String add(Model model) {
    if (log.isDebugEnabled()){
        log.debug("Invoking listCategory");
    }
    model.addAttribute("categoryView", new CategoryView());
    return "editCategory";
}

@RequestMapping(value = "category/saveCategory.htm", method = RequestMethod.POST)
public String saveCategory(CategoryView categoryView, Model model,  BindingResult result) {

    Category category = prepareCategoryFromView(categoryView);

    categoryService.save(category);
    categoryView.setCategoryId(category.getCategoryId());
    model.addAttribute("categoryView",categoryView);
    return "editCategory";
}

prepareCategoryFromView is a method which is setting the actual values on Category it's hibernate entity, below categoryView
public class CategoryView {
private long categoryId;
private String image = "";
private int parentId;
private boolean top;
private int column = 1;
private int sortOrder = 1;
private boolean status;
private String description;
private String name;
.
.
other variable and setter and getters
}

and the form is
<sf:form  method="post" enctype="multipart/form-data" id="form-category" cssClass="form-horizontal" modelAttribute="categoryView">
<sf:label path="name" cssClass="col-sm-2 control-label">Category Name</sf:label>
<sf:input path="name" id="name" name="name" cssClass="form-control" placeholder="Category Name" />
<sf:hidden path="categoryId" id="categoryId" name="categoryId" />
<sf:hidden path="languageId" id="languageId" name="languageId" />
<sf:label path="description" cssClass="col-sm-2 control-label">Category Name</sf:label>
<sf:textarea path="description" cssClass="form-control" placeholder="Description" id="description"/>
.
.
.
</sf:form>

In above form every time I am getting name and description is null (I think it's creating a new view object without given values in form)
Pls let me know, where I am wrong

A: Remove the enctype="multipart/form-data" from your form tag and try again (with the method arguments in the correct order). @ModelAttribute is not strictly required since your attribute name matches the class name.

A: I think @ModelAttribute annotation is missing here on CategoryView object.Because as per your form code it is the model attribute which will bind data to the bean in controller.
Attach it with your method argument like below,then you can check the data is binding to it or not.
@RequestMapping(value = "category/saveCategory.htm", method = RequestMethod.POST)
public String saveCategory(@ModelAttribute("categoryView") CategoryView categoryView, Model model,  BindingResult result) {

    Category category = prepareCategoryFromView(categoryView);

    categoryService.save(category);
    categoryView.setCategoryId(category.getCategoryId());
    model.addAttribute("categoryView",categoryView);
    return "editCategory";
}

redpajama_set_name: RedPajamaStackExchange


text: Q: Samsung Phone Keeps asking to Allow MTP every time i connect via USB I have noticed a very annoying bug. I have noticed it on many Ubuntu versions, and also on all my Samsung Sevices. (Galaxy S4, S5, and S7). Every time i connect the phone to USB, i get a popup on the phone that asks me to "Allow access to device data" and i have to click Allow. On Windows machines, this popup appears only once, and then Windows memorizes the option for that device. You dont need to "allow" if you plug the phone back to the PC. On Ubuntu, it asks me to Allow every single time. So annoying.


text:
Q: XSLT How to append one child element if another child element is repeating I have an XML where there are two child elements, I want to append second child elements if the first one is repeating.
Below is the request XML
<SelectedOffer>
<SelectedOfferItem>
    <OfferItemRefID>SP2F-58379439-103-1_ADT</OfferItemRefID>
    <PaxRefID>PAX1</PaxRefID>
</SelectedOfferItem>
<SelectedOfferItem>
    <OfferItemRefID>SP2F-58379439-103-1_ADT</OfferItemRefID>
    <PaxRefID>PAX2</PaxRefID>
</SelectedOfferItem>
<SelectedOfferItem>
    <OfferItemRefID>SP2F-58379439-103-1_CHD</OfferItemRefID>
    <PaxRefID>PAX3 </PaxRefID>
</SelectedOfferItem>
<SelectedOfferItem>
    <OfferItemRefID>SP2F-58379439-103-1_CHD</OfferItemRefID>
    <PaxRefID>PAX4</PaxRefID>
</SelectedOfferItem>
<SelectedOfferItem>
    <OfferItemRefID>SP2F-58379439-103-1_INF</OfferItemRefID>
    <PaxRefID>PAX5</PaxRefID>
</SelectedOfferItem>

Expected result would be like
<OfferItems>
<OfferItem OfferItemID="SP2F-58379439-103-1_ADT">
    <PassengerRefs>PAX1 PAX2</PassengerRefs>
</OfferItem>
<OfferItem OfferItemID="SP2F-58379439-103-1_CHD">
    <PassengerRefs>PAX3 PAX4</PassengerRefs>
</OfferItem>
<OfferItem OfferItemID="SP2F-58379439-103-1_INF">
    <PassengerRefs>PAX5</PassengerRefs>
</OfferItem>

A: In XSLT 2.0 it's as simple as
<xsl:for-each-group select="SelectedOfferItem" group-adjacent="OfferItemRefID">
  <OfferItem OfferItemId="{current-grouping-key()}">
    <PassengerRefs>
      <xsl:value-of select="current-group()/PaxRefID"/>
    </PassengerRefs>
  </OfferItem>
</xsl:for-each-group>


text:
Q: Remove "message" field for metricbeat set data I am trying to get metricbeat data using logstash.
(Kafka as input & ElasticSearch as Output).
input {
  kafka {
    bootstrap_servers => "XX.XX.XXX.XX:9092"
    topics => ["cc-data"]
  }
}
output {
  elasticsearch {
    hosts => ["XX.XX.XXX.XX:9200"]
    index => "metricbeat-%{+YYYY.MM.dd}"
  }
}

In the output I see the data as :
     {
        "_index" : "metricbeat-2017.01.18",
        "_type" : "logs",
        "_id" : "AVmzQUytyldhSr4kUaUS",
        "_score" : 1.0,
        "_source" : {
          "@timestamp" : "2017-01-18T20:21:45.324Z",
          "@version" : "1",
          "message" : "{\"@timestamp\":\"2017-01-18T20:21:44.394Z\",\"beat\":{\"hostname\":\"ip-XX-XXX-XX-XXX\",\"name\":\"ip-XX-XXX-XX-XXX\",\"version\":\"5.0.0\"},\"metricset\":{\"module\":\"system\",\"name\":\"process\",\"rtt\":104061},\"system\":{\"process\":{\"cpu\":{\"start_time\":\"2016-08-03T10:10:17.000Z\",\"total\":{\"pct\":0.000000}},\"fd\":{\"limit\":{\"hard\":4096,\"soft\":1024},\"open\":0},\"memory\":{\"rss\":{\"bytes\":0,\"pct\":0.000000},\"share\":0,\"size\":0},\"name\":\"migration/2\",\"pgid\":0,\"pid\":47,\"ppid\":2,\"state\":\"sleeping\",\"username\":\"root\"}},\"type\":\"metricsets\"}"
        }
      }
    ]
  }
}

I do not want "message" FIELD alone.. Instead, all the datas in that field should appear as it is [want to remove the "message" field name alone - but the content of that should appear] How do I delete the field name alone, and keep the content as it is.
Can anyone help how do we achieve this?

A: The kafka input has a plain codec by default, which means that it consumers the topic and interpret the content as a plain string. What you need instead is to change the codec to json to it parses the content to a JSON structure:
input {
  kafka {
    bootstrap_servers => "XX.XX.XXX.XX:9092"
    topics => ["cc-data"]
    codec => "json"           # <---- add this
  }
}


text:
Q: Method doInBackground does not override from the superclass I am trying to use AsyncTask but both my doInBackground and onPostExecute methods give me the same error saying Method does not override method from its superclass. My code is:
public class SigninActivity extends AsyncTask{

    private TextView status, result;
    private Context context;
    private int flag = 0;

    public SigninActivity(Context context, TextView status, TextView result, int flag) {
        this.context = context;
        this.statusField = status;
        this.roleField = result;
        this.flag = flag;
    }

    protected void onPreExecute() {
    }

    @Override
    protected String doInBackground(String... arg0) {
        //Code
    }

    @Override
    protected void onPostExecute(String result) {
        //Code
    }

A: You should create AsyncTask with three parameters < X,Y,Z >. For more details in here
    private class MyAsyncTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        // your code
    }

    @Override
    protected void onPostExecute(String result) {
       //your code
    }

    @Override
    protected void onPreExecute() {
      //your code
    }

    @Override
    protected void onProgressUpdate(String... text) {
        // your code

    }
}


text:
Q: Rudin's PMA theorems 7.11 and 7.12 Theorem 7.11: Suppose $f_n \to f$ uniformly on a set $E$ in a metric space. Let $x$ be a limit point of $E$, and suppose that $$\lim_{t\to x} f_n(t) = A_n \qquad (n \in N).$$ Then $\{A_n\}$ converges, and $$\lim_{t\to x} f(t) = \lim_{n\to \infty} A_n.$$
In other words, the conclusion is that
$$\lim_{n\to\infty}\lim_{t\to x}f_n(t)=\lim_{t\to x}\lim_{n\to \infty}f_n(t)$$
Theorem 7.12: If $(f_n)$ is a sequence of continuous functions on $E$ and if $f_n \to f$ uniformly, then $f$ is continuous on $E$.
I guess I'm having an issue understanding what theorem 7.11 is actually saying in English? Does the conclusion mean that the limit function of $(f_n)$ is continuous at any limit point of $E$? Why is it that continuity for a limit function looks like
$$\lim_{n\to\infty}\lim_{t\to x}f_n(t)=\lim_{t\to x}\lim_{n\to \infty}f_n(t)$$
and not something more like
$$
\lim_{t \rightarrow x} f(t) = f(x).
$$
Why does it follow naturally from 7.11 that 7.12 holds? I feel like I'm missing a simple understanding of what theorem 7.11 is actually saying, although I feel like I understand the proof (which is probably wrong to say because I don't understand the conclusion). Any insights are greatly appreciated.

A: Since you requested an explanation in plain English, the first theorem says that when convergence is uniform, the order in which you take the limits of the function $f_n$ does not matter. The ability to interchange limit operations in this way is one of the reasons why uniform as opposed to mere pointwise convergence of a sequence of functions is viewed as advantageous. The second theorem is just a special case of the first insofar as 7.11 says nothing about the functions being continuous. The most important piece of information that is being communicated in what you have written is that "the uniform limit of a sequence of continuous functions is continuous." This is a fundamental result that is routinely invoked in proofs in analysis, and so it is a good idea to not only memorize it, but to also develop a clear understanding of the intuition that underlies it.


text:
Q: How can I get the adjusted values with respect to a specific effect in a linear mixed effects model? I'm using R and lme4 to estimate the parameters of a model
model = lmer(response ~ fixed_effect + nuisance_effect + (1 | random_effect), data = data, REML = FALSE)

where fixed_effect is the categorical factor of interest, nuisance_effect is a numerical factor, and random_effect is a categorical factor.
I want to visualize the data while accounting only for the nuisance_effect, so I want to get the residuals with respect to that effect only. Using residuals(model) gives me the residuals for the entire model.
So, my question is twofold:

*

*Is this the right approach to visualization here?

*How can I pull out the residuals in this way?


text:
Q: Cloud Functions for Firebase - failing to deploy Enjoying life and coding a bit, after 30 minutes I decide to deploy my functions to see what I have done.
Sadly, this time , my functions did not deploy.
This has not happened before... I am scratching my head
I jump on my command line in windows 7 and look for the version of the firebase tools ... it is saying version 3.7.0. ... dammm... this ain't gonna be easy.
Then I jump at https://console.cloud.google.com/logs/viewer ... 2 red exclamation points..
I look at the error logs and it is saying
 protoPayload: {
  @type: "type.googleapis.com/google.cloud.audit.AuditLog"
  status: {
   code: 10
   message: "Operation interrupted."

This is my command line output:
i  deploying functions

i  functions: ensuring necessary APIs are enabled...
i  runtimeconfig: ensuring necessary APIs are enabled...
+  runtimeconfig: all necessary APIs are enabled
+  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (2.8 KB) for uploading
+  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
i  functions: creating function date_test...
i  functions: creating function testvunglecallback...
!  functions[date_test]: Deploy Error: Operation interrupted.
!  functions[testvunglecallback]: Deploy Error: Operation interrupted.

Functions deploy had errors. To continue deploying other features (such as datab
ase), run:
    firebase deploy --except functions

Error: Functions did not deploy properly.

Please try to help...
Thank you.


text:
Q: Searching for a word and not a string? I want to check a file for a particular word the way I have found posted on various forums is to use the following code...
Dim content = My.Computer.FileSystem.ReadAllText(filePath)
If content.Contains("stringToSearch") Then
    'Do your stuff
End If

Which is okay until you discover that it will search and match compound words and the likes. For instance If I search for the string light in a file and it's not there but instead the word lightning is, it will still register as having found a match... Is there a way to find and exact word using VB.net?

A: As mentioned by Andrew Morton, Regex makes this kind of thing very easy.  For instance, if you made a function like this:
Public Function ContainsWord(input As String, word As String) As Boolean
    Return Regex.IsMatch(input, $"\b{word}\b")
End Function

You could use it like this:
Dim content = My.Computer.FileSystem.ReadAllText(filePath)
If ContainsWord(content, "stringToSearch") Then
    'Do your stuff
End If

If you wanted to, you could even make it an extension method on the String type, by putting it in a Module and adding the ExtensionAttribute, like this:
<Extension>
Private Function ContainsWord(input As String, word As String) As Boolean
    Return Regex.IsMatch(input, $"\b{word}\b")
End Function

And then you could call it like this:
Dim content = My.Computer.FileSystem.ReadAllText(filePath)
If content.ContainsWord("stringToSearch") Then
    'Do your stuff
End If

A: Another method, using Regex.Matches, which allows to search for a collection of words and returns a Dictionary(Of String, Integer()).
The Dictionary Key represent the matched word, the Value, as an Array of Integers, all the positions inside the File where the word was found.
The extension method requires 2 parameters:
- the path of the file to search
- a boolean value, used to specify whether the search should be case sensitive.
Proposed as an extension method of IEnumerable(Of String):
Dim fileName As String = "[File Path]"
Dim searchWords As String() = {"light", "lighting", "clip", "clipper", "somethingelse"}
Dim result = searchWords.FindWords(fileName, False)

Print a result of the matches found:
result.ToList().ForEach(
    Sub(w)
        Console.WriteLine($"Word: {w.Key} Positions: {String.Join(", ", w.Value)}")
    End Sub)

Extension method:
Imports System.IO
Imports System.Runtime.CompilerServices
Imports System.Text
Imports System.Text.RegularExpressions

Module modIEnumerableExtensions

    <Extension()>
    Public Function FindWords(words As IEnumerable(Of String),
                              fileName As String,
                              caseSentive As Boolean) As Dictionary(Of String, Integer())
        Dim pattern As StringBuilder = New StringBuilder()
        pattern.Append(String.Concat(words.Select(Function(w) $"\b{w}\b|")))

        Dim options As RegexOptions = RegexOptions.Compiled Or
            If(caseSentive, RegexOptions.Multiline, RegexOptions.IgnoreCase Or RegexOptions.Multiline)

        Dim regx As New Regex(pattern.ToString().TrimEnd("|"c), options)
        Dim matches As MatchCollection = regx.Matches(File.ReadAllText(fileName))

        Dim groups = matches.OfType(Of Match).
            GroupBy(Function(g) g.Value).
            ToDictionary(Function(g) g.Key, Function(g) g.Select(Function(m) m.Index).ToArray())
        Return groups
    End Function
End Module

A: The shortest and fastest way to do this is using ReadLines with LINQ queries, specialy when you are working with a large files.
Dim myword As String = "Book"
Dim reg = New Regex("\b" & myword & "\b", RegexOptions.IgnoreCase)
Dim res = From line In File.ReadLines(largeFileName)
                  Where reg.IsMatch(line)

If your file containts "Book", "Books", "Book." and "Book," the results will be:
Book
Book,
Book.

And you can working with results as following
TextBox1.Text = resLines.Count

Or
TextBox1.Text = resLines(0)

Edited to make it consering "." and "," etc.


text:
Q: Custom error format for fluent validation error I followed Fluent documentation and I haven't found any option to overwrite default error format that is something like "'{propertyName}' must be something.". I have many validators and I won't rewrite them to .WithMessage("...").
Is there any option to change default message format?
I would like to have a similar interface to PropertyNameResolver that offers smart interface to change property name.

A: You can overwrite the messages globally by modifying the ValidatorOptions.ResourceProviderType as noted on the localization page.
You only have to define the strings that you would like to change as it will use the default string if no override is specified.


text:
Q: FragmentPagerAdapter always starts from the first page I have a Fragment pager adapter with five fragments and inside the third fragment I want to call an other activity which sends a selected picture to the container. It works fine but, every time the picture is selected from the other activity and the pager adapter starts from the first fragment in the fragment-activity instead of third fragment-activity. Do I have to force the pager adapter from the other activity or should I change something in the fragment-activity?
Code:
Fragment-activity:
package com.example.android.womb_the_game;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;

public class Circulation extends FragmentActivity {

    ViewPager vp;
    public static FragmentPagerAdapter adapterViewPager;

    @Override
    protected void onCreate(Bundle onSavedInstanceState) {
        super.onCreate(onSavedInstanceState);

        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_circulation);

        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        vp = findViewById(R.id.view_pager);
        adapterViewPager=new Adapter_Circulation(getSupportFragmentManager(), this);
        vp.setAdapter(adapterViewPager);

     TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(vp);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }

}

FragmentPagerAdapter:
package com.example.android.womb_the_game;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import android.content.Context;

public class Adapter_Circulation extends FragmentPagerAdapter {
    private static int NUM_ITEMS = 5;
    Context context;

    public Adapter_Circulation(FragmentManager fm, Context c) {
        super(fm);
        this.context = c;

    }

    @Override
    public Fragment getItem(int position) {
        switch (position)
        {
            case 0:
                return Frg0.newInstance ();
            case 1:
                return Frg1.newInstance();
            case 2:
                return Frg2.newInstance();
            case 3:
                return Frg3.newInstance();
            case 4:
                return Frg4.newInstance();
        }
        return null; //does not happen
    }

    @Override
    public int getCount() {
        return NUM_ITEMS; //three fragments
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "RULES";
            case 1:
                return "EVENTS";
            case 2:
                return "PLAN";
            case 3:
                return "SHOOT";
            case 4:
                return "JUMP";
        }
        return null;
    }
}

Fragment3:
package com.example.android.womb_the_game;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

public class Frg3 extends Fragment{

    private ImageButton shoot;
    private ImageButton snipe;
    private ImageButton aim;

    public static Frg3 newInstance() {

        Bundle args = new Bundle();

        Frg3 fragment = new Frg3();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View rootView = inflater.inflate(R.layout.fragment_frg3, container, false);
        shoot = (ImageButton) rootView.findViewById(R.id.shoot);
        snipe = (ImageButton) rootView.findViewById(R.id.snipe);
        aim = (ImageButton) rootView.findViewById(R.id.aim);

        final View.OnClickListener mListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.shoot:
                        FragmentManager FM0 = getFragmentManager();
                        FragmentTransaction FT0 = FM0.beginTransaction();
                        frg_shoot F10 = new frg_shoot();
                        FT0.add(R.id.fragment_container1, F10);
                        FT0.replace(R.id.fragment_container1, F10);
                        FT0.commit();
                        break;
                    case R.id.snipe:
                        FragmentManager FM = getFragmentManager();
                        FragmentTransaction FT = FM.beginTransaction();
                        frg_snipe F1 = new frg_snipe();
                        FT.add(R.id.fragment_container1, F1);
                        FT.replace(R.id.fragment_container1, F1);
                        FT.commit();
                        break;
                    case R.id.aim:

                        FragmentManager FM1 = getFragmentManager();
                        FragmentTransaction FT1 = FM1.beginTransaction();
                        frg_aim F11 = new frg_aim();
                        FT1.add(R.id.fragment_container1, F11);
                        FT1.replace(R.id.fragment_container1, F11);
                        FT1.commit();
                        break;
                }
            }
        };

        rootView.findViewById(R.id.shoot).setOnClickListener(mListener);
        rootView.findViewById(R.id.snipe).setOnClickListener(mListener);
        rootView.findViewById(R.id.aim).setOnClickListener(mListener);

        return rootView;
    }

}

Other Activity:
package com.example.android.womb_the_game;

import androidx.fragment.app.FragmentActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;

public class choose_dice_column extends FragmentActivity {

   private ImageButton b1;
   private ImageView im1;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_choose_dice_column);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

      b1 = (ImageButton) findViewById(R.id.b1);
      im1 = findViewById(R.id.im1);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(choose_dice_column.this, Circulation.class);
                i.putExtra("resid1",R.drawable.n1);
                startActivity(i);
            }

        });
    }
}

A: The problem is, whenever you get back to your activity, you are creating a new adapter. So add the following to your Circulation-Activity to keep the state of the adapter:
if(adapterViewPager == null)
{
    adapterViewPager = new Adapter_Circulation(getSupportFragmentManager(), this);
}


text:
Q: HighCharts' Tooltip is not displaying after zoom in WebView of Windows Phone 8.1 App I have used HighCharts in a static html file to create a graph and set that html file to uri of webview of Windows phone 8.1.
The problem is that the tooltip on data points are not displaying after zooming.
I have tried a lot but met no success.
Below is html code.

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=500, initial-scale=1.0">
    <title>Highcharts Example</title>

Any help would be appreciated!


text:
Q: jQuery ThickBox: Multiple titlebars when calling the initialization method I am using jQuery thickBox to make use of the light box effect n my page.Some times i load the content of one of my DIV using jQuery's load method.At that time the thick box didnt worked so I called the initialization function (I put that in another function called PreLoad() and invoiked it  )available in thickbox.js before i load the content to div
$(document).ready(function(){
tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
imgLoader = new Image();// preload image
imgLoader.src = tb_pathToImage;
});

So thereafter my lightbox worked fine.I wanted to call the PreLoad() function when i load the content again and again.Now if i call the PreLoad function 4 times,I am getting 4 Title bars in my light box. no Idea how to go ahead. Any Thoughts ?? Thanks in advance

A: Or add
$("#TB_window").html("");

somewhere at the top of tb_show function in the thickbox.js file.

A: You need to add a call to "tb_remove();" into your interaction pattern.  That should cleanly dismount a thickbox instance.
Just add "tb_remove();" to the top of your PreLoad() function.


text:
Q: SwiftUI Edit Struct from List I am attempting to have a list that when a cell it tapped it changes the hasBeenSeen Bool value within the State object itself.
struct State: Identifiable {
    var id = UUID()
    let name: String
    var hasBeenSeen: Bool = false
}

struct ContentView: View {
    let states: [State] = [
        State(name: "Oregon", hasBeenSeen: true),
        State(name: "California", hasBeenSeen: true),
        State(name: "Massachussets", hasBeenSeen: false),
        State(name: "Washington", hasBeenSeen: true),
        State(name: "Georgia", hasBeenSeen: false)
    ]

    var body: some View {
        NavigationView {
            List {
                ForEach(states, id: \.id) { state in
                    StateCell(state: state)
                }
            }.navigationBarTitle(Text("States"))
        }
    }
}

struct StateCell: View {
    var state: State

    var body: some View {
        HStack {
            Text(state.name)
            Spacer()
            if state.hasBeenSeen {
                Image(systemName: "eye.fill")
            }
        }.onTapGesture {
//            state.hasBeenSeen.toggle()
        }
    }
}

My original thought is that I need to make hasBeenSeen to a @State var but that doesn't seem to work. How can I make this Bool val editable from a list?

A: Views in SwiftUI are immutable - they are just structures - so you can't change their properties. That's why SwiftUI has a concept of a @State property wrapper. When you change "state" property, SwiftUI actually updates the state value, not the view's property value (which is, again, immutable).
So, you need to set @State on the states property within your view. (You'd also need to change the name, since identifier State is already taken by the State property wrapper - so I just changed it to StateEntity)
@State var states: [StateEntity] = [
      StateEntity(name: "Oregon", hasBeenSeen: true),
      // ... etc
   ]

That's not enough, though, since when you pass an element of the states array (a StateEntity value) to a child view, you're just passing a copy.
For that, you'd need a binding. A binding allows child views to modify state properties of parent views, without owning the data. So, the child view's property should use the @Binding property wrapper:
struct StateCell: View {
    @Binding var state: StateEntity

    // ...
}

SwiftUI made it easy to get the binding of state property by using the projected value, which in this case is $states.
However, you need to pass a binding not to the entire array, but to a specific element of that array. That, unfortunately (and rather annoyingly), is a bit trickier. You need to get the index of the element, and given the index, access the binding like so: $state[index].
One way is to do a ForEach over indices of states:
var body: some View {
   NavigationView {
      List {
         ForEach(states.indices) { index in
            StateCell(state: self.$states[index])
         }
      }.navigationBarTitle(Text("States"))
   }
}


text:
Q: In Ruby on Rails, render 'shared/score', :locals => { :score => @foo.score } will not pass in the local? Maybe I missed something in http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
It seems that to render a partial, we can use
render 'shared/score'

but the next section talks about locals
render :partial => 'bar', :locals => { :score => @foo.score }

But what about the first form?
render 'shared/score', :locals => { :score => @foo.score }

The line above will not pass in the locals, why?
It seems like it has to be
render :partial => 'shared/score', :locals => { :score => @foo.score }

but why is that?  (I am using Rails 3.0.6)

A: You actually want:
render 'shared/score', { :score => @foo.score }

Explanation
You can look at this for their source code on render.
http://api.rubyonrails.org/classes/ActionView/Rendering.html#method-i-render
If you see that if the first parameter is NOT a hash, it will default to that being the name of the partial, and pass the second paramater as locals.
The catch is that it wants the locals of in the 2nd paramater. :locals => {:score => @foo.score} may seem right at first, but you actually want: {:score=> @foo.score}.
The reason for this is that it sets the :locals option for the _render_partial method to the second paramater. So if you were to do it your way, it would actually look like:
:locals => {:locals => {:score=>@foo.score}}

Which doesn't make much sense.


text:
Q: How to reproject a raster based on another raster when the datum is not said and get the same extent? I am working with two rasters. I am trying to reproject r1 the same way as the raster r2. Rasters are available here
r1
class       : RasterLayer
dimensions  : 30286, 58025, 1757345150  (nrow, ncol, ncell)
resolution  : 99.99876, 99.99876  (x, y)
extent      : -2893269, 2909160, 224962.6, 3253525  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0
values      : 0, 7 (min, max)

r2
class       : RasterLayer
dimensions  : 585, 1386, 810810  (nrow, ncol, ncell)
resolution  : 0.04166599, 0.041666  (x, y)
extent      : 235.207, 292.9561, 25.04224, 49.41686  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84 +no_defs
values      : -7.904284, 12.21496  (min, max)

I precise that the resolution of r1 is 100 m and the resolution of r2 is supposed to be 4km. Moreover, the system of coordinates is different as one is in degree and another one in meter.
I would like to reproject the rasters in order they keep their own resolution and share the same extent.
I did not find a way to do it. When I upload my data in Arcgis, the rasters are aligned as I would like which is not the case with Qgis and R. The final goal would be to allow raster calculations by stacking the raster for example.
I do not want to reproject the raster from r2 to r1 as I am working with thousands of raster that have the same coordinates than r2.
I can work with Arcgis, Qgis, and R. However, I do not know how to code in Python.
Currently, by applying the method by Spacedman (answers below), I obtained. This is much better as my rasters are closers but there are still not at the same position when I plot them. Moreover, the resolution of r1 has changed. I am confused to what is the problem.

A: The extent of r2 is giving problems because its not in the longitude range -180 to 180, but probably 0 to 360:
extent      : 235.207, 292.9561, 25.04224, 49.41686  (xmin, xmax, ymin, ymax)

If you fix that then:
r1p = projectRaster(r1, r2)

will work nicely.
You can fix this by reassigning the extent of a raster to a new extent with the X coordinates minus 360:
> r2
class       : RasterLayer
dimensions  : 585, 1386, 810810  (nrow, ncol, ncell)
resolution  : 0.04166599, 0.041666  (x, y)
extent      : 235.207, 292.9561, 25.04225, 49.41686  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84 +no_defs
data source : in memory
names       : layer
values      : 1, 810810  (min, max)

> extent(r2) = extent(xmin(r2)-360, xmax(r2)-360, ymin(r2), ymax(r2))
> r2
class       : RasterLayer
dimensions  : 585, 1386, 810810  (nrow, ncol, ncell)
resolution  : 0.04166602, 0.04166602  (x, y)
extent      : -124.793, -67.0439, 25.04224, 49.41686  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84 +no_defs
data source : in memory
names       : layer
values      : 1, 810810  (min, max)


text:
Q: Export and save multiple images with a single command I want to save multiple images, each with an appropriately assigned name, in my working directory. The images show inverse trigonometric function plots listed below:
$InverseTrigFunctions = {ArcSin, ArcCos, ArcSec, ArcCsc, ArcTan,  ArcCot, ArcSinh, ArcCosh, ArcSech, ArcCsch, ArcTanh, ArcCoth}
Table[DensityPlot[Im[f[(x + I y)^3]], {x, -2, 2}, {y, -2, 2},  ColorFunction -> "Pastel", ExclusionsStyle -> {None, Purple},  Mesh -> None, PlotLabel -> Im[f[(x + I y)^3]],  Ticks -> None], {f, $InverseTrigFunctions}]
I use the Export function but I cannot save the images using a single command to my working directory.
How I can do this? Using a loop?

A: Just use Export, ToString and string concatenation:
inverseTrigFunctions = {ArcSin, ArcCos, ArcSec, ArcCsc, ArcTan,
   ArcCot, ArcSinh, ArcCosh, ArcSech, ArcCsch, ArcTanh, ArcCoth};

Table[Export[ToString[f] <> "-plot.png",
  DensityPlot[Im[f[(x + I y)^3]], {x, -2, 2}, {y, -2, 2},
   ColorFunction -> "Pastel", ExclusionsStyle -> {None, Purple},
   Mesh -> None, PlotLabel -> Im[f[(x + I y)^3]], Ticks -> None]], {f,
   inverseTrigFunctions}]

This exports them to files with the function name first, "-plot.png" for the rest of the name.


text:
Q: Increased Code Cache size for Java 7, ReservedCodeCacheSize needs to be twice as big as Java 6 I'm moving an app from Java 6 to Java 7, after switching to Java 7 the Code Cache usage is significantly higher. On Java 6 my app would use 160mb, it's now using more than 250mb. Is this normal?
My solution will probably just be to increase the size of the code cache but I'm trying to understand why this changed. Is this common with Java 7?


text:
Q: How to process data in the class behavior public properties in model? (Yii2) Model code:
<?php
namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use common\components\behaviors\PageAncestorBehavior;

/**
 * This is the model class for table "page".
 *
 * @property integer $id
 * @property string $title
 * @property string $title_eng
 * @property string $text
 * @property integer $update_ts
 *
 * @property PageTreepath[] $pageTreepaths
 */
class Page extends \yii\db\ActiveRecord
{
    public $ancestor;
    public $descendant;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%page}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'text'], 'required'],
            [['text'], 'string'],
            [['update_ts'], 'integer'],
            [['title', 'title_eng'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => Yii::t('app', 'Заголовок'),
            'title_eng' => Yii::t('app', 'Транcлитерация заголовка'),
            'text' => Yii::t('app', 'Текст страницы'),
            'update_ts' => Yii::t('app', 'Дата и время последнего обновления'),
            'ancestor' => Yii::t('app', 'Категория'),
        ];
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => 'yii\behaviors\TimestampBehavior',
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['update_ts'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['update_ts'],
                ],
            ],
            'pageAncestor' => [
                'class' => PageAncestorBehavior::className(),
                'ancestor' => $this->ancestor
            ]
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPageTreepaths()
    {
        return $this->hasMany(PageTreepath::className(), ['ancestor' => 'id']);
    }

    /**
     * Get all pages
     * @return array
     */
    public static function getAllPages() {
        $query = new \yii\db\Query;
        $query->select('id, title')
          ->from('{{%page}}')
          ->orderBy('title');

        $command = $query->createCommand();
        return $command->queryAll();
    }

    /**
     * Get list all pages for dropdown list
     * @return array
     */
    public static function getListAllPages() {
        $data = self::getAllPages();
        $result = array(0 => '-');

        if (!empty($data)) {
            foreach ($data as $d) {
                $result[$d['id']] = $d['title'];
            }
        }

        return $result;
    }
}

Behavior code:
<?php

namespace common\components\behaviors;

use yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use common\models\Page;

class PageAncestorBehavior extends Behavior
{
    public $ancestor;

    public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
        ];
    }

    /**
     * @param $event
     */
    public function beforeInsert($event)
    {

        // --- How to get ancestor value?

        //error_log("Ancestor:".$this->ancestor);
    }

    /**
     * @return Page
     */
    private function getOwner() {
        return $this->owner;
    }
}

View:
<?php $form = ActiveForm::begin([
            'enableClientValidation'=> true,
            'enableAjaxValidation'=> false,
            'validateOnSubmit' => true,
            'validateOnChange' => true,
            'validateOnType' => true,

        ]); ?>

    <?php echo $form->errorSummary($model); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => 255]) ?>

    <?php
         $redactor = yii\imperavi\Widget::widget(
            [
                'model' => $model,
                'attribute' => 'text',
                'options' => [
                    'minHeight' => 400,
                ],
            ]
        );
        $error = Html::error($model,'text', ['class' => 'help-block']); //error
    ?>

    <?= $form->field($model, 'text', ['template' => "{$error}\n{label}\n{hint}\n{$redactor}"])->textarea();?>

    <?php
        // There is select for Page[ancestor]. Inf Behavior i don't recieved this.
       echo $form->field($model, 'ancestor')->dropDownList($allPages);
    ?>

        <?= Html::submitButton(
            $model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'),
            ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']
        ) ?>

    <?php ActiveForm::end(); ?>

Controller:
public function actionCreate()
    {
        $model = new Page;
        $allPages = Page::getListAllPages();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'allPages' => $allPages
            ]);
        }
    }

I obtain all data from the form, but I don't receive value of $ancestor.
I want to receive these ancestor from the form that to use them in behavior.
Sorry for my English.

A: Just add ancestor to your rules and try!
 [['title','ancestor', 'text'], 'required'],

A: The variable must be public in the behavior. And in the behavior you access it with this a way $this->ancestor
In your model set pageAncestor, but the name of behavior is PageAncestorBehavior.... why?


text:
Q: Should a TRACE request contain a message body or not? HTTPbis section 7.8 describes the expectations of a TRACE request.

A TRACE request MUST NOT include a message-body. [...] the response SHOULD have a Content-Type of "message/http" (see Section 10.3.1 of [Part1]) and contain a message-body that encloses a copy of the entire request message.

To me it seems to be contradicting itself indicating that there MUST NOT be a message-body, but that there should be a message-body enclosing the entire request -- How is this handled in practice?

A: The actual spec is RFC 7231 (https://greenbytes.de/tech/webdav/rfc7231.html#rfc.section.4.3.8).
WRT question: one statement is about the request, the other is about the response.


text:
Q: Prove if $A$ has $n$ elements then $\mathscr{P_2}(A)$ has $\frac{n(n − 1)}{2}$ elements. I am working on this question

If $A$ is a set, let $\mathscr{P_2}(A)$ be the set of all subsets of $A$ that have exactly two elements. Prove that for every set A, if $A$ has $n$ elements then $\mathscr{P_2}(A)$ has $\frac{n(n − 1)}{2}$ elements.

prove by induction
Proof:
Base case: when $A$ has one element, $\mathscr{P_2}(A)$ two elements. This is true.
Induction case: suppose $A$ has $n$ elements, then $\mathscr{P_2}(A)$ has $\frac{n(n − 1)}{2}$ ; to show if $A$ has $n+1$ elements, then $\mathscr{P_2}(A)$ has $\frac{n(n + 1)}{2}$.
Then we have: $$ \frac{n(n + 1)}{2}=\frac{n(n-1)}{2}+n=\frac{n(n-1)}{2}+\frac{2n}{2}=\frac{n(n + 1)}{2}$$
Therefore, if $A$ has $n$ elements, then $\mathscr{P_2}(A)$ has $\frac{n(n − 1)}{2}$ elements. $\small\square$
Does my proof valid? If not, can anyone give me a hit or suggestion?
Thanks

A: 2 issues:

*

*Your base case has an error: if $|A|=1$, then $|\mathscr{P}_2(A)|=0=1\times(1-1)/2$. Perhaps this is your intended meaning but the wording is a bit strange.

*While the manipulation
$$
\frac{n(n + 1)}{2}=\frac{n(n-1)}{2}+n=\frac{n(n-1)}{2}+\frac{2n}{2}=\frac{n(n + 1)}{2}
$$
is correct, it's not clear what you are trying to say with it. Perhaps you meant something like this:

Suppose $|A|=n+1$ and let $B$ be $A\backslash\{a_0\}$ for some element $a_0$ of $A$. Let's look at the elements of $\mathscr{P}_2(A)$. Either an element is formed from 2 members from $B$ or an element is formed by pairing $a_0$ with a member of $B$. By the induction hypothesis, there are $n(n-1)/2$  formations of the first kind and, because $|B|=n$, there are $n$ formations of the second kind. We conclude:
$$
|\mathscr{P}_2(A)|=|\mathscr{P}_2(B)|+n=\frac{n(n-1)}{2}+n=\frac{(n+1)n}{2}\cdot
$$


text:
Q: GoF Design Patterns - which ones do you actually use? I'm trying to educate my colleagues in the area of design patterns.  Some of the original Gang of Four patterns are a little esoteric, so I'm wondering if there is a sub-group of "essential" patterns that all programmers should know. As I look through the list, I think I've probably used -

*

*Abstract Factory

*Factory Method

*Singleton

*Bridge

*Facade

*Command

Which ones do you actually use in practice, and what do you use them for?
Link for those wanting a list of patterns

A: The authors compiled the patterns from observed designs they found in real applications.  No one person will likely use all of them, but they are all used.

A: Here's a list of which ones I've used or seen in practice:
Singleton - Application object in ASP.Net being a prime example of this.
Adapter - Connecting to databases usually can involve an Adapter class at least in my area of .Net stuff.
Factory - General for generating objects though I saw this more in some older classic ASP back in the day.
Strategy - I had an application which for each type of device I had a similar structure for the class that I'd consider an implementation of this pattern.
Facade - In some ways this is similar to the Adapter pattern in terms of being something that ties together a couple of systems usually.

A: Decorator.
EDIT: In almost every project that gets beyond the 'trivial' stage, one ends up with an IAction interface (details may differ):
// Programming Language does not matter
interface IAction {
     bool operateOn(Foo* target);
     string getDisplayName(); // useful for debugging and logging
};

The next hour I spend on writing a lot of small, almost trivial classes that implement IAction. When combined, they are very powerful and flexible.
E.g. an LogAction (write to log and perform the IAction), NullAction (do nothing and return true), ActionList (perform a list of IActions, and return the ANDing of the bools). In some cases an AndAction (return the AND-ing of two actions, could be short-circuited or not), OrAction, NotAction make sense as well.
Although technically from the examples above only the LogAction is a Decorator (the other do not operate on exactly 1 IAction), I still consider this a generalization of the Decorator pattern when I make a ActionList of LogActions of IActions.

A: I assume you mean to restrict the question to usage of patterns in own code / projects (no class libraries and 3rd party frameworks).
As did others, I have also used the Factory patterns most often. Then

*

*Singleton: not so much nowadays, but still sometimes it is necessary, typically for global configuration data

*Strategy and Template Method: quite often, e.g. for representing different kinds of calculations in our app

*Builder: for marshalling the results of transactions with a mainframe system into output objects (in some cases it includes a great deal of text parsing and creating large object hierarchies)

*Command: I implemented it only once many years ago, but nowadays in our Java project I use Callables every now and then, which I believe are basically Commands

A: I've used many of the others which have already been mentioned (Singleton, Factory, Builder, Command, Strategy, etc...)
One I haven't seen mentioned yet is Flyweight, which I tend to use a lot. I've provided an example implementation below:
/**
 * Flyweight class representing OCR digits.
 *
 * @author matt
 *
 */
public class Digit {
    /** Static flyweight map containing Digits which have been encountered. **/
    private static Map digits = new HashMap();

    /** The block of text representing Digit. **/
    private String blockRep = null;

    /** A map representing acceptable blocks of characters and the string representation of their
     * numerical equivalents.
     */
    public static final Map VALID_DIGITS;

    /** Enum of valid digits. **/
    public static enum DigitRep {
        ZERO    (   " _ \n" +
                    "| |\n" +
                    "|_|"       ),

        ONE (       "   \n" +
                    "  |\n" +
                    "  |"       ),

        TWO (       " _ \n" +
                    " _|\n" +
                    "|_ "       ),

        THREE   (   " _ \n" +
                    " _|\n" +
                    " _|"       ),

        FOUR    (   "   \n" +
                    "|_|\n" +
                    "  |"       ),

        FIVE    (   " _ \n" +
                    "|_ \n" +
                    " _|"       ),

        SIX     (   " _ \n" +
                    "|_ \n" +
                    "|_|"       ),

        SEVEN   (   " _ \n" +
                    "  |\n" +
                    "  |"       ),

        EIGHT   (   " _ \n" +
                    "|_|\n" +
                    "|_|"       ),

        NINE    (   " _ \n" +
                    "|_|\n" +
                    " _|"       );

        private String blockRep;

        DigitRep(String blockRep) {
            this.blockRep = blockRep;
        }

        @Override
        public String toString() {
            return blockRep;
        }
    }

    static {
        /* Initialize the map of acceptable character blocks. */
        Map tmpMap = new HashMap();
        tmpMap.put( DigitRep.ZERO.toString(),   "0");
        tmpMap.put( DigitRep.ONE.toString(),    "1");
        tmpMap.put( DigitRep.TWO.toString(),    "2");
        tmpMap.put( DigitRep.THREE.toString(),  "3");
        tmpMap.put( DigitRep.FOUR.toString(),   "4");
        tmpMap.put( DigitRep.FIVE.toString(),   "5");
        tmpMap.put( DigitRep.SIX.toString(),    "6");
        tmpMap.put( DigitRep.SEVEN.toString(),  "7");
        tmpMap.put( DigitRep.EIGHT.toString(),  "8");
        tmpMap.put( DigitRep.NINE.toString(),   "9");
        VALID_DIGITS = Collections.unmodifiableMap(tmpMap);
    }

    /**
     * Private constructor to enforce flyweight/factory pattern.
     *
     * @param blockRep
     */
    private Digit(String blockRep) {
        this.blockRep = blockRep;
    }

    /**
     * Flyweight factory method to create a Digit object from the "block"
     * representation of the digit.
     * @param blockRep The "block" representation of a digit.  Should look
     * something like:
     * " _ \n"
     * "|_|\n"
     * "|_|"
     * @return A flyweight Digit object representing the digit.
     */
    public static synchronized Digit getDigit(String blockRep) {
        Digit digit = digits.get(blockRep);
        if(digit == null) {
            digit = new Digit(blockRep);
            digits.put(blockRep, digit);
        }

        return digit;
    }

    /**
     * Determines whether or not the digit is valid.
     * @return true if the digit is valid, else false.
     */
    public boolean isValid() {
        return VALID_DIGITS.containsKey(blockRep);
    }

    /**
     * Accessor method to get the block representation of this digit.
     *
     * @return
     */
    public String getBlockRep() {
        return blockRep;
    }

    @Override
    public String toString() {
        return VALID_DIGITS.containsKey(blockRep) ? VALID_DIGITS.get(blockRep) : "?";
    }
}

A: Most of the original Gang of Four patterns are still used today, but there are other now popular ones that aren't in the book.
Find a reference for Design Patters in the language you use. They tend to be more concrete and use specific language features to implement the patterns in a more succinct and elegant way.
Three great resources for Design Patterns:
"Head First Design Patterns" Book - the language of choice is Java, but is relevant to all languages.
dofactory Design Patterns - great and free .net design patterns explanations with code.
PluralSight - Design Patterns Library - this one is paid, but is too good not to include it in the list.

A: Well if you use common libraries like ACE, you end up using more than you think you use. I use Observer/Observable extensively :-)

A: I used a Builder at least once (the same converter process could build HTML or Excel output).
I frequently use the Template Method (for JDBC-related tasks, or abstract Swing controllers).
Once I had to develop lots of new features into a form-based application, which was a mess.
I could only progress after I had refactored the existing stuff to a State-pattern based solution.
(Well, most of it).
I also use Commands frequently (Swing Actions), and Observers too.
Once I used a Mememento-like solution for detecting changes in Swing forms. The form would
serialize its state what I compared (equals()) to earlier states.

A: I believe I have most them thru-out my career. the only one I am sure I have not used is that Adapter Pattern that is implemented with multiple inheritance on the book as I am not a big fan of multiple inheritance.

A: I'm fond of Decorator. The only one I've got add to those mentioned is Proxy.


text:
Q: Modify Excel file in ASP.NET "on the fly"
EDIT
  This question is no more justified because I can now save the Excel files on the server.
  But thanks to everyone for the answers!

I am writing an ASP.NET application in which a user uploads an Excel file.
I have to edit it and generated pictures "on the fly" (meaning no storage) then zip the Excel files with the pictures and send it back to the user.
My problem is that I don't know how to edit the Excel file that has been sent then send it back with the exact same name...
Here is the controller handling the upload of the file:
    [HttpPost]
    public ActionResult PoliteUpload(HttpPostedFileBase UserFile)
    {
        String viewReturned = "Polite";
        if (UserFile != null && UserFile.ContentLength > 0)
        {
            TempData["MessageTitle"] = @Resource.ExtensionOkTitle;
            TempData["Message"] = @Resource.ExtensionOk;
            string extension = Path.GetExtension(UserFile.FileName);
            if (extension.Equals(".xls"))
            {
                 //Old version ok
            }
            else if (extension.Equals(".xlsx"))
            {
                 //Current version ok
            }
            else
            {
                TempData["Error"] = true;
                TempData["Message"] = @Resource.ExtensionKo;
                TempData["MessageTitle"] = @Resource.ExtensionKoTitle;
            }
        }
        else
        {
            TempData["Error"] = true;
            TempData["MessageTitle"] = @Resource.NoFileTitle;
            TempData["Message"] = @Resource.NoFile;
        }
        return RedirectToAction(viewReturned);
    }

Could anyone help me on this?


text:
Q: Is there way to configure magento to bcc an email in every mail send out on an order? I need to send a copy of the order email to a particular email address every time an success order was placed. Is there way to configure this in magento without modifying or rewriting the sales order class ?

A: In your Magento Admin Panel, go to System > Configuration  and in left tabs find Sales
Under sales select 'Sales Emails' , there in every tab and for every email type: order or invoice or shipment, there is option: Send Order Email Copy To write your desired email address here.
Select "Send Order Email Copy Method" if you want to send it as separate email or as BCC.

A: Magento Admin -> System -> Configuration -> Sales -> Sales Emails -> Order -> Send Order Email Copy To


text:
Q: SQL relation 1 key not 2 keys between tables I want to define a foreign key constraint between the table Speler and the table Wedstrijd. I want the key on the Wedstrijd table, but when I use this code in my SQL console:
ALTER TABLE Speler
ADD FOREIGN KEY (idSpeler) REFERENCES Wedstrijd(idWedstrijd);

It puts a key on the table Speler and on the table Wedstrijd
Thanks for your time!

A: ALTER TABLE Wedstrijd
ADD FOREIGN KEY (idWedstrijd) REFERENCES Speler(idSpeler);

A: Instead of "solving" what you perceive as your problem, I think you have a different problem:
By mapping idSpeler to idWedstrijd, you are basically saying that a Speler (Player) is equal to a Wedstrijd (Match). That becomes a 1:1 relation which is then shown as a line with two yellow 'key'-endings (assuming you are using SQL Server).
It is very likely to me that instead you need to create a linking table WedstrijdSpeler that sits between the other two tables.
Then the new table WedstrijdSpeler needs to be given 2 Foreign Keys:

*

*WedstrijdSpeler.idWedstrijd -> Wedstrijd.idWedstrijd

*WedstrijdSpeler.idSpeler -> Speler.idSpeler.

Then you can give WedstrijdSpeler either a combined Primary Key (containing both fields idWedstrijd and idSpeler), or you can add a third field idWedstrijdSpeler and make that the Primary Key. Either approach will do, it is up to you.


text:
Q: Swift custom UITableviewCell width issue I have created a custom UITableviewCell in xcode 6 beta(5), but while testing on the simulator it looks too small, I tried to set the width using attribute inspector, and it didn't worked. I created it using a .xib file and I registered it in my mainViewController to use it with connected tableView
This is how it looks like in simulator

The cell part of the code, where my custom class name is CustomCell
 var cell:CustomCell = self.tableview.dequeueReusableCellWithIdentifier("cell") as CustomCell
 cell.txt.text="\(ListArray.objectAtIndex(indexPath.row))"
 return cell

This is how I register in viewDidLoad
 var nipName=UINib(nibName: "CustomCell", bundle:nil)
 self.tableview.registerClass(CustomCell.classForCoder(), forCellReuseIdentifier: "cell")
 self.tableview.registerNib(nipName, forCellReuseIdentifier: "cell")

A: Take a look at my response to UILabels in custom UITableViewCell never gets initialized . First of all, code in the heightForRowAtIndexPath function. Second, depending on how you set up the nib/storyboard, if it already connected the tableview to the custom view, get rid of registerClass. Otherwise it'll disconnect your nib connection and recreate a new one, wiping out all the customization you did in the nib.


text:
Q: Changing text isnt working in this instance, using jquery and javascript Create a password-protected account

This is what my login says on my site. I want to change the text to something simple like "Sign up here for a new account." I need a method which only uses Javascript/jQuery; I cant change the original code.
I've tried several things, but none of them work:

*

*document.body.innerHTML = document.body.innerHTML.replace(/Create a password-protected account/g, "Sign up here for a new account");

*document.body.innerHTML = document.body.innerHTML.replace("Create a password-protected account", "Sign up here for a new account");

*$('.create-password-account').html('Sign up here for a new account');

A: Use text() to change the text value
 $('.create-password-account').text('Sign up here for a new account');

A: Make sure you

*

*Include jQuery

*Wrap the line in a document.onready method

See example:
$(document).ready(function(){
    $('.create-password-account').text('Sign up here for a new account');
});

Here's a fiddle


text:
Q: WCF Operation contract availability This question was asked at interview.
Say I have a contract.
[ServiceContract]
public interface IMyService
{
  [OperationContract]
  void methodForClientA();

   [OperationContract]
   void  AnothermethodForClientA();

   [OperationContract]
   void methodForClientB();

  [OperationContract]
  void  AnothermethodForClientB();
}

When a clientA access the contract it should only  see the operation contracts
void methodForClientA(),void  AnothermethodForClientA().

Is it possible in WCF ?

A: You cannot keep client A and client B from seeing each other's methods, because they're all defined in the same contract.
You can, however, keep Client A and Client B from calling each other's methods, using WCF's security mechanisms.
Alternatively, you could have two separate services, each unique to the client.
Edit
The more I think about it, the more I would prefer the separate services options for such a scenario. If you have methods specific to each client, you really have separate services anyway, each specific to the particular client.


text:
Q: Show method parameters/prototype in PhpStorm Is there a way to see a method definition (parameters/prototype) in PhpStorm? I'm thinking of something similar to the way eclipse shows method declarations.

A: View | Quick Documentation for method description and info on parameters.
View | Quick Definition to see actual method definition (code).


text:
Q: R Programming - Identify items with exceptional sequence I have data in format similar to this:
ID  Timestamp   Status
1   1/1/2014    1
2   1/1/2014    1
3   1/2/2014    1
4   1/3/2014    1
1   1/3/2014    2
3   1/3/2014    2
4   1/5/2014    2
5   1/5/2014    1
1   1/6/2014    3
2   1/7/2014    3
3   1/8/2014    3
4   1/9/2014    3
5   1/10/2014   2
6   1/10/2014   1
3   1/10/2014   4
3   1/10/2014   5
3   1/10/2014   6
1   1/11/2014   4
2   1/11/2014   3
3   1/11/2014   4
3   1/11/2014   2
5   1/11/2014   3
6   1/12/2014   4
7   1/12/2014   5
5   1/12/2014   6
4   1/12/2014   7
2   1/13/2014   3
3   1/13/2014   4
1   1/14/2014   5
5   1/14/2014   3
6   1/14/2014   4
1   1/15/2014   6
1   1/16/2014   7

Each ID have to go through status from 1 to 7 in order 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
However, due to the data entry error, sometime the 4 happen before 3, 6 happen before 2, 7 happen before 1.
So can R help to identify the IDs that have status change not as the rule?
For above sample data - Only ID 1 have the correct status history 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 - Others are note correct.
Thank you very much!

A: Assuming it's OK for ID's to skip and duplicate statuses (just never go backwards) You could do something like this. Here's the data.frame I used to test
dd<-structure(list(ID = c(1L, 2L, 3L, 4L, 1L, 3L, 4L, 5L, 1L, 2L,
3L, 4L, 5L, 6L, 3L, 3L, 3L, 1L, 2L, 3L, 3L, 5L, 6L, 7L, 5L, 4L,
2L, 3L, 1L, 5L, 6L, 1L, 1L), Timestamp = structure(c(18262, 18262,
18263, 18264, 18264, 18264, 18266, 18266, 18267, 18268, 18269,
18270, 18271, 18271, 18271, 18271, 18271, 18272, 18272, 18272,
18272, 18272, 18273, 18273, 18273, 18273, 18274, 18274, 18275,
18275, 18275, 18276, 18277), class = "Date"), Status = c(1L,
1L, 1L, 1L, 2L, 2L, 2L, 1L, 3L, 3L, 3L, 3L, 2L, 1L, 4L, 5L, 6L,
4L, 3L, 4L, 2L, 3L, 4L, 5L, 6L, 7L, 3L, 4L, 5L, 3L, 4L, 6L, 7L
)), .Names = c("ID", "Timestamp", "Status"), row.names = c(NA,
-33L), class = "data.frame")

And then I define a helper function to test that all the difference in the status values are are all 1 and that we have all seven of them
isgoodseq<-function(x) {
    length(x) ==7 & all(diff(x)==1) & min(x)==1
}

Now we run this for each ID (making sure the data is in the correct order)
with(dd[order(dd$Timestamp, dd$ID, dd$Status),],
    tapply(Status, ID, isgoodseq))

And that gives us
    1     2     3     4     5     6     7
 TRUE FALSE FALSE FALSE FALSE FALSE FALSE

Which means 1 is the only good ID


text:
Q: Watch live news on AppleTV Is there any way to watch live news on an AppleTV? This is the only thing that's preventing me from cutting my cable.

A: The Apple TV wasn't designed for that sort of thing; it's for all intents and purposes a closed system (i.e., iTunes-stored content only).
At the same time, if you have a flat screen TV, then chances are you can hook up a PC or Mac to it using it as a monitor and grab newscasts off the web (a friend does this and it works great). Also some of the higher-end flat screens offer links to content distributed by the manufacturer (Sony's Bravia line comes to mind here).


text:
Q: How can I change the background of an element based on a value inside it? I have a table of numbers - if the number inside the  is below a certain number I want to highlight that  by making it red by adding a class. My jQuery knowledge is limited but I am pretty sure this is possible to do.
I am using .text() to return the value in the s and .each() to check the numbers one by one.

$(document).ready(function() {

  $(".carpet td").each(function() {
    if ($(this).text() < 5) {
      this.addClass("red")
    }
  });

});
.carpet {
  background-color: aliceblue;
}

.carpet td {
  padding: 12px 20px;
}

.red {
  background-color: #E7295B;
}

      2
      7
      4

      3
      4
      5

      2
      1
      1

A: Updated your fiddle.  You have to parse the text into a number, and fixed the addClass to be off of a jQuery object.
https://jsfiddle.net/9mmqjtk5/12/

$(document).ready(function() {

  $(".carpet td").each(function() {
    if (parseInt($(this).text(), 10) < 5) {
      $(this).addClass("red")
    }
  });

});
.carpet {
  background-color: aliceblue;
}

.carpet td {
  padding: 12px 20px;
}

.red {
  background-color: #E7295B;
}

      2
      7
      4

      3
      4
      5

      2
      1
      1


text:
Q: Bulk Email Sending I have a list in Outlook.
I need to send email to every one in that list.
One of my friends suggested to use Microsoft Exchange.
Is it safe using Microsoft Exchange.I don't want to get my sent emails Spammed.
Can anyone suggest me ?

A: From the spam perspective, so from the question perspective, there is no difference if you use MS Exchange or something else.
For not be treated like a spam, you have to sutisfy at leaset 2 rules of destination:

*

*Actually do not contain any spam (links to porn and stuff like this)

*Sutisfy other rules of the spam filter of mail server of destination

For more detailed explanation can have a look on:
How do you make sure email you send programmatically is not automatically marked as spam?

A: If the emails are not spam and the people you are sending the emails know you and have your address as friends or whatever it should get through just like any other bulk email send.


text:
Q: Stackoverflow error comes in Microsoft.Extensions.Hosting class I had Azure function which was written using .NET Core 3.1 and suddenly stopped working and showing StackOverflow exception in below code at TryAddEnumerables

Here is my stack trace

My startup class
 builder.Services
            .AddSingleton<IConfiguration>(config)
            .AddSingleton(serviceProvider => serviceProvider)
            .AddLogging()
            .AddSingleton<IManager, CManager>()
            .AddSingleton<IRegexManager, RegexManager>()

Removing below line solves the StackOverflow error but not sure on side affects of it
 AddSingleton(serviceProvider => serviceProvider)

Trace
System.Private.CoreLib.dll!Interop.Advapi32.EventWriteTransfer_PInvoke(long registrationHandle, System.Diagnostics.Tracing.EventDescriptor eventDescriptor, System.Guid* activityId, System.Guid* relatedActivityId, int userDataCount, System.Diagnostics.Tracing.EventProvider.EventData* userData) Unknown
 System.StackOverflowException
       HResult=0x800703E9
       Source=<Cannot evaluate the exception source>
     StackTrace:
  <Cannot evaluate the exception stack trace

System.Private.CoreLib.dll!Interop.Advapi32.EventWriteTransfer(long registrationHandle, System.Diagnostics.Tracing.EventDescriptor eventDescriptor, System.Guid* activityId, System.Guid* relatedActivityId, int userDataCount, System.Diagnostics.Tracing.EventProvider.EventData* userData)   Unknown
System.Private.CoreLib.dll!System.Diagnostics.Tracing.EtwEventProvider.System.Diagnostics.Tracing.IEventProvider.EventWriteTransfer(long registrationHandle, System.Diagnostics.Tracing.EventDescriptor eventDescriptor, System.IntPtr eventHandle, System.Guid* activityId, System.Guid* relatedActivityId, int userDataCount, System.Diagnostics.Tracing.EventProvider.EventData* userData)   Unknown
System.Private.CoreLib.dll!System.Diagnostics.Tracing.EventProvider.WriteEvent(ref System.Diagnostics.Tracing.EventDescriptor eventDescriptor, System.IntPtr eventHandle, System.Guid* activityID, System.Guid* childActivityID, int dataCount, System.IntPtr data) Unknown
System.Private.CoreLib.dll!System.Diagnostics.Tracing.EventSource.WriteEventWithRelatedActivityIdCore(int eventId, System.Guid* relatedActivityId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data)  Unknown
System.Private.CoreLib.dll!System.Threading.Tasks.TplEventSource.TraceOperationBegin(int TaskID, string OperationName, long RelatedContext) Unknown
System.Private.CoreLib.dll!System.Threading.Tasks.AsyncCausalityTracer.TraceOperationCreation(System.Threading.Tasks.Task task, string operationName)   Unknown
System.Private.CoreLib.dll!System.Threading.Tasks.Task.ScheduleAndStart(bool needsProtection)   Unknown


text:
Q: Web Worker effect on max http connections on per browser per domain This question is an extension to Max HTTP Connections
What kind of impact Web worker brings to this equation, would the limit increase? As in 3 web workers would be able to send (3 * browser limit) request?


text:
Q: Grade information missing while upgrading Scorm packages from captivate to storyline Recently we started migrating a series of SCORM packages from Adobe Captivate to Articulate Storyline. However, when uploading the end package into the LMS (Moodle), all the information regarding the grades is lost.
Besides verifying the name in the manifest, is there another way to prevent this from happening?
Open to any suggestions.


text:
Q: Check that the webserver is running, and that there are no firewalls blocking Facebook's crawlers Symfony Symfony enter image description here

A: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>УБЦТС ТӨХК-аас гэрэлгүй болон  хүчдэлийн уналттай 11802 өрхийн цахилгаан хангамжийг сайжруулсан | tog.mn </title>

    <meta property="og:site_name" content="tog.mn" />
    <meta property="og:locale" content="mn_MN" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="УБЦТС ТӨХК-аас гэрэлгүй болон  хүчдэлийн уналттай 11802 өрхийн цахилгаан хангамжийг сайжруулсан"/>
    <meta property="og:description" content="

    Өнгөрсөн 2016-2018 онд нийслэлийн төвийн дүүргүүд болон Төв аймгийн&nbsp;Баянчандмань, Баян-Өнжүүл, Лүн, Аргалант, Эрдэнэ, Алтанбулаг, Баянчандмань сумын&nbsp;гэр хорооллын&nbsp;нийт&nbsp;11802 өрхийг цахилгаан эрчим хүчинд холбосон.&nbsp;

"/>
    <meta property="og:url" content="http://tog.mn/index.php/public/newsshow/id/696" />
    <meta property="fb:app_id" content="595109791247965" />
    <meta property="og:image" content="http://tog.mn/uploads/news/14e4b5fcac520ce10c8e3dd36024397b3e166eb7.jpg" />
    <meta property="og:image:secure_url" content="http://tog.mn/uploads/news/14e4b5fcac520ce10c8e3dd36024397b3e166eb7.jpg" />
    <meta property="og:image:width" content="1500" />
    <meta property="og:image:height" content="1000" />


text:
Q: ssh to debian 11 takes almost 2 min this is what I see in the syslog - the ssh is being done with Private key.
after 2 minutes - login succesfull.
Feb  8 10:01:53 systemd[1]: Starting User Manager for UID 0...
Feb  8 10:01:53 systemd[34555]: gpgconf: error running '/usr/lib/gnupg/scdaemon': probably not installed
Feb  8 10:03:23 systemd[1]: user@0.service: Main process exited, code=exited, status=1/FAILURE
Feb  8 10:03:23 systemd[1]: user@0.service: Killing process 34555 (gpgconf) with signal SIGKILL.
Feb  8 10:03:23 systemd[1]: user@0.service: Killing process 34556 (awk) with signal SIGKILL.
Feb  8 10:03:23 systemd[1]: user@0.service: Killing process 34561 (dirmngr) with signal SIGKILL.
Feb  8 10:03:23 systemd[1]: user@0.service: Killing process 34555 (gpgconf) with signal SIGKILL.
Feb  8 10:03:23 systemd[1]: user@0.service: Killing process 34556 (awk) with signal SIGKILL.
Feb  8 10:03:23 systemd[1]: user@0.service: Killing process 34561 (dirmngr) with signal SIGKILL.
Feb  8 10:03:23 systemd[1]: user@0.service: Failed with result 'exit-code'.
Feb  8 10:03:23 systemd[1]: user@0.service: Unit process 34561 (dirmngr) remains running after unit stopped.
Feb  8 10:03:23 systemd[1]: Failed to start User Manager for UID 0.
Feb  8 10:03:23 systemd[1]: Started Session 14 of user root.

A: /etc/pam.d/common-session
#session optional pam_systemd.so
will solve this issue.

A: I uninstalled packages gpg-agent and dirmngr, which were causing problems.
I don't know if they were installed automatically or installed as a dependency, but they were not needed in my system.
This is not solution for everyone, so I don't want to write a command for removing packages here.


text:
Q: Relation between binomials how can I prove that the following relation is true:
$$\binom{x-2}y+2\binom{x-2}{y-1}+\binom{x-2}{y-2}=\binom{x}y$$
Thank you for hints or references!
Marted

A: HINT: Apply Pascal's identity twice:
$$\binom{x}y=\binom{x-1}y+\binom{x-1}{y-1}=\ldots~?$$
Added: By the way, you can prove by induction on $n$ that if you apply Pascal's identity $n$ times, you get the identity
$$\binom{x}y=\sum_{k=0}^n\binom{n}k\binom{x-n}{y-k}\;.$$
Pascal's identity is the case $n=1$, and your exercise is the case $n=2$.

A: Hint: what does the left hand side count? The first term is the number of ways of choosing $y$ out of $x-2$ items. Can you make a similar statement about the other two terms on the LHS? How is this equivalent to the right hand side?


text:
Q: URL mapping using jquery in spring mvc This somewhat confusing but it is my project requirement. I am using spring mvc and jquery. Now I have to post the form and expose the data to back end using ajax call of jquery for this my jquery is
home='<%=request.getContextPath()%>';

$('#userReg').submit(function(event){
    var add = {}
    add["type"] = $("#type").val();
    add["name"] = $("#companyName").val();
    add["regNumber"] = $("#regNumber").val();
    add["dob"] = $("#dob").val();
    add["email"] = $("#email").val();
    add["password"] = $("#password").val();
    add["confirmPassword"] = $("#cpassword").val();
    add["line1"] = $("#line1").val();
    add["line2"] = $("#line2").val();
    add["state"] = $("#state").val();
    add["country"] = $("#country").val();
    add["zipCode"] = $("#zipCode").val();
    console.log("search: ", add);
    event.preventDefault();
    $.ajax({
        type : "POST",
         headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            url : home+"/addCompany",
        data : JSON.stringify(add),
        dataType : 'json',
        timeout : 100000,
        success : function(data) {
            console.log("SUCCESS: ", data);
            alert(data)

        },
        error : function(e) {
            console.log("ERROR: ", e);
            alert(e);

        },done : function(e) {
            console.log("DONE");
        }
});
});

and corresponding method
 @RequestMapping(value="/addCompany",method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
   public@ResponseBody String userLogin(HttpServletRequest req,@RequestBody CompanyRegVO user){
    logger.debug("signUp user:"+user);
     // get reCAPTCHA request param
    String gRecaptchaResponse = req.getParameter("g-recaptcha-response");
    boolean isVerified= Verify.verifyGcaptchResponse(gRecaptchaResponse);
    ObjectMapper mapper=new ObjectMapper();
    String jsonString="";
    System.out.println("signUp user:"+user);
    Integer id=null;
    try{
        if(isVerified){
            id = signupHandler.process(user);
            if(id!=null){
                logger.debug("ID in controller:"+id);

                emailHandler.sendVerificationMail(id,user.getEmail());
                System.out.println("user create successfully");

            }
            jsonString=mapper.writeValueAsString("User creaated successfully");

        }
         else
        jsonString= mapper.writeValueAsString("please verify that you are not a robot");
    } catch (JsonGenerationException e) {

        e.printStackTrace();
    } catch (JsonMappingException e) {

        e.printStackTrace();
    } catch (IOException e) {
                e.printStackTrace();
    } catch (Exception e) {
        try {
            jsonString=mapper.writeValueAsString(e.getMessage());
        } catch (JsonProcessingException e1) {

        }
        return jsonString;
    }

    return "success";

   }

Now my form is mapped with this URL
@RequestMapping(value="/signUp",method=RequestMethod.GET)
   public String register(Model model){
    CompanyRegVO user=new CompanyRegVO();
    model.addAttribute("userForm", user);
    return "signUp";
   }

When I submit my form I expected that my jquery code will execute will invoke my upper one method but it inovkes above get method and return me signUp page with my data as query parameter. Now if I comment mapping for "/signUp" my server is giving 404 error. since page is mapped to that URL. So any one can please tell what is remedy for this kind of situation jquery or spring??
Edit 1:
below is my form
<form class="form-horizontal" name="userReg"  id="userReg">

 Company Name

 <input  name="companyName" type="text"   class="form-control" id="companyName" placeholder="Name" />

 Registration number

 <input  name="RegNumber" type="number" required="required"  class="form-control" id="regNumber" placeholder="Registration number" />

 Address line 1

 <input  name="line1" type="text" required="required"  class="form-control" id="line1" placeholder="line1" />

 Address line 2

 <input  name="line2" type="text"   class="form-control" id="line2" placeholder="line2" />

 Zip code

 <input  name="zipCode" type="number" required="required"  class="form-control" id="zipCode" placeholder="zip code" />

 State

 <input  name="state" type="text" required="required"  class="form-control" id="state" placeholder="State" />

 Country

 <input  name="country" type="text" required="required"  class="form-control" id="country" placeholder="country" />

Email

<input name="email" type="email" class="form-control" id="email" placeholder="Email" />

Date of Birth(dd-mm-yyyy)

<input name="dob"  type="text" class="form-control" id="dob" placeholder="Date of birth" />

Password

<input name="password" id="password" maxlength="12" pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,12})" required="required" type="password" class="form-control" id="password" placeholder="password" />

Confirm Password

<input name="confirmPassword" id="cpassword"  maxlength="12" required="required" type="password" class="form-control" id="cpassword" placeholder="confirm password" />

User type

<select class="form-control" id="type" name="type" >
<option selected="selected">--select--</option>
 <option  value="user" >CEO</option>
 <option value="admin">HR</option>

</select>

<input type="submit" class="btn-lg btn-primary center-block" value="save">

 </form>

A: When use <input type="submit" ..... /> it will submit your form according to your form action url. e.g something.html
So change the  and add a click listener.
<input type="button" onclick="_submit()"/>

and your js would be
function _submit(){
    // submit your form via ajax.
}

This should submit your form with your specified url.
Thanks.


text:
Q: How do you delete an entire column of values from an ndarray obtained from misc.imread()? I am reading a png image and it is in RGBA format and i would like to remove the 'A' part. The shape of my image is (694, 1077, 4) but I would like it to be (694, 1077, 3). I'd like to remove the last column in the array so I only have RGB values.

A: Simply do this:
im_without_A = im[:, :, :3]

A: nd = np.random.randn(60).reshape(3,4,5)
print nd
print nd[:,:,:nd.shape[2]-1].shape #(3L, 4L, 4L)

This will take out the last column.

A: You can use the mode='RGB' parameter (see docs), which should omit the alpha band.


text:
Q: Mule 3: How to get the values of "global-property" elements from Java source code Is there a way to retrieve the values of "global-property" elements in Java code?
<mule xmlns="http://www.mulesoft.org/schema/mule/core">
  <global-property name="theKey" value="theValue" />
</mule>

I'm using Mule 3.2.1.  Thanks.

A: This:
MuleContext muleContext = ...
muleContext.getRegistry().get("theKey");


text:
Q: Problema mysqli_fetch_assoc() | não é nada a ver com bolean ;) sou novo aqui, estou com um problema no codigo abaixo.: alguem consegue me dar uma luz?
Codigo.:

   <?php
   while($linha = mysqli_fetch_assoc ($resultado))
   {
      echo '
';
      echo ''. $linha['ID'] .'	';
      echo ''. $linha['id'] .'	';
      echo ''. $linha['id'] .'	';
      echo ''. $linha['id'] .'	';
      echo ''. $linha['id'] .'	';
      echo ''. $linha['id'] .'	';
      echo '
';
   }
   mysqli_close ($conexao);
   ?>

Erro.:

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
  null given in
  /home/u666149583/public_html/bootstrap/motorista/listar.php on line 70


text:
Q: taskqueue for deleting entities fail - python - flask - google appengine I don't know what I'm doing.
That's why my google appengine taskqueue isn't working.
The goal is to simply delete a million billion entities upon request ... okay.. not that many. I don't really want to succum to using mapreduce and I don't think I'll need too.  Still pretty sure that a request without a task queue implementation will time out. Hence a taskqueue.
In my case, a taskqueue that fails. Like this:

INFO     2018-01-28 18:48:21,129 module.py:788] default: "POST /del/text HTTP/1.1" 302 -
  WARNING  2018-01-28 18:48:21,129 taskqueue_stub.py:1981] Task task5 failed to execute. This task will retry in 3600.000 seconds

Here is my wonderful failure code:
@sign_in_
@app.route('/del/<entity_kind>', methods=["GET", "POST"])
def DeleteStuff(entity_kind):

  allowed_deletion = {
    'text': models.Text,
  }

  cursor = None
  bookmark = request.form.get('bookmark', '')
  if bookmark:
    cursor = ndb.Cursor.from_websafe_string(bookmark)

  query = allowed_deletion[entity_kind].query()
  entries, next_cursor, more = query.fetch_page(
    1000,
    keys_only=True,
    start_cursor=cursor)

  ndb.delete_multi(entries)

  bookmark = None
  if more:
    bookmark = next_cursor.to_websafe_string()

  taskqueue.add(
    url='/del/'+entity_kind,
    params={'bookmark': bookmark}
    )
  return "{0} deleted".format(entity_kind)

However, I can't even get a task with just a return statement in it to execute:
in app.yaml
- url: /del/*
  script: app.app
  login: admin

"trigger" handler tied to app.yaml:
@sign_in_
@app.route('/del/<entity_kind>', methods=["GET", "POST"])
def DeleteStuff(entity_kind):

  allowed_deletion = {
    'text': models.Text,
    'call': models.Call,
    'voicemail': models.Voicemail,
    'image': models.Image,
    'email': models.Email,
  }

  taskqueue.add(
    url='/deleting/'+entity_kind,
    #params={'bookmark': bookmark}
    )
  return "{0} to be deleted".format(entity_kind)

worker.yaml:
runtime: python27
api_version: 1
threadsafe: true
service: worker

handlers:
- url: /deleting/.*
  script: worker.app
  login: admin

worker.py:
from flask import Flask, render_template, request, redirect, url_for, abort, make_response
from google.appengine.ext import ndb
import datetime

from app import app
from app import models

@app.route('/deleting/<entity_kind>',methods=['POST'])
def DeletingStuff(entity_kind):

  print "entered task queue"

  allowed_deletion = {
    'text': models.Text,
    'call': models.Call,
    'voicemail': models.Voicemail,
    'image': models.Image,
    'email': models.Email,
  }
  return

app structure
app (folder)
    - __init__.py
    - app.py
    - worker.py
    - worker.yaml
    - app.yaml

maybe worker should be in it's own folder? I wouldn't know how to hook that up in flask though...
The print statement in the taskqueue isn't even firing.
all I'm getting in the terminal is stuff that says

INFO     2018-01-28 22:11:21,432 module.py:788] default: "POST
  /deleting/image HTTP/1.1" 302 - WARNING  2018-01-28 22:11:21,432
  taskqueue_stub.py:1981] Task task25 failed to execute. This task will
  retry in 409.600 seconds

Finally, a working solution
@sign_in_
@app.route('/del/<entity_type>', methods=["GET", "POST"])
def DeleteStuff(entity_type):

  taskqueue.add(
    url    = "/execute_task",
    method = "POST",
    params = {
      "entity_type": entity_type,
    }
  ) # from 'from google.appengine.api import taskqueue'
  return Response("sending {} task to queue... Check logs".format(entity_type), mimetype='text/plain', status=200)#Response from 'from Flask import Response'

@sign_in_
@app.route('/execute_task', methods=["GET", "POST"])
def execute_task():
  allowed_deletion = {
    'a': models.SomemodelA,
    'b': models.SomemodelB,
    'c': models.SomemodelC,
    'd': models.SomemodelD,
  }
  entity_type = request.form.get("entity_type", '')
  bookmark = request.form.get('bookmark', '')

  cursor = None
  if bookmark:
    cursor = ndb.Cursor.from_websafe_string(bookmark)

  if entity_type:
    query = allowed_deletion[entity_type].query()
    entries, next_cursor, more = query.fetch_page(
      1000,
      keys_only=True,
      start_cursor=cursor)

    ndb.delete_multi(entries)

    bookmark = None
    if more:
      bookmark = next_cursor.to_websafe_string()

      taskqueue.add(
        url='/execute_task',
        params={'entity_type': entity_type, 'bookmark': bookmark}
      )

  return Response("did it. You'll never see this message", mimetype='text/plain', status=200)

notes
@sign_in_ can be on the task as well without throwing errors
Google app engine throws failure errors with variable urls for task-queues, in other words this will throw failure errors:
@app.route('/execute_task/<some_variable>', methods=["GET", "POST"])
def execute_task(some_variable):
    pass

both urls are listed in app.yaml, no need for worker.py and worker.yaml
- url: /del/*
  script: app.app
  login: admin
- url: /execute_task
  script: app.app
  login: admin

Many thanks to GAEfan for helping!! :)
Also Note: I was able to debug my way to the solution starting over from his code given in another post of mine: simple google app engine taskqueue tutoral? flask / python / GAE

A: Start with:
@app.route('/del/<entity_kind>', methods = ['GET', 'POST'])

Next, request.args is for a query string.  You want to handle the POST params:
request.form.get('bookmark', '')

Next, your @sign_in_ tag is causing a redirect for the task queue to a signin page.  (See the 302 referenced in the error log?).  Remove that.  Try adding this to your app.yaml:
- url: /del/.*
  script: whereisapplication.app
  login: admin

That will put it behind your Google login, but the task queue still can access.
Update to your update:
A print statement from a task is meaningless;  You will never see it.  Try:
import logging
logging.info("{0} to be deleted".format(entity_kind))

or:
@app.route('/deleting/<entity_kind>/',methods=['GET', 'POST'])
@app.route('/deleting/<entity_kind>',methods=['GET', 'POST'])
def DeletingStuff(entity_kind):
    if request.method == 'GET':
        print "here"

and see if you can access the url in the browser.  Note trailing slash in 1st route: to help diagnose the redirect issue.
You could also skip the POST method completely, and use a query string:
/deleting/text?cursor=387123481246123469
cursor = request.args.get("cursor", None)