text:
Q: Linking Excel to Access - Headers don't update when a column in excel is added/deleted I've done a simple link from excel to access. However, the file in excel changes frequently, and columns are added and removed occasionally. What I have noticed is that the headers in access don't change. If I delete a column in excel, the corresponding header in Access is still there. Same problem when I insert a column. A new column doesn't appear with a header - blank cells appear in an already existing column header, and all the values are shifted to the right.
How can I create through VBA or through Access's settings, a setup where the columns are dynamically changed whenever Excel changes?
Thanks for any assistance.
Images:
Example of Excel file pre-column B deletion
Example of Access file pre-column B deletion
Example of Excel file post-column B deletion
Example of Access file post-column B deletion
For some reason, even though I've deleted column B in excel, the "column B" header still appears in Access, with the column C values underneath.

A: When you originally link a table, Access stores its structure (its "meta data") in the TableDef object for the linked table. This structure is not updated unless you tell Access to do so.

*

*Manually:

External Data -> Linked Table Manager
Then tick the table(s) that need updating and click OK.

http://theitservice.co.uk/microsoft-access-basics-manage-linked-tables/

*

*Programmatically:

CurrentDb.TableDefs("myLinkedTable").RefreshLink

If your Excel file changes often enough, you could simply run this command from your startup code (AutoExec macro), so the TableDef is always up to date when you run your DB.
To automatically determine when this is actually needed, would be much more involved (and too broad for this question).

A: Wait a second, so you want to export data from Excel to Access but the field names will change in both places?  Here is a simple way to export data data, but I'm not sure how you will handle those changing field names.
Sub ADOFromExcelToAccess()
' exports data from the active worksheet to a table in an Access database
' this procedure must be edited before use
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
    ' connect to the Access database
    Set cn = New ADODB.Connection
    cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
        "Data Source=C:\FolderName\DataBaseName.mdb;"
    ' open a recordset
    Set rs = New ADODB.Recordset
    rs.Open "TableName", cn, adOpenKeyset, adLockOptimistic, adCmdTable
    ' all records in a table
    r = 3 ' the start row in the worksheet
    Do While Len(Range("A" & r).Formula) > 0
    ' repeat until first empty cell in column A
        With rs
            .AddNew ' create a new record
            ' add values to each field in the record
            .Fields("FieldName1") = Range("A" & r).Value
            .Fields("FieldName2") = Range("B" & r).Value
            .Fields("FieldNameN") = Range("C" & r).Value
            ' add more fields if necessary...
            .Update ' stores the new record
        End With
        r = r + 1 ' next row
    Loop
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub

Normally, you open an Access Table and then edit the table to change field names.  You can use SQL to create a table dynamically.
CREATE TABLE tblCustomers
    (CustomerID INTEGER NOT NULL,
    [Last Name] TEXT(50) NOT NULL,
    [First Name] TEXT(50) NOT NULL,
    Phone TEXT(10),
    Email TEXT(50))

You can use VBA to create a table too.
Sub CreateTableX1()
    Dim dbs As Database
    ' Modify this line to include the path to Northwind
    ' on your computer.
    Set dbs = OpenDatabase("Northwind.mdb")
    ' Create a table with two text fields.
    dbs.Execute "CREATE TABLE ThisTable " _
        & "(FirstName CHAR, LastName CHAR);"
    dbs.Close
End Sub

I'm not sure what your setup looks like, and I'm not sure I can suggest some kind of best practice here, but maybe with the ideas I posted here, you can come up with something.  Please do post back with your final solution when you get everything working.


text:
Q: c++ and opencv get and set pixel color to Mat I'm trying to set a new color value to some pixel into a cv::Mat image my code is below:
    Mat image = img;
    for(int y=0;y<img.rows;y++)
    {
        for(int x=0;x<img.cols;x++)
        {
        Vec3b color = image.at<Vec3b>(Point(x,y));
        if(color[0] > 150 && color[1] > 150 && color[2] > 150)
        {
            color[0] = 0;
            color[1] = 0;
            color[2] = 0;
            cout << "Pixel >200 :" << x << "," << y << endl;
        }
        else
        {
            color.val[0] = 255;
            color.val[1] = 255;
            color.val[2] = 255;
        }
    }
    imwrite("../images/imgopti"+to_string(i)+".tiff",image);

It seems to get the good pixel in output (with cout) however in the output image (with imwrite) the pixel concerned aren't modified. I have already tried using color.val[0].. I still can't figure out why the pixel colors in the output image dont change.
thanks

A: You did everything except copying the new pixel value back to the image.
This line takes a copy of the pixel into a local variable:
Vec3b color = image.at<Vec3b>(Point(x,y));

So, after changing color as you require, just set it back like this:
image.at<Vec3b>(Point(x,y)) = color;

So, in full, something like this:
Mat image = img;
for(int y=0;y<img.rows;y++)
{
    for(int x=0;x<img.cols;x++)
    {
        // get pixel
        Vec3b & color = image.at<Vec3b>(y,x);

        // ... do something to the color ....
        color[0] = 13;
        color[1] = 13;
        color[2] = 13;

        // set pixel
        //image.at<Vec3b>(Point(x,y)) = color;
        //if you copy value
    }
}

A: just use a reference:
Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

A: I would not use .at for performance reasons.
Define a struct:
//#pragma pack(push, 2) //not useful (see comments below)
struct BGR {
    uchar blue;
    uchar green;
    uchar red;  };

And then use it like this on your cv::Mat image:
BGR& bgr = image.ptr<BGR>(y)[x];

image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y

redpajama_set_name: RedPajamaStackExchange


text:
Q: lxml get the all the html of an xpath selected element So I have a given piece of HTML and I want to select a part of it using xpath and lxml
from lxml import etree

example_html = '''

abc

def

'''

htmlparser = etree.HTMLParser()
tree = etree.fromstring(example_html, htmlparser)

el = tree.xpath('//div')

el now is obviously this [<Element div at 0x7f61154c3f88>] what I want to do is a el[0].get_html() to get:

abc

def

Is this possible? And if not with lxml is there another library?

A: You can try with BeautifulSoup,
from bs4 import BeautifulSoup

example_html = '''

abc

def

'''

soup = BeautifulSoup(example_html)
print(soup.span)

abc

def


text:
Q: Google php api oauth 2.0 return uri I'm trying to retrieve the email address of clients for a social login to my sites DB.
Implementation of the google+ quick-start app for PHP also includes some javascript which breaks IE8 and 9.
So I figured I'd look at a purely PHP API, and downloaded this from git-hub:
https://github.com/google/google-api-php-client
I think I can feel my way using the example files to setting up the call for info I want, but have no idea how to get the result via the return uri. Infact when i run the examples, it logs in fine, and then calls the return uri of which when run doesn't contain any POST data, so I assume it uses some other method. I've google searched for a while now and no luck.
Does anyone have any examples, or point to any tutorials, or am I going down the wrong track?
Namaste

A: The uri redirects to it's self same php file.
Use the idtoken.php example to gain the email address for your DB.
For testing:
Add the full address to your Google Developers Dashboard / Credentials / REDIRECT URIS:
http://yoursite.com/google-api-php-client/examples/idtoken.php
Edit the idtoken.php and fill out your $client_id and $client_secret and $redirect_uri
The $redirect_uri being:
http://yoursite.com/google-api-php-client/examples/idtoken.php
You'll see the result directly on the page, work it from there.


text: Q: Como puedo cargar la lista de autores de un libro, en una ventana modal, esto en php usando laravel Tengo mi tabla Autores .. libro .. y una tabla que una las dos ..AutorLibro .. donde se almacena la lista de autores que tiene el libro .... Presento mi lista de libros sin problemas ..pero quiero que al momento de seleccionar el icono de autores .. me despliegue  la lista de los autores de ese libro .. Estoy desarrollando en Laravel .. en esta cuarentena me propuse aprender este lenguaje .. y sería de gran ayuda que me puedan dar una mano


text:
Q: Inequality involving an increasing sequence Let $(x_1,x_2,\dots,x_n)$ be an increasing sequence of numbers in $[0,1]$. I'd like to show that there exists a universal constant $ c > 0 $ such that
$$
\sum_{i=1}^{n-1}\sqrt{i(n-i)}(x_{i+1}-x_i) \leq c\sqrt{\sum_{i,i'}(x_i - x_{i'})^2}.
$$
It seems plausible since we have the identity
$$ \tag{1}
\sum_{i=1}^{n-1}i(n-i)(x_{i+1}-x_i) = \frac{1}{2}\sum_{i,i'}|x_i - x_{i'}|.
$$
Edit: Proof of (1). Using the fact the sequence of numbers is increasing, we have
$$
\sum_{i,i'}|x_i - x_{i'}| = 2\sum_{i'\leq i}(x_i - x_{i'}).
$$
Next, $ x_i - x_{i'} = \sum_{j = i'}^{i-1}(x_{j+1}-x_j) $. Hence,
\begin{align*}
\sum_{i,i'}|x_i - x_{i'}| & = 2\sum_{i'\leq i}\sum_{j = i'}^{i-1}(x_{j+1}-x_j) \\
& = 2\sum_{i'=1}^n \sum_{i=i'}^n\sum_{j = i'}^{i-1}(x_{j+1}-x_j) \\
& = 2\sum_{i'=1}^n \sum_{j=i'}^{n-1}\sum_{i = j+1}^{n}(x_{j+1}-x_j) \\
& = 2\sum_{j=1}^{n-1} \sum_{i'=1}^{j}\sum_{i = j+1}^{n}(x_{j+1}-x_j) \\
& = 2\sum_{j=1}^{n-1}j(n-j)(x_{j+1}-x_j).
\end{align*}

A: Here's a start.
The right side can be simplified.
Let
$s_1
=\sum_{j=1}^nx_{j}
$
and
$s_2
=\sum_{j=1}^nx_{j}^2
$,
$\begin{array}\\
r(n)
&=\sum_{i=1}^n\left(x_i - \frac{1}{n}\sum_{j=1}^nx_{j}\right)^2\\
&=\sum_{i=1}^n\left(x_i - \frac{1}{n}s_1\right)^2\\
&=\sum_{i=1}^n\left(x_i^2 - \frac{2x_i}{n}s_1+\frac1{n^2}s_1^2\right)\\
&=s_2 - \frac{2}{n}s_1^2+\frac1{n}s_1^2\\
&=s_2 - \frac{1}{n}s_1^2\\
\end{array}
$


text:
Q: Why am i getting the error "kernel/drivers/screen.c:7:22: error: invalid initializer char* string[] = message;" I'm trying to make a print function for an operating system. But i'm getting this error. What am i doing wrong
void vgaprint(char message, char color, int len) {
    char* video_memory = 0xb8000;
    char* firstcharcolor = 0xb8001;
    char string[] = message;
    char stringindex = string[0];
    *video_memory = stringindex;
    *firstcharcolor = color;
    int nextchar = 2;
    for(int i = 1; i < len; ++i)
    {
        stringindex = string[i];
        char* charpos = video_memory+nextchar;
        char* charcolor = charpos+1;
        *charpos = stringindex;
        *charcolor = color;
        nextchar = nextchar+2;
    }
}

A: Your code is wrong, overly complicated and there are poorly chosen variable names (e.g. stringindex which is not an index at all).

*

*you want to display several chars and not only one char, therefore you don't need char message but char *message, or better const char *message in the function signature,

*you don't need to copy the message prior to displaying it,

*you don't need a special treatment of the first character to display, you can do everything in the loop

*yoo don't need all those intermediate variables which makes your code hard to understand (and it also might be slower).

You probably want something like this:
void vgaprint(const char *message, char color, int len) {
    static char *video_memory = 0xb8000;   // start of video memory
    char *charpos = video_memory;          // charpos is current pointer to video memory

    for(int i = 0; i < len; ++i)
    {
        *charpos = message[i];             // set char
        *(charpos + 1) = color;            // set color
        charpos += 2;                      // goto next char
    }
}

or even simpler:
void vgaprint(const char *message, char color, int len) {
    char *charpos = 0xb8000;      // charpos points to start of video memory

    for(int i = 0; i < len; ++i)
    {
        *(charpos++) = message[i];  // set char
        *(charpos++) = color;       // set color
    }
}

Call it like for example this:
vgaprint("Hello world!", 0, 12);  // poor style because 12 is the hardcocded
                                  // length of the "Hello world!" string


text:
Q: How to get a confidence level with cpplint? How do I get a confidence value from cpplint?
--verbose = 0
doesn't do anything for me
Thanks!

A: I'm using cpplint 1.5.5. I believe the confidence value displays per default when using it:
Input:
cpplint memory_management.h
Ouput: Both have a confidence level of [5]
memory_management.h:0:  No copyright message found.  You should have a line: "Copyright [year] <Copyright Owner>"  [legal/copyright] [5]
memory_management.h:0:  No #ifndef header guard found, suggested CPP variable is: _HOME_MEMORY_MANAGEMENT_H_  [build/header_guard] [5]
Done processing memory_management.h
Total errors found: 2


text:
Q: Finding Webelement using ID with Curly Braces I am trying to find the table having ID using Selenium WebDriver but unable to do so, getting error as follows:
Unable to find element
Could someone please suggest, what am I doing wrong ?
<table id="{EB2E32F8-B236-42CD-9425-49BB4EA9DB01}-{A85091D3-69F3-419D-98EE-0FEBD1C3CC65}" class="ms-listviewtable" cellspacing="0" cellpadding="1" border="0"  onmouseover="EnsureSelectionHandler(event,this,11)" dir="none" o:webquerysourcehref="&XMLDATA=1&RowLimit=0&View=%7BA85091D3%2D69F3%2D419D%2D98EE%2D0FEBD1C3CC65%7D" xmlns:o="urn:schemas-microsoft-com:office:office" summary="CloneConfiguration" onmousedown="return OnTableMouseDown(event);" handledeleteinit="true">

I am trying to find the table using ID
driver.findElement(By.id("{EB2E32F8-B236-42CD-9425-49BB4EA9DB01}-{A85091D3-69F3-419D-98EE-0FEBD1C3CC65}"));

Any Idea ?

A: Seems like id is not static. you can try to get it by classname. i.e.
driver.findElement(By.className("ms-listviewtable"));

A: You can try xpath to locate the element using below code snippets:
Code snippet 1:
driver.findElement(By.xpath("//table[@class='ms-listviewtable']"));

Code snippet 2:
driver.findElement(By.xpath("//table[@summary='CloneConfiguration']"));

Code snippet 3:
driver.findElement(By.xpath("//table[@onmousedown='return OnTableMouseDown(event);']"));

Code snippet 4:
driver.findElement(By.xpath("//table[@onmouseover='EnsureSelectionHandler(event,this,11)']"));


text:
Q: django assign value to positiveIntegerField programmatically I am working on a little django application where the model contains a TextField and a PositiveIntegerField.
I need the PositiveInegerField to be populated with the number of words in the TextField.
This could be done via custom javascript code that count the number of words in the TextField's text area and put the value to the word count field text box before submitting the form but I do not want to play with custom javascript in the admin.
How to assign a value to a PositiveIntegerField programmatically?

A: This can be achieved using a pre_save Signal.
Create a signal-function like this:
def calculate_wordcount(sender, instance, **kwargs):
    # count the words...
    instance.word_count = # your count from line above

Then attach this function to your model. The preferred way since Django 1.7 is the application configuration (see doc).
You can attach your function in the AppConfig ready() - method
def ready(self):
    pre_save.connect(calculate_wordcount,
                     sender= ,# your model
                     weak=False,
                     dispatch_uid='models.your_model.wordcount')

I'll leave all necessary imports up to you, please comment, if you need further direction!

A: While in general I think save signals are a reasonable idea, in this particular case you can also override .save() yourself
class MyClass(models.Model):

    [stuff]

    def save(self, *args, **kwargs):
        self.wordcount = #something that calculates wordcount
        super(self.myClass, self).save(*args, **kwargs) #Call django's save!

(as a rule of thumb, I'll overwrite save() if I'm just doing things to one model, but use a signal if I'm using one model to affect another. The idea is to keep all things affecting a model near it in the code. But this gets into personal philosophy)
Also WARNING: No matter which version you use, the signal or overwriting save(), bulk_create and bulk_delete will not send a signal or call your specific save function. See the documentation here: https://docs.djangoproject.com/en/1.8/topics/db/models/#overriding-predefined-model-methods


text:
Q: rails 5 api app with json error response instead of html error response If I create an app in rails using the --api flag my error responses are in html rather than json.
How am I able to change the default error handler so that whenever an error is thrown in a controller action, I receive a json only response with the error and http status?
right now I am using the code below in every custom action
rescue => e
    response.status = 422
    render json: { error: e.message }

I'd rather not have to add this each time...
UPDATE:
I used the rescue_from method in the application controller
rescue_from Exception do |exception|
    render json: exception, status: 500
end

But I feel this is very wrong and the status will always be hard coded as 500

A: you can add format as json in routes so it will always accept request in json format like below
namespace :api, as: nil, defaults: { format: :json } do
     devise_for :users, controllers: {
        registrations: "api/v1/users/registrations",
        passwords: "api/v1/users/passwords"
      }

      resources :products, only: [:show,:index] do
        get "check_product_avaibility"
        get "filter", on: :collection
      end
end

For handling errors globally, you can add around_action in application controller file
around_action :handle_exceptions, if: proc { request.path.include?('/api') }

# Catch exception and return JSON-formatted error
  def handle_exceptions
    begin
      yield
    rescue ActiveRecord::RecordNotFound => e
      @status = 404
      @message = 'Record not found'
    rescue ActiveRecord::RecordInvalid => e
      render_unprocessable_entity_response(e.record) && return
    rescue ArgumentError => e
      @status = 400
    rescue StandardError => e
      @status = 500
    end
    json_response({ success: false, message: @message || e.class.to_s, errors: [{ detail: e.message }] }, @status) unless e.class == NilClass
  end

NOTE: render_unprocessable_entity_response and json_response are custom methods , you can add your own methods to render json response.

A: You can use the api_error_handler gem.
Include it in your bundler file:
gem "api_error_handler", "~> 0.2.0"

The in your application controller, invoke the library.
class ApplicationController < ActionController::API
  handle_api_errors(
    # Error handling options go here if you want to override any defaults.
  )

  # ...
end

Now if you have a controller like this:

class UsersController < ApplicationController
  def index
    raise 'SOMETHING WENT WRONG!!!'
  end
end

When you hit this endpoint you will see this response
{
  "error": {
    "title": "Internal Server Error",
    "detail": "SOMETHING WENT WRONG!!!"
  }
}

And the status code will be set to an appropriate status code based on the type of error you had.
See the gem's README for more info on how to configure the error response.


text:
Q: CollectionView doesn't work properly is iOS I have a view in Xaml and I am trying to use collection view as following
<CollectionView
x:Name="ColorCollectionView"
Margin="5"
HeightRequest="250"
WidthRequest="250"
ItemSizingStrategy="MeasureFirstItem"
ItemsSource="{Binding Categories}"
SelectedItem="{Binding SelectedCategory, Mode=OneWayToSource}"
SelectionChangedCommand="{Binding SelectedItemChangedCommand}"
SelectionChangedCommandParameter="{Binding Source={x:Reference ColorCollectionView}, Path=SelectedItem}"
SelectionMode="Single"
VerticalOptions="Center">
   <CollectionView.ItemsLayout>
     <GridItemsLayout Orientation="Horizontal" Span="2"
   </CollectionView.ItemsLayout>
   <CollectionView.ItemTemplate>
     <DataTemplate>
         <StackLayout Padding="20,0" Spacing="0">
                <Frame Padding="10"
                       BackgroundColor="White"
                       BorderColor="{Binding
                       BackgroundSelectedColor}"
                       CornerRadius="100"
                       HasShadow="False">
                 <Image HeightRequest="60" Source="{Binding Image}"WidthRequest="60"/>
                  </Frame>
                  <Label FontFamily="{x:Static constants:Fonts.Medium}" FontSize="12" HorizontalOptions="Center" Text="{Binding Name}" TextColor="Black" /
          </StackLayout>
     </DataTemplate>
  </CollectionView.ItemTemplate>
</CollectionView>

and it works fine in android but I got this exception in iOSd
Managed Stacktrace:
at <unknown> <0xffffffff>
at ObjCRuntime.Messaging:nint_objc_msgSend_nint <0x0011f>
at UIKit.UICollectionView:NumberOfItemsInSection <0x0017a>
at Xamarin.Forms.Platform.iOS.GridViewLayout:NeedsPartialColumnAdjustment <0x00282>  at

Xamarin.Forms.Platform.iOS.GridViewLayout:get_CollectionViewContentSize


text:
Q: Detecting the differences between two string vectors I've got a data_frame that looks like this.
df <- data_frame(name = c('john','bill','amy'),
           name.2 = c('johhn','ball','ammy'))
df
# A tibble: 3 x 2
   name name.2
  <chr>  <chr>
1  john  johhn
2  bill   ball
3   amy   ammy

I want to add a column that shows the difference between the two name(.2) columns. Like this:
df %>%
mutate(diff = c('h','a','m'))
# A tibble: 3 x 3
   name name.2  diff
  <chr>  <chr> <chr>
1  john  johhn     h
2  bill   ball     a
3   amy   ammy     m

I'd prefer to find a solution that uses elements of tidyverse and stringr if possible, but I'll take it like I get it.

A: Using base R we canndo something like:
diffc=diag(attr(adist(df$name,df$name.2, counts = TRUE), "trafos"))
transform(df,diff=regmatches(name.2,regexpr("[^M]",diffc)))
  name name.2 diff
1 john  johhn    h
2 bill   ball    a
3  amy   ammy    m

Breakdown:
compute approximate string distance between df[,1] and df[,2]
  d=adist(df$name,df$name.2, counts = TRUE)

obtain the diagonal of the transformation matrix:
   e= diag(attr(d, "trafos"))

Find the position of those that are either deleted,substituted or inserted ie not maintained:
    f=regexpr("[^M]",e)

extract the values of df[,2] at those specified positions:
     dat$diff==regmatches(name.2,f)

A: You could use the vecsets library:
library(vecsets)
df$diff <- mapply(vsetdiff, strsplit(df$name.2, split = ""),
                            strsplit(df$name, split = ""))

df
#  name name.2 diff
#1 john  johhn    h
#2 bill   ball    a
#3  amy   ammy    m

Note it looks like you just want the values in name.2 that are not in name which is why the first argument to mapply is the strsplit of name.2.


text:
Q: Перенос строк в Python3 тип bytes Во втором питоне можно написать строку вида
s ="\x31\xc9\xf7\xe1\x64\x8b\x41\x30\x8b\x40"\
"\x0c\x8b\x70\x14\xad\x96\xad\x8b\x58\x10"\

и будет работать. Как можно сделать аналогичную мульти-строчную строку для массива байт? Т.е. для
s = b'\x31\xc9\xf7\xe1\x64\x8b\x41\x30\x8b\x40'..

Если я пишу две строки подряд, оно не работает. Если задать через ''' тройные кавычки - в строку байт попадают символы переноса строки (что неприемлемо). Вариант только в одну строку, но это сильно растягивает редактор..

A: Правила такие же как и для строк:

*

*Используйте \, чтобы экранировать перенос строки в коде

*Или объявляете в круглых скобках

Пример:
b = b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82' \
    b' \xd0\xbc\xd0\xb8\xd1\x80!'
print(b.decode('utf-8'))
# привет мир!

b = (b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82'
     b' \xd0\xbc\xd0\xb8\xd1\x80!')
print(b.decode('utf-8'))
# привет мир!


text:
Q: Unable to access values from multiple html checkboxes I am trying to save the values from html checkboxes in a MySQL database table but I am not doing it right. I need your suggestions here.
This is my html
@foreach($sql as $sql)

    {{$sql->name}}

        <input type="hidden" name="resource[]" value="{{$sql->id}}">
        <input type="checkbox" name="resources[]" value="c">Create
        <input type="checkbox" name="resources[]" value="r">Read
        <input type="checkbox" name="resources[]" value="u">Update
        <input type="checkbox" name="resources[]" value="d">Delete

@endforeach

This is my controller where I am trying to save into a DB table
public function store(Request $request) {
    foreach ($request->resource as $resource) {
        # code...
        foreach ($request->resources as $resources) {
            $res[] = $resources;
            $options =  implode(',', $res); // Get selected options
            $resource = $resource; // Get value of the resource
        }
    }
}

This does not work as it only shows just one 'selected checkbox field'.
Please what am I doing wrong?

A: Looking at your HTML code, it appears you're going to be looping over possibly more than one SQL statement to make the checkboxes.  The server won't be able to tell these apart.  You should change your checkbox names to be more like:
<input type="checkbox" name="resources[{{$sql->id}}][]" value="c">Create
<input type="checkbox" name="resources[{{$sql->id}}][]" value="r">Read

Then your PHP code could look something like this:
foreach ($request->input('resources') as $id => $resources) {
    $options[$id] = implode(',', $resources);
}

Each SQL statement will be in the $options array keyed by the SQL id.  The array value will be the checked checkboxes values separated by a comma.
print_r($options)

[
    1 => "c,r,u,d",
    2 => "c,r,d"
]

A: If you are trying to save the selected values separated by comma, for ex: if user has selected by c and d, then you are saving in database as c,d ?. if so then you can get all selected values in single line.
public function store(Request $request) {
   // get all values separated by comma
   $selectedValues = implode(",", $request->input('resources'));

  // save values in database here

}

A: remember the your checkbox is an array !
for your understating better what sent to your controller just write
print_r($_POST);exit();

to see what arriving exactly after that write it in your framework  method like :
foreach($_POST['resources'] as $resources){
...
}


text:
Q: "Debug assertion failed! expression: _p != nullptr" error error imageI tried to make a program that does calculation with multiple arguments.
Everything works as I intended except for last one in the picture i attached.
Every time I try to put more than 2 numbers in the command line, the error occurs.
The example of input is this : program1.exe 12 + 13 - 2 + 1
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int a, b, rst;
    int i;
    char opr;

    if (argc > 100)
    {
        printf("Too many arguments!\n");
        return 0;
    }
    else if (argc <= 1)
    {
        printf("There are no arguments!\n");
        return 0;
    }

    a = atoi(argv[1]);
    rst = a;
    if (argc == 2)
    {
        a = atoi(argv[1]);
    }
    else if (argc % 2 != 0)
    {
        printf("Invalid fomula!\n");
        exit(0);
    }
    else
    {
        for (i = 1; 2*i <= argc; i++)
        {
            b = atoi(argv[2 * i]);
            opr = argv[2 * i - 1];
            switch (opr)
            {
            case '+':rst = a + b;
                break;
            case '-':rst = a - b;
                break;
            }

            rst = a;
        }
    }
    printf("%d", rst);

    return 0;
}

A: Running the code as is, with input set to: <program.exe> 2 + 5
a null pointer error occurs here:
for (i = 1; 2*i <= argc; i++)
        {
            b = atoi(argv[2 * i]);//Null pointer for i==2
            opr = argv[2 * i - 1];
            switch (opr)

because there is no argv[4].  This results in undefined behavior.
It is impossible to make corrections accurately without knowing what the program expects as input.  Because you do not specify, my best guess is the program attempts to read a set of arguments from the command line, eg:
argv[0]          argv[1]   argv[2]   argv[3]
<program>.exe    1         +         2

Then convert the values read into variables, and perform a math operation using two numerics and a math operator such as + or -.
Assuming this is the basic goal, the following example simplifies your existing code to perform these steps.  Note corrections to the argument input count test, and lower down, the looping indexes:
#include <stdio.h>
#include <stdlib.h>

/// test using:
// prog.exe 2 + 3 3 - 4 6 + 7

//results are:
//result 0: 5
//result 1: -1
//result 2: 13

typedef struct {
    int n1;
    char opr;
    int n2;
    int result;
} CALC;

int main(int argc, char *argv[])
{
    int i;
    // test for correct number of input arguments
    if((argc-1)%3 !=0)
    {
        printf("Wrong number of inputs.\n");
        return 0;
    }

    // read in, and assign variables (use array of struct)
    int max = (argc-1)/3;  //guaranteed viable only after determining multiples are correct from above
    //Get ALL input into array variables
    CALC calc[max];
    for (i=0;i<max;i++)
    {
        //convert inputs into usable variables
        calc[i].n1  = atoi(argv[i*3+1]);
        calc[i].opr = argv[i*3+2][0];
        calc[i].n2  = atoi(argv[i*3+3]);

        // perform calulations
        switch(calc[i].opr) {
            case '+':
                printf("result %d: %d\n", i, calc[i].n1 + calc[i].n2);
                break;
            case '-':
                printf("result %d: %d\n", i, calc[i].n1 - calc[i].n2);
                break;
        }
    }

    return 0;
}

Most error checking, and testing of function return values are left to you.


text:
Q: Clarification on what a "Transaction" is for HERE maps API I am currently evaluating several mapping API's and I have a question regarding HERE maps and what transactions and requests are.  According to the "Plans" page,
"For most of our services, a transaction is one server request. For map, satellite and traffic tiles, it's 15 requests.", but when I look at my usage page, it says I have generated 756 Map Tile Requests on 9/27.  Does this mean I have already generated 756 transactions or do I have to do the math and I've only generated 51 (rounding up) transactions?
Also, I only see "Map Tiles" metric on the usage graph.  I do not see where the initial transactions/requests (request to initiate the map) are counted.  Are these not counted and only map tile requests are?
Any clarification is greatly appreciated!  Thank you In advance!

A: As of today Aug 2018, google have free monthly 28k google map load.
average 1k per day.
User interactions with the map, such as panning, zooming, or switching map layers, do not generate additional map loads.
It is more than here map free 250k transaction per month.
1 map load could be hundreds of transaction.
google 28k map load >>  here map 250k transaction
Bing map has free yearly 125k bing map transaction,
Maximum 125,000 cumulative billable transactions per calendar year at no charge
Google map has the most free usage compare to bingmap here map.
Also google map saterlite imagery is way better than bing map.
Bing map imagery is way better than here map. (bing map and here map share some imagery in some kind of place or in some way.... you can tell by right bottom logo remark.)
Conclusion:
Your first choice should be goolge map,
google map give you most free usage + best imagery quality.
second is bing map, less quality image, less free usage.
last is here map. worst quality of image. less free usage.
1 Google map load means 1 user load 1 html page (with google map). As long as this user does not close this loaded map page, even this user zoom/pan millions times, send million request to interact with server, still count as 1 map load. So google give you the most free usage.


text:
Q: Should Perl scripts really have no extension? I just began reading O'Reilly's Learning Perl, 6th Edition and was surprised when I came across this excerpt.
#!/usr/bin/perl
print "Hello, world!\n";

Let's imagine that you've typed that into your text editor. (Don't
  worry yet about what the parts mean and how they work. You'll see
  about those in a moment.) You can generally save that program under
  any name you wish. Perl doesn't require any special kind of filename
  or extension, and it's better not to use an extension at all.
Why is it better to have no extension? Imagine that you've written a
  program to calculate bowling scores and you've told all of your
  friends that it's called bowling.plx. One day you decide to rewrite it
  in C. Do you still call it by the same name, implying that it's still
  written in Perl? Or do you tell everyone that it has a new name? (And
  don't call it bowling.c, please!) The answer is that it's none of
  their business what language it's written in, if they're merely using
  it. So it should have simply been called bowling in the first place.

This is the only source I've seen with this view, everything else I've read has supported the .pl extension. I'm no Perl programmer yet, and I wanted to know what the community's view on this was before I got into a habit.

A: The advice in the book is perfectly valid -- at least for UNIX-like systems. The execution of the script is controlled by the #! line, not by the extension part of the file name. Using a special extension for Perl scripts exposes information that should not be important to anyone running the script.
Windows is a different matter. Windows does not support the #! mechanism; instead, the method used to open a file depends on the extension. For example, the Windows shell might be configured so that double-clicking on a .pl file (or executing it from a prompt) will pass it as an argument to the Perl interpreter. Installing a Perl system will probably set that up for you automatically.
For Perl scripts intended to be portable, the .pl suffix required by Windows might "leak" onto UNIX-like systems. It's probably best to have a system-specific installation method that chooses an appropriate name for the script as it's installed.
On UNIX-like systems, a .pl extension is mostly harmless, and if you find it useful as a reminder of what language is used by a particular script (perhaps you have a collection of .pl, .py, .sh, and .rb scripts), then you can do that. But there are drawbacks to that approach, as described in the book: if you reimplement a script in a different language, you'll have to change the name and update anything that calls it.
(Perl modules need to have a .pm extension so that Perl can find them. For example, this:
use Foo::Bar;

will cause the interpreter to search for a file named Bar.pm in a a directory named Foo under one of the directories listed in the @INC array. But .pm files aren't meant to be executed directly.)

This is the only source I've seen with this view, everything else I've read has supported the .pl extension.

I find that surprising. Most of the advice I've seen says not to use the .pl extension for executable scripts.

A: Doesn't matter
#!/usr/bin/perl

tells the system what program to use to run the code.
if you changed that to
#!/usr/bin/bash

or
#!/usr/bin/python

you would use a different interpreter.
Having the extension is totally optional, and the point that the user doesn't need to know the language is 100% correct in most cases.
running add 2 3 and getting back 5 is all i care about (as a user).
The only time I add an extension to scripts is if I need the end user (some times my self) to know the language for some reason.
example.sh or example.pl to show to different ways to accomplish the same task.
All that said though, it is more common to not have an extension, but it's all taste.

A: The excerpt indeed makes a perfectly valid advice.
I would also add, that for a smaller system it is quite trivial to go over and rename a few files and/or strings here and there in case of changing your mind about the implementation.
On the other hand, a modern trend in developing largish systems implies having the main executable file without any extension while all the modules it depends on to still have the language-specific extension.
In fact, Python requires this by design, and usually the main Python script (the one without extension in the name) is just a few lines bootstrapping the whole app.

A: All the book is telling you is that on Unix, the file extension is nothing more than a convention.  In reality, many types of files fall in to this category.  Ruby files use the same convention so they don't need the .rb extension.  C compilers only need valid C code, so you can name them .watoozy if you wanted to.
While there is no technical restraint, there is the practical constraint of the principle of least surprise.  Basically, it would be very surprising to see ruby code in a .pl file, so people don't generally do that.
The one exception to the rule
In some server applications, the start up script is in an extension-less file to make it easier to start up the application as a service.  The file looks like just any other compiled command in that case.  As long as you have Perl installed, it will behave that way as well.

A: The excerpt, from the "O'Reilly's Learning Perl, 6th Edition" book is garbage.
Comparing C to perl is not equivalent, for starters C will be compile to a binary, that does not have an extension.
Perl will not be compile so some text editors will need the extension in order to identify the filetype.
As apart of best practice you should not hardcode full script filename with extension anywhere in your system, You should always use a symlink or an alias depends on your operating system.
In the future if you need to change the original file, you only need to change the symlink to point to your new location.


text:
Q: Failed to load resource: Uncaught TypeError: $(...).select2 is not a function So my MVC application keeps on throwing an Http internal server error with status code 500 when it renders my view.
The error it is throwing is a JQuery "Uncaught TypeError: $(...).select2 is not a function"
Uncaught TypeError: $(...).select2 is not a function
    at HTMLDocument.<anonymous> (AddUser:381)
    at fire (jquery-1.11.0.js:3100)
    at Object.fireWith [as resolveWith] (jquery-1.11.0.js:3212)
    at Function.ready (jquery-1.11.0.js:3424)
    at HTMLDocument.completed (jquery-1.11.0.js:3454)

Using debugger tools, it throws the error here:
$('selectUser').select2();

This is how I call my script:
@section Scripts {

    @Scripts.Render("~/bundles/forms")

    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />

Some SO posts suggest that this error is caused when you omit type="text/javascript"in your script tag or when you call the select2 function before the reference to the CDN service but as it clearly shows on my code all seems fine regarding the aforementioned.
According to this Uncaught TypeError: $(...).select2 is not a function, I am told to make sure if I have one version of JQuery loaded and all seems fine
Here is some additional code from my View that will help in reproducing the problem:

Controller:
    public ActionResult AddUser()
    {
        if (TempData["StatusMessage"] != null)
        {
            ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
        }
        else
        {
            ViewBag.StatusMessage = "";
        }
        AddUserToRolesViewModel vm = new AddUserToRolesViewModel();
        vm.Users = db.Users.ToList();
        return View(vm);
    }

EDIT:
Just to make sure that JQuery Core didn't load twice (once in Master and once in Content page) - I have included the markup for my master page.
_Layout.cshtml
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="shortcut icon" href="/favicon.ico" />
    @Styles.Render("~/Content/Template/css/style.css")

    @Scripts.Render("~/bundles/jquery")

    <title>@ViewBag.Title</title>

    @Html.Partial("_Header_top")

            @Html.Partial("_Menu_left")

                    @RenderBody()

                    @Html.Partial("_Footer")

@RenderSection("scripts", required: false)
@Scripts.Render("~/bundles/jqueryval")

Update II:
So I went ahead to my App_Start folder and navigated to my BundleConfig.cs and there I noticed something:
   public static void RegisterBundles(BundleCollection bundles)
   {
      bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js",
                         "~/Content/Template/js/plugins/jquery-ui-
                1.8.16.custom.min.js"
   }

According to this link: Usage of the ASP.NET MVC4 jquery/javascript bundles and I realized that file  "~/Content/Template/js/plugins/jquery-ui-1.8.16.custom.min.js" had alreasdy been added to this bundle and referenced in my content page (AddUser.cshtml) as:

At this point, I strongly believed this was going to fix the problem and so I removed this reference in my content page because I believed that that could be loading JQuery core twice but still nothing. The error still persists. What else can I do to try solve this?
Worthy mention that this error persists across all browsers (Chrome, IE & Firefox)


text:
Q: depth-first-search I implemented a depth-first-search in c# based on information I found on the net and old java books and I used the Node and NodeList and Graph from the msdn site.
How can one modify the DFS or BFS to check for particular weight?

A: If you can find a path from A-C and a path from C-D then you have your path A-C-D.

A: To implement a DFS, you need to use a stack implicit (recursively call the function itself) or explicit (use a stack object). For each state, you have a current node you are visiting. You will have to visited each neighbor of the current node, and also if you have visited the current node, then you can skip processing the current one.
That is pretty much the algorithm. What you need to do is translating that to code.


text:
Q: Dihedral Group question involving $D_{4n}$ Let $D_{4n}$ be the dihedral group of the order $4n$.

Prove that $D_{4n}/\langle T^n \rangle$ is isomorphic to $D_{2n}$.

We tried to configure an action on the diagonals of the $n$-gon and prove that there is a homomorphism from $D_{4n}$ to $D_{2n}$ and the kernel of the homomorphism is $\langle T^{2n} \rangle$ but we're stuck.

A: Let $D_{4n}=\langle a,b\rangle$ with $a^{2n}=1$ and $b^2=1$ and let $D_{2n}=\langle c,d\rangle$ with $c^{n}=1$ and $b^2=1$.
Define $\phi : D_{4n} \to D_{2n}$ by $\phi(a)=c^2$ and $\phi(b)=d$.
This is a homomorphism with kernel $\{a^ib^j \in D_{4n} : \phi(a^ib^j)=1\}$, and $$a^ib^j \in \ker\phi \iff 1=\phi(a^ib^j)=\phi(a)^i\phi(b)^j=c^{2i}d^j$$
If $j$ is odd, you have a rotation, $1$, equal to a reflection, $c^{2i}d^j$, so $j$ must be even.
Thus, $1=c^{2i}$, which implies that $n \mid 2i$, or $2i=nk$ for some integer $k$.
This means that any element of the kernel is an integer power of $a^n$, so  $\ker\phi = \langle a^n\rangle$.
EDIT: to show the homomorphism is well-defined, we need to check that $\phi(bab)=\phi(a^{-1})$, as  Jyrki Lahtonen pointed out.
$$\phi(bab)=\phi(b)\phi(a)\phi(b)=dc^2d=d(dc^{-2})=(c^2)^{-1}=(\phi(a))^{-1}=\phi(a^{-1})$$
ANOTHER EDIT: Note that $\phi$ is also surjective; now the first isomorphism theorem gives you the isomorphism.


text:
Q: Grails: WAR file deployment : Finding the port I have a Grails 2.3.6 app running as a WAR file in a server. Currently it's running in Tomcat 7.
In future we might have the app run in other servers too.
Now the problem i face is unique. In one of the service groovy files i need to get the port number for the running app.
For Tomcat the port number is set in server.xml and one potential way to get that will be to read from there.
But am looking for a more generic solution. So that even if the WAR file is deployed in other type of servers, i could get the port number.
Any suggestions are welcome!

A: The port (singular) isn't necessarily well-defined, e.g. you can have a Tomcat configured with several connectors listening on different ports, or serving both http and https.  In the context of a particular request you can talk about "the port" that that request was received on, but then what happens if your app is behind a reverse proxy or load balancer...
The only reliable approach is to manually specify the appropriate port number/URL/whatever in a configuration file (e.g. a grails.config.locations external).

A: You'll probably need to set the grails.serverURL configuration property to the base root of the application. In the development environment, this is typically something like
grails.serverURL = "https://localhost:8080/example"

and in the production environment
grails.serverURL = "https://example.org"

If you don't set this correctly, certain things won't work, e.g. generating absolute URLs. If this property is set correctly, then getting the port in a service is as simple as:
class MyService {

  def grailsApplication

  Integer getPort() {
    String basePath = grailsApplication.config.grails.serverURL
    // parse out the path (exercise for reader)
  }
}

A: If you need the port in the service you can get it from HttpServletRequest as follows:
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest()
def port = request.getServerPort()


text:
Q: How to send (POST) a .json file selected via an input file control on client side HTML form Hi I currently have a form to select a file for upload to an endpoint that requires the payload to be encoded as JSON.
Currently, I have the following form but it is multipart/form-data. I do not think it is possible to encode a form submission as application/json without resorting to something like ajax....
<form action = "/upload" method = "POST"
         enctype = "multipart/form-data">
         <input type = "file" name = "file" />
         <input type = "submit"/>
</form>

Is it possible using ajax to read the file selected in the form and send the contents as a json payload to the POST url endpoint? Can anyone help?

A: It's possible by using the FileReader API to parse the file to a string and send the string to the server as encoded JSON.
<form id="upload-form" action="/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="file" />
  <input type="submit"/>
</form>

First of we'll need a function that takes in a File and parses it to a string with the FileReader. The readFileAsText function returns a Promise which will resolve once the file has been parsed as text.
The result should be the content of the file as a string. That string is the JSON that we'll send to the server.
const readFileAsText = file => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.onload = ({ target }) => {
    resolve(target.result);
  };
  reader.readAsText(file);
});

Edit: nowadays you can perform this same process of reading the file as string with the Blob.text() method. A File instance has this method as well and is used like this:
/**
 * In this context the file variable is an instance of File.
 */

// In an async context
const text = await file.text();

// Outside an async context.
file.text().then(text => {
  // handle the text.
});

Next will be the AJAX part of sending your payload to the server. We do this by using the Fetch API. Here we specify the content type in the headers and create a POST request with a payload that contains JSON.
After the request is made it checks the response from the server and expects a JSON response from the server. Be sure to return a JSON response from the server side.
const sendJSON = async json => {
  const headers = {
    'Content-Type': 'application/json'
  };

  const response = await fetch('/upload', {
    headers,
    method: 'POST',
    body: json
  });

  if (!response.ok) {
    throw new Error(`Sending file caused an error - ${response.statusText}`);
  }

  return response.json();
};

Now we'll try to piece it together. In the following snippet we listen for the submit event on the form. When the form submits, stop the default behavior and overwrite what we need to do on submit.

*

*Get the values from the form with the FormData API. This enables us to extract the values from the form without having to select a specific element.

*Select the file from the formData object and pass it to the readFileAsText function (or use the text() method on the file). The result should be the JSON in the file.

*Now pass the json from the file into the sendJSON function and off it goes.
const form = document.querySelector('#upload-form');

form.addEventListener('submit', async event => {
  event.preventDefault();

  const formData = new FormData(event.target);
  const file = formData.get('file');

  // No file size means no file.
  if (file.size === 0) {
    return; // Do nothing.
  }

  try {
    const json = await readFileAsText(file);
    const response = await sendJSON(json);
    console.log(response);
  } catch(error) {
    console.log(error);
  }
});


text:
Q: Windows Embedded Compact 7: Developing?? Visual Studio 2010?? Templates? I would like to develop for Windows Embedded, but can't find any easy tutorials.
I have looked here and here
Does it just work on Silverlight, or something special?
There doesn't seem to be any templates for VS 201

A: start here
http://www.microsoft.com/windowsembedded/en-us/develop/windows-embedded-products-for-developers.aspx
http://blogs.msdn.com/b/usisvde/archive/2009/08/11/windows-embedded-development-center-updated-on-msdn.aspx
search MSDN, you will find what you are looking for

A: Here is a step by step tutorial by Samuel Phung:

The Windows Embedded Compact 7 (Compact 7) getting started series is
  created to provide simple and easy to follow information to help
  academic, hobbyist and commercial developers to learn and engage in
  Compact 7 development.

http://www.embedded101.com/Compact7
Also his book:
http://www.amazon.com/Professional-Windows-Embedded-Compact-7/dp/1118050460


text:
Q: Gantt schedule calendar one on top of the other I'm using a library to use a Gantt, but I'm not able to add it to Gantts on other lines, they're on top of each other. I would like to know if anyone knows how to solve this, as in the documentation below this is not very clear. Below is a screenshot of what is happening.
https://gantt-schedule-timeline-calendar.neuronet.io/

A: The overflow may be a result of the opacity of the items not being zero.
Using the same lib with the same problem I just set the opacity of the gantt row item to 1 and worked well for me:
.gantt-schedule-timeline-calendar__chart-timeline-items-row-item {
    opacity: 1 !important;
}


text:
Q: Field Size using SSIS I'm immporting a csv file with column headers:
 ID     ProductNumber     ProductName
 1234    A298384          Whatchamacallit
 3949    A293939          Whatchamacallit_Extra

I only need the ID and ProductNumber, when I map the file, I set ProductName to 'ignore'
When the package runs, it errors with the mesage that ProductName will truncate. I don't
understand why its erroring if I set the mapping to 'ignor'
I've also tried to import and have included ProductName, setting the field to Nvarchar (4000), it still errors. I've checked the file, there is no product name more than 54 characters.
I'm using SQL 2005.
Any insight would be helpful
Thanks.

A: I assume you have some kind of "Flat File Source" as the source connection for your data flow.  If so, when you click into it and view columns; is the Productname unchecked?

A: If you don't want to import the third column, go to advanced tab in your connection manager and delete the last row.
Another way would be to ignore the errors occuring in the error output tab in your flat file task (ingore truncation and failure), but i advice you to use what i wrote above.

A: Another way to fix this is to go into the Advanced section of the flat file connection manager and set the field length for the last field to something higher than the default 50 that is set for string values if you don't override.  Since you say that 54 is your longest data width for that last column use at least that value.
To find where to change this, open the connection manager editor by double clicking the flat file connection.  In the box on the left there are four choices "General", "Columns", "Advanced", and "Preview".  You will want to click Advanced, then highlight your "ProductName" column, then in the box on the right find "OutputColumnWidth" and set it to at least 54.


text:
Q: transform if else base logic to foreach failed I have this function
const applyColor = (value) => {

        let color
        //shallow to dark
        const colors = ['#B3E5FC', '#81D4FA' ,'#4FC3F7', '#29B6F6', '#03A9F4', '#039BE5', '#0288D1']

        if(value >= 100 && value < 199){
            return {index: 1, color: colors[0]}
        }else if(value >= 200 && value < 299){
            return {index: 2, color: colors[1]}
        }else if(value >= 300 && value < 399){
            return {index: 3, color: colors[2]}
        }else if(value >= 400 && value < 499){
            return {index: 4, color: colors[3]}
        }else if(value >= 500 && value < 599){
            return {index: 5, color: colors[4]}
        }else if(value >= 600 && value < 699){
            return {index: 6, color: colors[5]}
        }else if(value >= 700){
            return {index: 7, color: colors[6]}
        }
}

It's working when I do
{data.map(o =>

)}

But I tried to refactor it using loop.
let gap = 100
        const maximum = 700
        for(let i = 0; i < colors.length; i++) {

            if(value >= maximum) {
                color = {index: colors.length, color: colors[colors.length - 1]}
            }else if(value >= gap && value < gap + 99){
                color = {index: i, color: colors[i]}
            }
            gap += 100

            return color

        }

I got color of undefined error, I couldn't spot what's wrong. Any clue?

A: As others ahve mentioned your i now starts at 0 rather than 1.
I'm not overly familiar with javascript so excuse any syntax errors (please suggest edits if this is wrong).  Could this not be simplified to:
let color
const colors = ['#B3E5FC', '#81D4FA' ,'#4FC3F7', '#29B6F6', '#03A9F4', '#039BE5', '#0288D1']
var i = Math.floor(value/100)
if (i> colors.Length) {i= colors.Length}
if (i <1) {i= 1}
return {index: i, color: colors[i - 1]}

Basically value integer division by 100
If its over 7 make it 7 or < 1 make it 1
return the color

A: You need to take care for values less than the gap and you need a consistent way to calculate the index. You current code will start at 0 (the previous started at 1) but you last index will be colors.length which is 7 (while previously it would be 6), so now 6 is entirely skipped.
Use

const applyColor = (value) => {
  const colors = ['#B3E5FC', '#81D4FA', '#4FC3F7', '#29B6F6', '#03A9F4', '#039BE5', '#0288D1']
  const step = 100,
        index = Math.max(1,Math.min(Math.floor(value / step), colors.length)); // clamp index between 1 and color.length

  return {
    index: index ,
    color: colors[index-1]
  }
}

// testing
for(let i = 50; i<=850;i+=100){
  console.log(`applyColor(${i}) == `, applyColor(i));
}
/*for stackoverflow console*/
div.as-console-wrapper{max-height:100%}


text:
Q: table footer should be show at the bottom of each page during print in html I would like to show header and footer on page during print. So the I use code which is:

                Header

 Body data

Header and content are shown correctly. Footer also show is correct as at the end of each page. But Issue is when last page content only one line, footer show after that line instead of page bottom.

A: rename your index.html in index.php. Create a footer.php.
Insert your footer code in the footer.php
Go into your index.html and add the following code to the section where you want to add your footer:
<?php

include 'footer.php';

?>


text:
Q: Dynamic service injection w/ tree shaking I'm trying to create an ApiService that acts as a wrapper for a series of other services within my Angular 7 application. Currently, I am injecting my services within the constructor of parent ApiService:
import { Injectable, Inject } from '@angular/core';

import { StoreInfoService } from '@services/store-info/1.0/store-info.service';
import { MenuService } from '@services/menu/1.0/menu.service';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(
    @Inject(MenuService) public menu: MenuService,
    @Inject(StoreInfoService) public storeInfo: StoreInfoService,
  ) {}
}

This works fine, and allows me to call my API endpoints by doing this:
api.storeInfo.get('S9293')

But this does not allow me to take advantage of tree-shaking. Every service that I inject within ApiService will be included in my app, and I anticipate having a large number of services that will be wrapped within ApiService, and not every client will need to use every service.
Is there any way to wrap services within a parent wrapper service like this, while taking full advantage of tree-shaking?

A: I don't believe that you can have proper tree shaking while the service is injected into the API service (but I am open to being wrong).
I did some reading and found some pretty awesome information. Here is a link demonstrating how/why tree shaking works with the new providers.
It may sound a little weird, but an alternative idea you may be able to try is to use the file replacements with the CLI to set up the "dynamic" providers you actually provide the old way in a module, and where they are used to use the @Optional decorator on the service. Here is an example with the environment ts:
// abstract-service.ts
@Injectable()
export abstract class AbstractService1 {
  abstract myMethod(value: number): string;
}

// service.ts
@Injectable()
export class Service1 extends AbstractService1 {
  constructor() {
    super();
  }

  myMethod(value: number) {
    ..// do stuff
    return '';
  }
}

// env ts
export const environment = {
  ..
  specialProviders: [
    // no provider and having the AbstractService1 optional only has a reference to the method, no meat!
    { provide: AbstractService1, useClass: Service1 }
  ],
  ..

// angular json
"fileReplacements": [
  ..
  {
    "replace": "src/environments/environment.ts",
    "with": "src/environments/environment.<my-env>.ts"
  }
  ..
],

// shared service ts
..
constructor(
  @Optional() public Service1: AbstractService1,
  @Optional() public Service2: MyService2,
) {}
..

// module
providers: [
  ..
  ...environment.specialProviders,
  ..
],

(Edits)  Added demonstration of an abstract class for the "optional" service so the meat of the class is not included in the build if it's not provided. There will still be method references where the methods are used.


text:
Q: What are the current lossless audio containers and codecs for browser based audio recording in 2022? Audio recording is not my thing but I am on a project that needs to record audio from a web based app.  I am using the MediaRecorder API and some of the most recent information I see on containers and codecs is from 2018 on this web site: https://blog.addpipe.com/recording-audio-in-the-browser-using-pure-html5-and-minimal-javascript/
It lists:

*

*Firefox -- "audio/ogg; codecs=opus"

*Chrome -- "audio/webm; codecs=opus", "audio/webm; codecs=pcm"

*Opera -- "audio/webm; codecs=opus", "audio/webm; codecs=pcm"

It suggests a MediaRecorder replacement called "PolyFill" for Safari and Edge.
I have not tried PolyFill yet but I have tried the other mime type and codec strings above and they all seem to work.  Is this what is current in 2022?
Is there a canonical source for this info?


text:
Q: SIP Account in Android, what for? I just dont Understand
From the text of Android Website.
It said,

"Android provides an API that supports the Session Initiation Protocol
  (SIP). This lets you add SIP-based internet telephony features to your
  applications"

Which then I questioned myself, can we use this SIP API in
the Ad-Hoc connection of two Android devices connected each other?
What about,

"Each participant in the application's communication session must have
  a SIP account. There are many different SIP providers that offer SIP
  accounts."

an Account? What is that for? I assumed the account is
for handling the data translated from and to (client-server) communication.
But what about if I used for the Ad-Hoc TWo android communication, that Has no Internet connectivity? I mean, Can I used SIP Api for this? Or i should use something else...?

A: This mean Android now have build-in SIP stack API.
So if you want to build SIP applications like SIP softphone, then you can use Android API for SIP without using a thirtparty SIP stack.
Many applications build with SIP for example: PJSIP, CSipSimple, Linphone ...
After have SIP application (SIP client) you must have account to login and make call with another SIP clients.

A: SIP is an application layer protocol, means it works on transport layer, TCP/UDP/IP/SCTP...
You can make sip client using SIP API such as voip client and make a call with two android devices without server, just direct ip call, after set up ad-hoc network.
Thanks.


text:
Q: React render an image dynamically after a page reload (depends on state) I've a react component that I try to load image dynamically. The image is dependent on a state, that is loaded from the backend with useEffect. The initial state is empty.
When I change the state (using a drop list inside the form), the image is displayed correctly but when I reload the page, the image won't show up.
What I'm trying to do is to re-render / delay the render of the the component (or just  tag) after the fetch is complete. So I use loading as an indicator, and change it's value inside the useEffect after fetch returns.
But still when the page reloads the value of winner is undefined, and I get no image.
const Winner = () => {
  const [winner, setWinner] = useState({"id": "", "name": ""})
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch(`/api/v1/winner`, {
      method: 'GET',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
    })
    .then(res => res.json())
    .then(jsonData => {
      setWinner(jsonData)
      setLoading(false)
    })
    .catch((error) => {
      console.log(error)
    })
  }, [])

  return (
    (loading ?
Loading..
 :
      <Box className="bonus">
        <img src={`./static/${winner.name}.png`.toLowerCase()} width="40px" height="40px" />
        <FormControl>
        ...
        </FormControl>
      </Box>
  ))
}

Any suggestions / help is appreciated.

A: The initial state data and the data after fetch are different

{"id": "", "name": ""}

after fetch

{"status":"success","id":"17"}

so winner doesn't have a name prop,
Alternatively you can set the initial state to null
const [winner, setWinner] = useState(null)

....

if(loading) return "loading ..."
if(!winner) return null
if(winner) return <data.../>;


text:
Q: Quickbase Calendar Report - Colorize bar In the quickbase calendar report - highlight a blue bar for the length of time which is the .itme class.  What I am hoping to do is to change the .itme class to the exact same style except a different color.  Currently I am able to change my class as necessary but I can't upload a css color style to support my new class.  Please see my latest in the code.
If(IsNull([Task Name])," ", [Task Name]="Vacation", "Apple")

A: The class attribute expects a class name that is defined in  tags so passing the definition directly is going to cause some kind of error.  You could try appending a new set of style tags to the document with your class defined like:

I don't think that will work in this instance because the existing .itme class has color styling as part of it and I'm not sure how the browser resolves conflicting classes.  You probably don't want to replace .itme entirely because it has a lot of other styling information like size and borders.  Instead, I suggest you insert your styling directly in the style attribute because it will supersede the class where they conflict.  Try something like this:
If(IsNull([Task Name])," ", [Task Name]="Vacation", "Apple")

I'm not sure what "Apple" is doing for you here but I left it in none-the-less.


text:
Q: No internet access on Arch Linux Today I installed Arch Linux on my laptop. Everything seems to work okay, except Internet access.
I have tons of tutorials, nothing works. When I type ping google.com it returns

unknown host google.com.

My whole rc.conf file:
INTERFACE=eth0

A: Take a look at the Beginners Guide on How to establish a network connection in the arch wiki
Arch Wiki Beginners Guide.
Arch uses systemd, while initscripts as rc.conf are deprecated and no longer used.

A: As already mentioned, rc.conf is deprecated. I think your issue is around incorrectly setting up eth0 as your network interface. You probably want to check out this thread in addition to the Beginners Guide mentioned.
https://bbs.archlinux.org/viewtopic.php?id=156283
Specifically check how your interface is mapped when you run 'ip link'. It may not be eth0!


text:
Q: SagePay form integration BillingSurname is too long I have managed to get my server talking to the SagePAY server using PHP with Form integration.
My name-value-pairs are constructed, strung together, encrypted and are being posted to SagePAY where they are being accepted.
However, SagePAY server response is stating that the BillingSurname is too long (error 3108).  BillingSurname is built and delivered in exactly the same way as BillingForenames and did have the same data in it. I have tried just sending "Smith" through instead and it is still 'too long'.  Needless to say it is less than the 20 chars specified.
Any ideas anyone?
Edit: Adding the code that encrypts - although I don't think that is the problem - been through that already as the server is now reading TXCode, Currency, Amount etc until we reach the Billing Address.
<?php
function pkcs5_pad($text, $blocksize)
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

function encryptFieldData($input)
{
    $key = "SagePAY encryption key here";
    $iv = $key;

    $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_CBC, "");
    if (mcrypt_generic_init($cipher, $key, $iv) != -1)
    {
        $cipherText = mcrypt_generic($cipher,$input );
        mcrypt_generic_deinit($cipher);

        $enc = bin2hex($cipherText);
    }
    return $enc;
}
$str = "VendorTxCode=13362020&Currency=GBP&Description=a-url.co.uk Personalised stationery&SuccessURL=http://a-url.co.uk/success/&FailureURL=http://a-url.co.uk/problem/&VendorEmail=email@a-url.co.uk&SendEmail=1&Amount=7.95&BillingFirstnames=Albert&BillingSurname=Smith&BillingEmail=email@a-url.co.uk&BillingAddress1=4drds&BillingAddress2=deldSurrey&BillingCity=ddcd&BillingPostCode=XX7 1XX&BillingCountry=GB&BillingPhone=01342 123456&DeliveryFirstnames=Albert&DeliverySurname=Smith&DeliveryAddress1=4drds&DeliveryAddress2=deldSurrey&DeliveryCity=ddcd&DeliveryPostCode=AB7 6RF&DeliveryCountry=GB"
$datapadded = pkcs5_pad($str,16);
$cryptpadded = "@" . encryptFieldData($datapadded);
?>

A: Solution by OP.
I had inadvertently added an extra field that was not in the specification - BillingEmail. That caused the SagePAY error on BillingSurname.


text:
Q: Apache return 429 only to bots, for specific urls i have a Magento website working with Apache2 and every day i get bots crawling urls that i do not want to and i would like to return 429 for specific urls.
i have tried this in my htaccess
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (Yahoo!\Slurp|semrushbot) [NC]
Redirect 429 /shop/ricerca/
</ifModule>

where my bots are:

yahoo slurp googlebot yandex semrush etc

and path to protect are:
/path/toprotect/

/path/to/protect2/

tailing access logs seems my snippet is not working.
any one can help me?
eventually if too messy, i'll just use nginx as reverse proxy and filter bots from there where i have more experience

A: There are several errors:

*

*You are mixing mod_rewrite directives (RewriteCond) with mod_alias directives (Redirect). You should a have RewriteRule, instead.

*You can't use HTTP 429 Too Many Requests with a redirect.

Any valid HTTP response status code may be specified, using the
syntax [R=305], with a 302 status code being used by default if none
is specified. The status code specified need not necessarily be a
redirect (3xx) status code. However, if a status code is outside the
redirect range (300-399) then the substitution string is dropped
entirely, and rewriting is stopped as if the L were used.

*

*The escape character \ in Yahoo!\ Slurp is for escaping the space you are missing.

Result after these corrections, redirecting everything to /shop/ricerca/:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_USER_AGENT} (Yahoo!\ Slurp|semrushbot) [NC]
    RewriteRule "(.*)" "/shop/ricerca/" [L,R=302]
</IfModule>

Or, if you are not trying to redirect to /shop/ricerca/ but protect it with 429 Too Many Requests:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_USER_AGENT} (Yahoo!\ Slurp|semrushbot) [NC]
    RewriteRule "^/shop/ricerca/(.+)" - [R=429]
</IfModule>


text:
Q: nerdctl compose error: FATA[0000] error while creating container portainer: exit status 1 I am running lima on a M1 mac with OSX Ventura. I have a docker compose file that works perfectly when I try to run it with docker cli.
docker-compose:
version: "3.8"
services:
  portainer:
    container_name: portainer
    image: portainer/portainer-ce:latest
    volumes:
      - ~/docker/portainer/data:/data
      - /var/run/docker.sock:/var/run/docker.sock
    restart: always
    ports:
      - "9443:9443"

When I run the below command
nerdctl compose --env-file ../macbook.env up --debug-full
The command fails with the following error.

FATA[0000] error while creating container portainer: exit status 1

Needless to say this is not enough information for me to diagnose the issue. Is there a way to find out exactly whats failing? Basically how do I get this simple docker-compose file to run so I can start adding more services to it.

A: mount a local volume in to the container at the location wher the portainer application logs are output.
This will output logs to a file in the directory on your local machine that you can then consult for further information
eg. (probably not correct) /tmp/portainerLogs:/var/logs/portainer
If you can run the container without any customising, you can ssh into the container with docker exec -it [container_id] bash which will effectively log you into the container with a bash shell prompt. -i - interactive, -t teletypewriter (connect the keyboard). Once in locate the logs and mount the directory as needed.
I'd probably be querying the portainer image with something like docker image inspect [imageId] --no-trunc - this should give you info that was used to create the docker container (similar to the directives for the Dockerfile used to create the image). Perhaps the log dir is there?
Also on my M1 MBP I see there may be a way to bypass this entirely and look on your local machine since reportedly container log output goes to:
/var/lib/docker/containers/<container_id>/<container_id>-json.log
However on my M1 MBP I see a similar directory at:
/var/containers/ but mine is empty since I've not really used it much for dev.


text:
Q: Can we get numbered rankings on the leaderboard Can we have all the sites (auto) ranked on the Winterbash Leaderboard page?

It would make it easier to know the exact position of a site
Any thoughts/opinions on this?

A: You can add the numbers using CSS counters.
We can target all the list items except the first by using :not(:first-child), then simply set a counter and use it as the content of a pseudo-element.
The important parts are just the counter-* rules, the rest is mostly positioning and styling.
body {
    counter-reset: rank;
}

.lb-row:not(:first-child):before {
    counter-increment: rank; /* Increment the counter by 1 */
    content: counter(rank);

    /* layout */
    display: block;
    position: absolute;
    left: -70px;
    height: 70px;
    line-height: 70px;
    width: 30px;

    /* style */
    font-size: 1.5em;
    text-align: center;
    font-weight: bold;
}

.lb-row {
    position: relative /* we need this to position the number */
}

Adding that as a user style gives us...

A: In case such feature won't be added, you can execute the following JS code to get the ranks:
$(".lb-row").each(function() {
    var row = $(this);
    var index = row.index();
    if (index > 0) {
        var iconCell = row.find(".lb-icon");
        if (iconCell.length == 1) {
            var rankDiv = $("

");
            rankDiv.css({
                "position": "absolute",
                "width": "70px",
                "height": "70px",
                "line-height": "70px",
                "text-align": "center",
                "vertical-align": "middle",
                "font-size": "25px",
                "color": "#000"
            });
            rankDiv.text("#" + index);
            iconCell.prepend(rankDiv);
        }
    }
});

This can be executed via any modern browser's developer console. It will show the rank of each site in the middle of its icon. Not ideal, but should be clear enough, and took the couple of minutes I had to spare. :)


text:
Q: Multiple thumbnails and one gallery I'm looking for solution for a gallery on a WP page that shows multiple thumbnails of images in that gallery, but not all thumbnails in gallery (like default Galleries in WP works).
I want (i.e.)certain 3 thumbnail images to show up on page, which (each one of them) leads to the same gallery with more than 3 images (i.e. 7 images).
Additionally (it would be uber-fantastic), if it would throw in description how many images there are in the gallery (some WP function, you know?).
It should work like from the shortcode with images with such (fabricated) property : "show-thumbnails"
[gallery ids="152,153,103,104,102,64,60" show-thumbnails="152,153,103"]

Is it possible in WordPress? Perhaps you know some plugin that has such options ?
Or know how to pass some additional params to WP ? Thanks!

A: You can add this code in WP page. For any plugin shortcode to add in WP page:
<?php do_shortcode('[plugin shortcode]'); ?>

like:
<?php echo do_shortcode('[gallery ids="152,153,103,104,102,64,60" show-thumbnails="152,153,103"]'); ?>

A: It is possible but it needs some developing effort. First of all it is important to know that WordPress default »galleries« are not discrete resources you can address with an separate URL. They are just shortcodes defined on a single posts context.
So what you need to do is to define a URL the thumbnails point to which, of cause, defers from the posts thumbnail. One (not the only) way is, to add a rewrite endpoint to your permalink. Assuming your post permalink is your-domain.tld/2014/a-wordpress-post/ the URL the thumbnails could look like your-domain.tld/2014/a-wordpress-post/thumb/123/. The number on the last part represents the ID of each thumbnail. Endpoints are normally added on init:
add_action( 'init', 'wpse_131753_add_thumb_endpoint' );
function wpse_131753_add_thumb_endpoint() {

    add_rewrite_endpoint( 'thumb', EP_PERMALINK | EP_PAGES );
}

Now, you need to change the way, WordPress renders the gallery shortcode. There's a filter for that called post_gallery. It bypasses the output of the default function called gallery_shortcode() which is defined in wp-includes/media.php.
Let's view some code for this:
add_filter( 'post_gallery', 'wpse_131753_gallery_view', 10, 2 );
function wpse_131753_gallery_view( $output, $shortcode_attributes ) {

    $default_attributes = array(
        'show-thumbnails' => '',
        'order'           => 'ASC',
        'orderby'         => 'menu_order ID',
        'id'              => $post ? $post->ID : 0,
        'itemtag'         => 'dl',
        'icontag'         => 'dt',
        'captiontag'      => 'dd',
        'columns'         => 3,
        'size'            => 'thumbnail',
        'include'         => '',
        'exclude'         => '',
        'link'            => ''
    );
    $atts = shortcode_atts( $default_attributes, $shortcode_attributes, 'gallery' );
    $current_thumb_ID = get_query_var( 'thumb' );
    // build your gallery markup here using
    // $atts[ 'show-thumbnails' ] and
    // $current_thumb_ID
    // to defer between varous outputs

    if ( $current_thumb_ID ) {
        // here you may want to show the compltete gallery
    } else {
        // and here you may want to show the thumbs in
        // $atts[ 'show-thumbnails' ]

        // to link to the detailed view use this:
        $permalink = untrailingslashit( get_permalink( get_the_ID() ) );
        $thumb_link = $permalink . '/thumb/' . $thumb_ID;
        // where $thumb_ID is one of the IDs in your atts.
    }
    return $output;
}

The function sould lookup for the default used gallery shortcode attributes and build the html on your belief whether it should show only the three thumbnails when no endpoint is given or a specific thumbnail was clicked (the endpoint contains the ID of the clicked thumbnail). The enpoint's value is stored in the query variable: get_query_var( 'thumb' ).


text:
Q: Switch focus between opened dialogs is there any way to programmatically switch focus between shown dialogs?
To resume...
I need method dialog.requestFocus(), but there is no some like that...
Thanks...

A: Well this thing that you want to do it is not user friendly you shouldnt do things like this. The dialogs are modal so you should pop it out prompting the user to do some action chose some decision and so on after that the dialog should vanish :)...
Things like requestFocus() it is stupid to be present in the component like dialog on android, cause when the dialog is visible it is logical that it is focused....
BUT,for your pleasure you can do the flowing:
when you decide that you should change the focus hide the dialog A like dialogA.dismiss() and dialogB.show();, if you decide to back to A than dialogA.show();, dialogB.dismiss();...
this is simple hack but if you code syntactically correct it will work


text:
Q: Расфасовка по колонкам в CSV Я изучаю Scrapy и делаю первые шаги и не могу понять как можно сделать расфасовку по колонкам при экспорте спарсенных данных в CSV. Например, я делаю парсинг интернет-магазина и там у каждого товара огромное количество характеристик (атрибутов), мне нужно чтобы каждый этот атрибут был в отдельном столбце в CSV файле. Я думаю что нужно парсить все характеристики с HTML тегами в одно поле и потом указав в каком теге находится название атрибута, а в каком значение атрибута дать команду Python раскидать все это по столбцам, название атрибута - это название столбца. Получится каждая характеристика (атрибут) товара в отдельном столбце.
Как это сделать?

A: В помощь Вам XPath - String text() — возвращает набор текстовых узлов.


text:
Q: Codeigniter 3 enviar arquivo com extensão PFX Preciso fazer Upload de um arquivo com a extensão .pfx (certificado digital).
Estou usando a library Upload do CodeIgniter da seguinte forma:
Estou colocando a extensão allowed_types mas não envia. Retorna: O tipo de arquivo que você está tentando fazer upload não é permitido.
$config['upload_path'] = $pasta;
$config['allowed_types'] = 'pfx';
$config['max_size'] = 100000;
$config['encrypt_name'] = TRUE;

$this - > load - > library('upload');
$this - > upload - > initialize($config);
if ($this - > upload - > do_upload('userfile')) {
    echo json_encode(array('image1' = > $this - > upload - > data('file_name'), 'file_ext' = > str_replace(".", "", $this - > upload - > data('file_ext')), 'error' = > 0, 'mensage' = > 'Arquivo enviado com sucesso.'));
} else {
    echo json_encode(array('mensage' = > $this - > upload - > display_errors(), 'error' = > 1));
}

A: Esse erro ocorre porque o framework não está achando essa extensão na lista de mime types, ou seja, ele não sabe o que é nem como tratar um arquivo .pfx. Pra resolver, abra config/mimes.php da sua aplicação e acrescente a seguinte linha ao final do array():
'pfx' => array('application/octet-stream'),

Fonte: Preferences; get_mimes(); Mime type do pfx.

A: Além de atualiza seus arquivos MIMES, utilize também o tipo de header application/x-pkcs12,
Ou seja:
'pfx'   =>  array('application/octet-stream', 'application/x-pkcs12')


text:
Q: Is it possible to create platform specific views? In UWP, device specific views can be created by placing those views into their respective folders or appending the relevant device name to the file name.
I don't see any information on doing the equivalent with MAUI as regards platform specific views only platform specific code.
Is this a thing ?
The closest I can get is using preprocessor directives and giving the files unique names. This means there are still multiple code behind files unfortunately.
So -
#if ANDROID
      await Navigation.PushAsync(new Page1Windows());

#elif WINDOWS
      await Navigation.PushAsync(new Page1Android());

#endif

A: It's a thing.
The default MAUI projects provide a platform specific folder you can put platform specific code in.
If you want something more complicated, like your platform-named folders or files, you can edit your csproj to include or exclude files by name & platform.
There are examples of both file and folder-based targeting in the Configure multi-targeting docs:
Here's the combined view from Combine filename and folder multi-targeting that excludes files and folders that include platform names that don't match the current target.
<ItemGroup Condition="$(TargetFramework.StartsWith('net6.0-android')) != true">
   <Compile Remove="**\**\*.Android.cs" />   <None Include="**\**\*.Android.cs" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" />
   <Compile Remove="**\Android\**\*.cs" />   <None Include="**\Android\**\*.cs" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" />
</ItemGroup>

<ItemGroup Condition="$(TargetFramework.StartsWith('net6.0-ios')) != true AND $(TargetFramework.StartsWith('net6.0-maccatalyst')) != true">
   <Compile Remove="**\**\*.iOS.cs" />   <None Include="**\**\*.iOS.cs" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" />
   <Compile Remove="**\iOS\**\*.cs" />   <None Include="**\iOS\**\*.cs" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" />
</ItemGroup>

<ItemGroup Condition="$(TargetFramework.Contains('-windows')) != true ">
    <Compile Remove="**\*.Windows.cs" />   <None Include="**\*.Windows.cs" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" />
    <Compile Remove="**\Windows\**\*.cs" />   <None Include="**\Windows\**\*.cs" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" />
</ItemGroup>


text:
Q: JSLint: Use a named parameter So I'm running JSLint on the lastest version of jQuery available at bit.ly/jqsource. I've made the tests as lax as possible, but I still get errors. One of them is "Use a named parameter" on line 327:
target = arguments[0] || {},
What does it mean? Even this blog post doens't provide information.

A: It means that the code is accessing the parameter using the arguments collection instead of a parameter specified in the function signature:
You can reproduce the error message with this code:
function x(a) {
    var b = arguments[0];
}

Using the named parameter gives the same result without the lint error:
function x(a) {
    var b = a;
}

A: I'll assume it actually says "Use a named parameter" instead of "variable".
If so, there can be a performance hit in some browsers when you reference the arguments object. I'd guess that's what it's complaining about.
Some browsers will optimize away the creation of the arguments object if it is never referenced.


text:
Q: What is the point of Rengar vs Kha'zix anymore? There is a mini-quest in LoL that when there's a Kha'zix and Rengar on opposite teams, a duel between them is initiated somewhere along in the game. The question is, what's the point of it anymore if Rengar doesn't lose stacks anymore even if he dies.

A: The point to it doesnt change, its still the same as before - Just a little extra fun and lore interaction.
The only difference is that with rengar not being able to lose stacks, The Hunt is more likely to happen now.
The Hunt occurs when Rengar has atleast 10 stacks, and Khazix has used 3 evolution points.
Whoever kills the other first gains an additional bonus.
Rengar gains "The Head of Khazix", which is a fully stacked necklace. You can skip from 10 to 20 stacks if thats how many stacks he has.
As of patch 4.14 Rengar also gains additional vision in brushes with the head of Khazix.
(Thanks Caffeinated Cake)
Khazix gains an additional evolution point if he wins.


text:
Q: Problems with callouts Mock and tests We have a problem in our organization and I was hoping for some advice from you on how to best tackle this.
We have a handler class that makes a callout to a Master Data Management system for account validation. That handler class is perfectly covered by it's own tests that utilize Mocking of the outbound call.
Now our business process dictates that we need to do a check every time an Account is created or updated, so we invoke that callout from an Account After trigger.
Now we run into a problem as any testmethod we have in the system that tries to construct an Account for unit testing purposes triggers the outbound callout and fails with a Fatal error: testmethods cannot invoke callouts.
Can somebody give us a hint on how to best properly deal with this?
Best regards,
Ivar

A: In your trigger handler class AccountTriggerHandler create static field
@testVisible
private static Boolean skipCallout = Test.isRunningTest();

and then before making a callout check:
if(!AccountTriggerHandler.skipCallout){
    // do callout
}


text:
Q: Warning: spl_object_hash() expects parameter 1 to be object, with Message i am getting the error when i try to flush the data,

Warning: spl_object_hash() expects parameter 1 to be object

along with this message

Found entity of type  on association Subject\Entity\Subject#user, but expecting Subject\Entity\User

now here is the action i am trying to implement
 public function addAction() {
    $form = new SubjectForm();
    $form->get('submit')->setAttribute('label', 'Add');
    $request = $this->getRequest();
    if (!$this->sessionVar) {
        $this->sessionVar = new SessionContainer('zftutorial');
        $userid = $this->sessionVar->offsetGet('userid');

        $form->get('user')->setAttribute('value', $userid);
    }
    $form->setData($request->getPost());

    if ($request->isPost()) {
        $subject = new Subject();
        $form->setInputFilter($subject->getInputFilter());
        if ($form->isValid()) {
            $subject->populate($form->getData());
            $this->getEntityManager()->persist($subject);
            $this->getEntityManager()->flush();
            return $this->redirect()->toRoute('subject');
        }
    }
    return array('form' => $form);
}

and this is my subject.php

namespace Subject\Entity;

use Doctrine\ORM\Mapping as ORM;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

/**
 *

 * @ORM\Entity

 * @ORM\Table(name="subject")

 * @property string $subjectname

 * @property int $user_id

 * @property int $id

 */
class Subject implements InputFilterAwareInterface {

protected $inputFilter;
/**

 * @ORM\Id

 * @ORM\Column(type="integer");

 * @ORM\GeneratedValue(strategy="AUTO")

 */
protected $id;
/**

 * @ORM\Column(type="string")

 */
protected $subjectname;
/**
 * @ORM\ManyToOne(targetEntity="Subject\Entity\User", inversedBy="subjects")
 * @var User|null
 */
private $user;

/** @return User|null */
public function getUser() {
    return $this->user;
}

/** @param User $user */
public function setUser(User $user) {
    if ($user === null || $user instanceof User) {
        $this->user = $user;
    } else {
        throw new InvalidArgumentException('$user must be instance of Entity\User or null!');
    }
}

/**

 * Magic getter to expose protected properties.

 *

 * @param string $property

 * @return mixed

 */
public function __get($property) {

    return $this->$property;
}

/**

 * Magic setter to save protected properties.

 *

 * @param string $property

 * @param mixed $value

 */
public function __set($property, $value) {

    $this->$property = $value;
}

/**

 * Convert the object to an array.

 *

 * @return array

 */
public function getArrayCopy() {

    return get_object_vars($this);
}

/**

 * Populate from an array.

 *

 * @param array $data

 */
public function populate($data = array()) {

    $this->id = $data['id'];

    $this->subjectname = $data['subjectname'];

    $this->user = $data['user_id'];
}

public function setInputFilter(InputFilterInterface $inputFilter) {

    throw new \Exception("Not used");
}

public function getInputFilter() {

    if (!$this->inputFilter) {
        $inputFilter = new InputFilter();
        $factory = new InputFactory();
        $inputFilter->add($factory->createInput(array(
                    'name' => 'id',

                    'filters' => array(
                        array('name' => 'Int'),
                    ),
                )));
        $inputFilter->add($factory->createInput(array(
                    'name' => 'subjectname',
                    'required' => true,
                    'filters' => array(
                        array('name' => 'StripTags'),
                        array('name' => 'StringTrim'),
                    ),
                    'validators' => array(
                        array(
                            'name' => 'StringLength',
                            'options' => array(
                                'encoding' => 'UTF-8',
                                'min' => 1,
                                'max' => 100,
                            ),
                        ),
                    ),
                )));

        $inputFilter->add($factory->createInput(array(
                    'name' => 'user_id',
                    'required' => true,
                    'filters' => array(
                        array('name' => 'Int'),
                    ),
                )));

        $this->inputFilter = $inputFilter;
    }

    return $this->inputFilter;
}

}

i am trying to implement oneToMany but i dont know what is wrong here.

A: Ok found answer
what i was doing was wrong i was doing this
if ($request->isPost()) {
    $subject = new Subject();
    $form->setInputFilter($subject->getInputFilter());
    if ($form->isValid()) {
        $subject->populate($form->getData());
        $this->getEntityManager()->persist($subject);
        $this->getEntityManager()->flush();
        return $this->redirect()->toRoute('subject');
    }
}

Instead i had to first find the Relevant entity like this
 if ($request->isPost()) {
        $subject = new Subject();

//following is the line  i was looking for
        $user = $this->getEntityManager()->getRepository('Subject\Entity\User')->find(array('id'=>$userid));
        $form->setInputFilter($subject->getInputFilter());
        if ($form->isValid()) {
            //$user->add
            //$subject->setUser($user);
            $subject->populate($form->getData());
            $subject->setUser($user);
            $this->getEntityManager()->persist($subject);
            $this->getEntityManager()->flush();
            return $this->redirect()->toRoute('subject');
        }
    }


text:
Q: JScroll: Change nextHref after ajax changed tab and URI JScroll can't see when the javascript changed window history with pushState.
I added JScroll for posts on index page. The default URL is localhost for example. And when there is no path after, the default posts will be loaded and jscroll will work as it should have.
But I have tabs on index page (new, top, hot), which change order of posts. So when I click on a tab, it dynamically changes URL with window.history.pushState, and sends request with new filter for showing posts.
But in JScroll, it still leaves old href and loads old data. For example - I am scrolling on localhost/new, and when I change tab to localhost/top in JScroll nextHref is "http://localhost:8000/new?page=3 div.infinite-scroll" instead of "http://localhost:8000/top?page=1 div.infinite-scroll".
How can I change it so it is synced with tabs?

A: I found a solution.
After each change of tab I added
$('.infinite-scroll').removeData('jscroll').jscroll.destroy();
and called JScroll initializer again.


text:
Q: как с помощью localStorage сделать так чтобы теги  создаваемые в JavaScript не исчезали после перезагрузки? без jQuery js
function fuf() {
    let ghj = document.querySelector('body');
    ghj.innerHTML += "
приветик
";
}

html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width">
    <title>Document</title>

    <button onclick="fuf()">кликЕР</button>

A: В твоём варианте это будет жестко :)
Сохранять - вот так...
localStorage.setItem("saved",
  JSON.stringify([...document.querySelectorAll("body p")]
    .map(el => el.innerText)
  )
);

Читать - вот так...
let savedParagraphs = JSON.parse(localStorage.getItem("saved")) || [];
savedParagraphs.forEach(text => {
    let newElement = document.createElement("p");
    newElement.innerText = text;
    document.body.appendChild(newElement);
});

В чём прикол... В localStorage можно хранить только строки! Поэтому массив надо сохранить как JSON и потом прочитать как JSON. Если прочитать не удалось, то результат getItem == null. JSON.parse(null) будет null и если результат null то null или пустой_массив - || [] вернёт пустой массив. Потом обходим (если был) каждый элемент по словам и создаём параграф - (не вот так ghj.innerHTML += "
приветик
") что в корне не правельно, а правильно через создание DOM элемента параграф, и установкой ему текстового значения. Потом присоеденяем новый созданный элемент к тэгу BODY у которого есть символическая ссылка document.body


text:
Q: How to set the URL for View using Wagtail?
Does Wagtail only use the slug in Promote Tab, or should I set the url in
  urls.py?

I'm using Wagtail, I've 2 pages:
a) Ministerios Internacionales Elim
b) Doctrina Elim
I want to set a as homepage, and b to:
http://127.0.0.1:8000/doctrina-elim/

Right now doctrina/urls.py is empty :(
I've this model in doctrina/models.py:
class DoctrinaIndexPage(Page):

    template = 'doctrina/doctrina_index_page.html'

    nivel = models.CharField(max_length=255, default='Básico')

    subtitle = models.CharField(max_length=255, default='Publicación reciente')

    body = RichTextField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('subtitle', classname="full"),
        FieldPanel('body', classname="full")
    ]

The view has this (doctrina/views.py):
from django.shortcuts import render

# Create your views here.
def home_page(response):
    return render(response, "home/home_page.html")

# Create your views here.
def doctrina_index_page(response):
    return render(response, "doctrina/doctrina_index_page.html")

In promote tab, it has this url:
doctrina-elim

But entering that after the hostname gives 404, why?

Structure:
-doctrina
    |__pycache.py_
    |__migrations.py
    |__templates
    |___init__.py
    |_admin.py
    |_apps.py
    |_models.py
    |_test.py
    |_urls.py
    |_views.py

-elim
     |__pycache_.py
     |_settings.py
     |_static
     |_templates
     |___init__.py
     |_urls.py
     |_wsgi.py
-home
     |__pycache_.py
     |_migrations.py
     |_static
     |_templates \ home
        |_home_page.html
        |_welcome_page.html
     |___init__.py
     |_models.py
     |_urls.py
     |_views.py

I can only access my Page models when setting them as sites, and visit the "/" home.

A: With Wagtail you will likely find that your views.py file does not have a lot in it.  Rather, you create links to navigate to the page, and then Wagtail serves up the page - you don't have to render it from a view as you are doing.  Here is some example code of how you might render a navigation bar:
{% load wagtailcore_tags %}

    {% for item in request.site.root_page.get_children.live.in_menu %}

            {{ item.title }}

    {% endfor %}

This code only shows a single-level menu/page tree (not sub-menus), and it doesn't show applying a class name to indicate the active menu item - it only shows the basics of creating a menu.  To conclude:  whereas in Django you render and create associated context from within views.py, Wagtail takes care of rendering the page without the need of anything in views.py.  However, if you need to add context to a Wagtail page, then define get_context(self, request) for the page:  https://docs.wagtail.io/en/latest/topics/pages.html#customising-template-context.

A: As mentioned at How to set the URL for View using Wagtail? , the doctrina-elim page needs to be made a CHILD page of the homepage.
You can do that from the page listing (this page) by clicking on 'More' underneath the page, then 'Move'.
If you don't do that, Wagtail will not treat it as belonging to the same site.