text:
Q: Angular2: Unsubscribe from host listener If I subscribe to an event in an Angular2 component using host{}, how can I unsubscribe from the event?
@Component({
    selector: "foo",
    host: {
        "(window:resize)": "doSomething($event)"
    }
});

I've tried to use $event to unsubscribe, but the event itself never presents the scenario in which I want to unsubscribe.
For now, I'm just doing a poor man's short circuit, but I'd prefer to avoid the extra checks involved in short circuiting.
Poor man's short circuit:
private _conditionMet:boolean = false;
doSomething(e) {
    if(this._conditionMet) {
        return;
    }
    ...
}

somethingElse() {
    this._conditionMet = true;
}

A: You can't unsubscribe from host-listener. If you need to unsubscribe you need to subscribe imperatively.
See also Programmatically (un)register to event with Angular 2


text:
Q: Do I need to reinstall my OS due to Ruby? After trying to upgrade my flutter apps dependencies failed, I've seen a command in the call stack and tried to run it. Now I think I screwed up my local ruby installation with my workarounds. I would like to know if I could retrace my steps to get the original ruby setup without my workarounds, without reinstalling the OS or is it fine the way it is?
Possible important information:

*

*Ventura: 13.0

*XCode: 14.01

Here is a summary of what I've done:
It was: sudo gem pristine ffi --version 1.15.5, but instead of fixing stuff it broken even more. Some things were missing and I tried to get back to it's original state.
I've found this answer. Now I tried to reinstall cocoapods which was apperantly broken by running: sudo gem install cocoapods.
Didn't work out because of some missing ruby/config.h headers apperantly. After researching I once again found an answer:

*

*

*

*I ran: cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/include/ruby-2.6.0/ruby

*

*There I created the systemlink: sudo ln -sf ../../../../Headers/ruby/config.h

*

*Afterwards I navigated one folder up: cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/include/ruby-2.6.0

*

*And here I needed to do something different from the original answer: I needed to run: sudo ln -sf universal-darwin21 universal-darwin22
I've also installed the xcode cli 14.2 beta thing, but that didn't help either.
Now the App I tried to upgrade is broken, but a different one seems to work, so I think not everything is broken on the system, at least I hope so.

A: Passing RUBY_CFLAGS="-w" worked for me on MacOS Ventura M1 Max.
example:
RUBY_CFLAGS="-w" rbenv install 2.4.0

A: Same issue Xcode 14.2 14C18 on Monterey, when I try to install cocoapods, (homebrew version is lag behind).
I am luckier than you.
I follow this https://stackoverflow.com/questions/64070241/install-ruby-development-tools-for-gem-installation-on-osx-catalina
And got ruby and the latest cocoapods.
I take all the steps, but I think the essential elements only:
xcode-select --install #(for toolchain)
brew install rbenv ruby-build
rbenv install 3.1.2 (your choice) #which will install Ruby from source with regardless to installed Xcode.
sudo gem install cocoapods

Voila!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I run this check even at all times I want to check if a file has a new line added to it but the check does not do what its supposed to do.
 while True:
    with open("text.txt", "r") as file:
        currentLines = len(file.readlines())
        if currentLines != totalLines:
            totalLines = currentLines
            get_latest_message()
            print(totalLines)
        else:
            myMessage = input("type a message: ")
            send_message(myMessage)

The program is supposed to use get_latest_message() if the text file is edited but this does not work because the check is only executed after you send a message because of the way the loop is structured, and because get_latest_message() only prints the latest message (yours since you just sent it) and skips over any sent in between.
Basically, I want to run the above code even while stopped at the myMessage = input("type a message: ") part. Thanks!

A: Trying putting each seperate component of the program in seperate threads using the threading library. You could loop through and check if any new text was added to the file in one thread, while the other thread could be checking whether the user input any text, and writing it to the file.


text:
Q: How to create a status bar icon on the right side? (Android) Notification and NotificationManager are used to create icons to be placed on the top-left position of the screen. A Notification also need to have an entry on the status bar pull-down.
However, icons on the right side such as the battery, signal strength, wireless indicators do not need any entry on the status bar.
How do I make such icons without any entry in the status bar pull-down?

A: I believe the right side area of the notification bar is reserved for the OS.

A: Why would you accept the above answer . . . if you take the android source and build it yourself then setting the icon on the right side isn't impossible. I've Started a new Question with this check here  How to create a Notification \ status bar icon on the right side?


text:
Q: Sort and display all products by most viewed in WooCommerce Inspired by the thread Sort Woocommerce products by most viewed using Post View Counter,  here is my code below, that changes the product sorting option to show products most viewed products:
    /**
 * Setting post count on each visit
 *
 */
add_action( 'woocommerce_before_single_product', 'prefix_save_product_views' );
function prefix_save_product_views(  ) {

    $product_id = get_the_ID();
    $increment = 1;
    $current_visit_count = get_post_meta( $product_id, 'product_visit_count', true );

    $total_visit_count = (int)$current_visit_count + $increment;
    update_post_meta( $product_id, 'product_visit_count', $total_visit_count );

}

/**
 * Change the display order based on visit count only in Catalog
 *
 */
add_filter('woocommerce_get_catalog_ordering_args', 'prefix_woocommerce_catalog_orderby');
function prefix_woocommerce_catalog_orderby( $args ) {
    $args['meta_key'] = 'product_visit_count';
    $args['orderby'] = 'meta_value_num';
    $args['order'] = 'desc';
    return $args;
}

However it does not show all other products which do not have any page views yet.
Is there a way to prioritize sorting by page views and at the same time, after, to show other products (that haven't page views yet) as well.
Any idea please?

A: For that all other products (not viewed yet) should need to have product_visit_count meta key with a meta value of 0.
You can do that by adding this simple function, that you will run once (always make a database backup):
// Function that set "product_visit_count" metakey with a zero value on non visited products
function set_zero_product_visit_count_on_not_visited_products() {
    // Only for admin user role
    if( ! current_user_can('edit_products')) return;

    // Get all products that doesn't have "product_visit_count" as metakey (not visited)
    $product_ids = wc_get_products( array(
        'limit'         => -1,
        'return'        => 'ids',
        'meta_key'      => 'product_visit_count',
        'meta_compare'  => 'NOT EXISTS',
    ) );

    // Loop through product ids
    foreach( $product_ids as $product_id ) {
        // Add 'product_visit_count' meta key with a value of 0 (zero)
        update_post_meta( $product_id, 'product_visit_count', 0 );
    }
}

// Triggers the function
set_zero_product_visit_count_on_not_visited_products();

Code goes in functions.php file of your active child theme (or active theme).
Once saved, as an administrator user role, browse any page of your web site, this execute the function. Now you can remove it (delete it). Tested and works.

Now for your new upcoming products, when you will add a new product, the following script will add product_visit_count meta key with a meta value of 0:
add_action( 'woocommerce_admin_process_product_object', 'init_product_visit_count_on_new_prodct' );
function init_product_visit_count_on_new_prodct( $product ) {
    // Get 'product_visit_count' meta value
    $meta_value = $product->get_meta( 'product_visit_count' );

    // If meta value doesn't exist
    if ( empty($meta_value) ) {
        // Set the 'product_visit_count' to zero
        $product->update_meta_data( 'product_visit_count', 0 );
    }
}

Code goes in functions.php file of your active child theme (or active theme). It should work.


text:
Q: Structuring firebase database, dependency on two variables I'm having some trouble structuring my database.
Currently I have users and groups structured as following:
-groups
    -groupId
         -groupname: "...."
         -users
              -userId: true

-users
  -userId
       -username: "..."
       -groups
            -groupId: true

Now I want to add variables that are dependent on both groups and user. I tried making another tree called groupUser containing both a groupId and userId, but it's hard to query on two conditions with Firebase. So what would be the best way to structure the database?
Thanks in advance!

A: I would structure your data like so:
{
    groups: {
        groupIdOne: {
            groupname: "...",
            users: {
                userIdOne: true
            }
        }
    },
    users: {
        userIdOne: {
            username: "...",
            groups: {
                groupIdOne: true
            }
        }
    },
    groupUsers: {
        groupIdOne: {
            userIdOne: {
                //data for group users
            }
        }
    },
    //and/or
    userGroups: {
        userIdOne: {
            groupIdOne: {
                //data for user groups, same as above
            }
        }
    }
}

This way if you have a group id and a user id you just query that node directly by doing something like .child('groupUsers').child(groupId).child(userId)


text:
Q: Pivot data base on number of values in group by, instead of a full pivot I am trying to pivot a dataframe in pandas. In the example below, the pivot would be on the id column and value is the value column. But instead of a normal pivot where each of the ids would be their own column (several thousand in my real dataset), I want (3) generic id columns since each type usually only has 1-3 ids.
I tried using pivot and pivot table functions in pandas. I have also been playing around with groupby without aggregation. Is there a more straight-forward solution? Is there a term for what I am trying to achieve?
Starting Sample Dataset:

type id    value
A    123   11.9
A    234   10.2
A    129   19.3
B    123   11.9
B    189   12.2
B    120   17.8
C    120   17.8
C    139   17.9
D    110   8.5

Desired Output:

type id1    id2    id3
A    11.9   10.2   19.3
B    11.9   12.2   17.8
C    17.8   17.9   Nan
D    8.5    Nan    Nan

A: First create the dummy column id and then groupby using that
df1['aux'] = df1.groupby('type')['id'].cumcount().reset_index()[0].values
df1.pivot(index='type', columns = 'aux', values = 'value')

Output:
aux      0     1     2
type
A     11.9  10.2  19.3
B     11.9  12.2  17.8
C     17.8  17.9   NaN
D      8.5   NaN   NaN

A: cumcount, pivot_table & add_prefix
First we can create the new id's with cumcount since they are in consecutive order in the groups of type:
Then we can pivot on this new id and use add_prefix to get your wanted column names:
df['id2'] = df.groupby(['type']).cumcount()+1

piv = df.pivot_table(index='type', columns='id2', values='value')\
        .add_prefix('id_')\
        .reset_index()\
        .rename_axis(None, axis=1)

  type  id_1  id_2  id_3
0    A  11.9  10.2  19.3
1    B  11.9  12.2  17.8
2    C  17.8  17.9   NaN
3    D   8.5   NaN   NaN


text:
Q: Regular expression to match Google earth URLs I am trying to get a regular expression that verifies that the url input a user feeds in a form is a valid google earth url. eg https://earth.google.com/web/@18.2209311,-63.06963893,-0.67163554a,2356.53661597d,34.99999967y,358.1303302h,0t,0r
I have tried to use js and html for verification but its not working here is the regex function that I currently have
var urlRegex = /^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;
var earthRegex = /earth.google.com/;

and within the function I have this:
if ((linkInUrl !== '-') && !(urlRegex.test(linkInUrl) && earthRegex.test(linkInUrl))) {
return 'Please enter a valid Link URL';

A: You may try using the following regex pattern:
(?:ht|f)tps?:\/\/earth\.google\.com\/web\/@-?\d+(?:\.\d+)?,-\d+(?:\.\d+)?,-?\d+(?:\.\d+)?a,-?\d+(?:\.\d+)?d,-?\d+(?:\.\d+)?y,-?\d+(?:\.\d+)?h,\d+t,\d+r

Perhaps too long for a full explanation, but each CSV component at the end of the URL is generally matched using something like -?\d+(?:\.\d+)?, which will match a positive/negative integer/float number.


text:
Q: Gradient Grid View With SQL and Asp.net Gridview I am trying to do a gradient color in asp.net below is my code behind.  When I'm debugging in google chrome the result I get is this:  background: linear-gradient(red, 'Color [A=255, R=230, G=255, B=0]';
I'm basically trying to get a gradient style grid view while pulling a user defined color from my database.  How do I accomplish this?
 SqlDataAdapter grid13 = new SqlDataAdapter("SELECT [User],Colors, [TempID]
 FROM dbo.[Colors]", con13);
    DataTable tools13 = new DataTable();
    grid13.Fill(tools13);
    DataTable alltools13 = new DataTable();

    foreach (DataRow row in tools13.Rows)
    {
        foreach (var item in row.ItemArray)
        {
            if (e.Row.Cells[1].Text == (row["User"].ToString()))
            {
                e.Row.Cells[0].BackColor =
 System.Drawing.ColorTranslator.FromHtml(row["Colors"].ToString());
                e.Row.Cells[1].BackColor =
 System.Drawing.ColorTranslator.FromHtml(row["Colors"].ToString());
                e.Row.Cells[2].BackColor =
 System.Drawing.ColorTranslator.FromHtml(row["Colors"].ToString());
                e.Row.Cells[3].BackColor =
 System.Drawing.ColorTranslator.FromHtml(row["Colors"].ToString());
               e.Row.Cells[1].Attributes.Add("style", "background: linear-
 gradient(red,
 '"+System.Drawing.ColorTranslator.FromHtml(row["Colors"].ToString())+"'");

A: The gradient is not supported by all browsers, so you should be careful about this.
In my example, I write a CSS class for each item. It is possible for you to turn this into a C # class and write methods to identify identical objects and avoid identical CSS classes, but it will not be the focus here.
TableDAO (what?)
It is better to work with List <> than with DataTable. But you use DataTable in the question, so I did a GoHorse here just to keep consistency with your question OK?
public class TableDAO
{
    public DataTable GetClients()
    {
        var clientTable = new DataTable("tblClients");
        clientTable.Columns.Add("id", typeof(int));
        clientTable.Columns.Add("name", typeof(string));
        clientTable.Columns.Add("gradientParams", typeof(string));
        clientTable.Columns.Add("gradClass", typeof(string));

        var row = clientTable.NewRow();
        row[0] = 1;
        row[1] = "Kakaroto";
        row[2] = "left,red,orange,yellow,green,blue,indigo,violet";
        row[3] = "grad1";
        clientTable.Rows.Add(row);

        row = clientTable.NewRow();
        row[0] = 2;
        row[1] = "Vegeta";
        row[2] = "right,rgba(255,0,0,0),rgba(255,0,0,1)";
        row[3] = "grad2";
        clientTable.Rows.Add(row);

        row = clientTable.NewRow();
        row[0] = 3;
        row[1] = "Broly";
        row[2] = "-90deg, red, yellow";
        row[3] = "grad3";
        clientTable.Rows.Add(row);

        return clientTable;
    }
}

Aspx.cs (Code Behind)
using TableDAO = MyApplication.DAO.TableDAO;
public partial class MyPage : System.Web.UI.Page
{
    protected string TableGradientCss { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        BindClients();
    }

    public void BindClients()
    {
        var dao = new TableDAO();
        var clientTable = dao.GetClients();
        gvDados.DataSource = clientTable;
        gvDados.DataBind();

        ExtractClientsGradientCss(clientTable);
    }

    protected void gvDados_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        var label = e.Row.FindControl("gradClass") as Label;
        if (label != null)
        {
            e.Row.CssClass = label.Text;
        }
    }

    private void ExtractClientsGradientCss(DataTable clients)
    {
        var sb = new StringBuilder();
        foreach(DataRow row in clients.Rows)
        {
            sb.Append(
                GetGradientCss(
                    row["gradClass"].ToString(),
                    row["gradientParams"].ToString()));
        }
        TableGradientCss = sb.ToString();
    }

    private string GetGradientCss(string className, string gradientParams)
    {
        var css = @"
        .{0} {{
            background: white;                          /* For browsers that do not support gradients */
            background: -webkit-linear-gradient({1});   /*Safari 5.1-6*/
            background: -o-linear-gradient({1});        /*Opera 11.1-12*/
            background: -moz-linear-gradient({1});      /*Fx 3.6-15*/
            background: linear-gradient({1});           /*Standard*/
        }} ";
        return string.Format(css, className, gradientParams);
    }
}

Aspx (Designer View)
// some code
<style>
    <%= TableGradientCss %>
</style>
// more code
<asp:GridView ID="gvDados" runat="server"
    AutoGenerateColumns="false"
    OnRowDataBound="gvDados_RowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="Código">
            <ItemTemplate>
                <%# Eval("id") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Nome">
            <ItemTemplate>
                <%# Eval("name") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField Visible="false">
            <ItemTemplate>
                <asp:Label ID="gradClass" runat="server"
                    Text='<%# Eval("gradClass") %>'>
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>


text:
Q: Issue with PHP loop not displaying all elements The following code snippet for a wordpress page for some reason is not displaying all of the elements in the this loop.  It is only displaying one of the three that are actually returned for $latest_comment. When I console out $latest_comment I get three Obj, all of which I want to run through and display.
Everything looks fine to me but I'm looking with tired eyes.  Any help is appreciated. It seems it must be in the if statement following the $latest_comment assignment.
<?php $num_comment=get_comments_number();
                            if($num_comment > 0){ ?>

                            <?php $args = array(
                                'number' => 10000,
                                'post_id' => $post->ID,
                                'status' => 'approve'
                            );?>
                            <?php $latest_comment = get_comments($args);
                            //returns 3 Obj which is correct

                            if( $latest_comment ) foreach( $latest_comment as $comment ) {

                                $vote = get_comment_meta( $comment->comment_ID, 'age1', true );
                                //var_dump($vote);
                                if($vote=="on"){
                                ?>

                                .....html stuff here....

                            <?php  break; } ?>
                            <?php } ?>

                       <?php } ?>

A: remove <?php  break; } ?> form your code


text:
Q: characteristic polynomial of an endomorphism of on $\mathcal{O}_X$-module I've seen several times people looking at the characteristic polynomial of some
$f \in \mathrm{End}_{\mathcal{O}_X}(\mathcal{E})$
where $\mathcal{E}$ is an $\mathcal{O}_X$-module on let's say some smooth projective algebraic variety $X$ over a field $k$. I'm not sure I understand what does it means. For instance, where are the coefficients of this polynomial? Are they in k?
Thanks


text:
Q: How to validate JWT token using identity server 4 in DRF? I have an idenityserver4, a front-end angular app, and a Django rest framework resource API. The Angular app is unaccessible if not logged, and redirect to the identityserver4. The user has to log in there and is redirected to the front-end. So far so good, the provider gives the front-end a JWT access token.
Then the frontend application asks for resources to the DRF API providing the JWT. That's where I'm stuck, all the tutorials I find on google explain how to create your own provider. But I just want to get the token, check with the identity server 4 that it's valid, authenticate the user, provide the resources
Any code snippet or library will be highly helpful.
Thanks.

A: I had a similar problem that I haven't fully solved, but maybe this can help you.
It is a permission class that only checks if a given jwt is properly encoded and signed using authlib, from there you can access the token internal information to do further validation.
permissions.py:
from authlib.jose import jwt
from rest_framework import permissions
from rest_framework.exceptions import APIException

class TokenNotValid(APIException):
    status_code = 403
    default_detail = "Invalid or absent JWT token field."

class NoAuthHeader(APIException):
    status_code = 403
    default_detail = "Absent 'Authorization' header."

class ValidJWTPermission(permissions.BasePermission):
    """
    Global permission check for JWT token.
    """

    def _get_pubkey(self):
        # You will probably need to change this to get the
        # public key from your identity server and not from a file.
        with open("../public.pem", "rb") as key_file:
            pubk = key_file.read()
        return pubk

    def has_permission(self, request, view):

        auth_header = request.META.get('HTTP_AUTHORIZATION')
        # print("Received header:")
        # print(auth_header)
        if auth_header is None:
            raise NoAuthHeader

        try:
            token = auth_header.split()[1]
            # print("Encoded Token:")
            # print(token)
            dec_token = jwt.decode(token,self._get_pubkey())
        except Exception:
            # Probably should add proper exception handling.
            raise TokenNotValid

        # print("Decoded token:")
        # print(dec_token)

        return True

views.py:
from .permissions import ValidJWTPermission

class HelloView(APIView):
    permission_classes = [ValidJWTPermission]

    def get(self, request):
        return HttpResponse("Hello, world. You're at the gerenciador index.")


text:
Q: How to add archives (with pagination) to page template? So the site I'm building has a few different archives pages. For the newest one I'm building, I tried to copy the archive.php I've got:
page-archives.php:
<?php get_header(); ?>

Archives

    <?php get_template_part('inc/loops/default','default-loop'); ?>

    <?php custom_pagination(); ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

inc/loops/default.php:
<?php

global $query_string;
$results = new WP_Query($query_string);

if ($results->have_posts()) :
    while ($results->have_posts()) :
        $results->the_post();
                    // DO STUFF HERE.
             endwhile;
    endif;

?>

And the custom_pagination function in functions.php:
function custom_pagination() {
    global $wp_query;
    $big = 999999999;
    echo paginate_links(array(
        'base' => str_replace($big, '%#%', get_pagenum_link($big)),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'total' => $wp_query->max_num_pages,
        'type' => 'list'
    ));
 }

Whenever I do global $query_string or global $wp_query, it thinks the query is for the Archives page (which it is) and I'm not sure how to break out of that.
I can work around that by putting the loop directly in the page-archives.php without $query_string and call paginate_links() instead of calling it's wrapper, but I'd rather not do that.
Also, I have an archive.php which is basically this, but I can't figure out how to get it to work for all posts. I need to answer this question anyways for a few other custom archives.


text:
Q: Is the following a well-known idiom? "The legal team buried them in paper" Slang Legal Terms
I have heard the expression in movies but  it is not represented as an idiom in computer searches.
I want to use it in a legal case in which I am involved
A similar question occurs in another posting.

A: The idiom, to bury oneself in something, is recognized by the McGraw-Hill Dictionary of American Idioms and Phrasal Verbs.
Definition:

*

*Figurative: to become very busy with something.

Example:

She stopped taking phone calls and buried herself in her work.

This idiom is also recognized by:

*

*Cambridge Advanced Learner's Dictionary & Thesaurus

*Merriam-Webster Online Dictionary

*Macmillan Dictionary Online

*Oxford Dictionaries Online

A: I would prefer the term paperwork in either the passive or active voice, but paper would also work.

*

*The legal team was buried in paperwork

*The legal team buried the defendant in paperwork

Alternatively, one could use the participle drowning, as in "He was drowning in paperwork". Merriam-Webster calls this construction a metaphor

"He was drowning in paperwork" is a metaphor in which having to deal with a lot of paperwork is being compared to drowning in an ocean of water.

You can certainly be buried...

*

*in paperwork

*under a pile of paper (OR) documents

Source

*under a mountain of paper/paperwork

Google Ngram suggests "a mountain of paperwork" (green line) is the most common phrase.


text:
Q: php extract year/month/day/hour/minute/seconds from a date if i have a date and i want to extract the year, the month, etc in PHP5, how should i proceed?
if i do
 $y = date('Y',$sale->end);

it doesn't work...

A: If $sale->end is a valid datestamp, pass it through strtotime() like so:
$y = date('Y', strtotime($sale->end));

A: As jnpcl indicated, if $sale->end holds a valid datestamp you can do the following:
list($year,$month,$day,$hour,$minute,$second)=explode('-',date('Y-m-d-h-i-s',strtotime($sale->end)));


text:
Q: url_launcher Unable to call mobile browser This is my code
 void _launchUrl() async {
    userInfo = SpUtil.getMap(Constants.APP_USERINFO);
    if(userInfo['permit']['hua_yan'] == '1'){
      final Uri _url = Uri.parse('http://www.baidu.com');
      if (!await canLaunchUrl(_url)) throw 'Could not launch $_url';
    }
  }

Will prompt
I/UrlLauncher( 6039): component name for http://www.baidu.com is {com.huawei.browser/com.huawei.browser.Main}

I used some official prompt codes, but still can't, still can't
https://developer.android.com/training/package-visibility/use-cases,in AndroidManifest.xml file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.ahlims.ahlims">
    <!-- Flutter needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <queries>
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="https" />
        </intent>
    </queries>
</manifest>

Hope to get help, thank you

A: Add below dependency in AndroidManifest.xml just above of application
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" />
    </intent>
    <!-- If your app opens https URLs -->
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <data android:scheme="http" />
    </intent>
    <!-- If your app opens https URLs -->
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <data android:scheme="https" />
    </intent>
</queries>

MobileUrl Screen
class MobileUrl extends StatelessWidget {
  const MobileUrl({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    void _launchUrlA() async {
      final Uri _url = Uri.parse('https://flutter.dev');
      if (!await launchUrl(_url)) throw 'Could not launch $_url';
    }
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(onPressed: (){
                _launchUrlA();
              }, child: Text('Click Button'))

            ],
          ),
        ),
      ),
    );
  }
}

A: This can realize the function I want。
 String baseUrl = Get.find<AppConfigService>().baseUrl;
 final Uri url = Uri.parse(baseUrl);
 if (await canLaunchUrl(url)){
    await launchUrl(url, mode: LaunchMode.externalApplication ,webOnlyWindowName:'_blank');
}

Reference links:
https://pub.dev/documentation/url_launcher/latest/url_launcher/launchUrl.html


text:
Q: What to do after git init? Seeking to create private GitLab repository and sync with local working site files? I have initialized a Git repository in local C:/pathtosite/.git/ ...
I've created a private repository on GitLab ...
My goal is to continue working on my site locally, but have version control ...
Hours later, I'm still having issues trying to understand what to do next ...

A: You need to add your files and push them to your repository.
git add -A
git commit -m 'first commit'
git remote add origin git@gitlab.domain.com:username/repository.git
git push -u origin master

Step by step:
Add all files in repository
git add -a

Commit files (with commit message 'first commit')
git commit -m 'first commit'

add your remote gitlab repository(git@gitlab.domain.com:username/repository.git) as origin
git remote add origin git@gitlab.domain.com:username/repository.git

push your files to origin
git push -u origin master

Hope this helps?

A: If I understand your question right, you've run
git init

locally, and created a repository on GitLab? If so, the issue is that you're not quite following the standard workflows for git. You don't want to explicitly initialize your local git repository. Instead, following the gitlab documentation:

*

*Go to your repository page on gitlab

*Copy the https URL it gives you on the right-hand side of the page

*Take that URL, and run git clone the-url-goes-here one level above where you would like the local copy to go (i.e. if you want the repository in C:\my\gits\path\repo, run this command in C:\my\gits\path).

Once you do that, you'll have a local copy you can work in under version control. fupduck's answer below covers what you'll want to do once you have that repository working with regard to adding files and making changes.


text:
Q: SharedPreferences save a text entered in an EditText and display it in a TextView in another activity I'm beginner in Android development and I have an issue with save changement with some texts display in some TextViews. But one is more difficult for me.
For explain simple, I have 2 activities, Activity1 is the main, Activity2 is the user informations.
In Activity1 (Main) the user clic the button ("login") then he go on Activity2 here user can enter his personal informations and he click on a button ("save data") then I add his datas on a database (SQLite), then when the user click on another button ("go") he return on Activity1 I use an intent in order to show his nickname on a TextView in the Activity1 with a "Welcome" + nickname.
But when the user quit the app, there's no save, the changement hasn't save with the nickname, but the nickname are always in my database.
I will show u some code:
Activity2:
public class ProfilActivity extends Activity {

EditText editNickname; // We just work on the nickname so I just keep it
MyDatabase myDb;
Button bAddData, go;
public SharedPreferences prefs;
private String nicktobesaved;

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_profil);
    myDb = new MyDatabase(this);
    prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);

    editNickname = (EditText) findViewById(R.id.pseudo2);
    bAddData = (Button) findViewById(R.id.ajouter);

    nicktobesaved = prefs.getString("nickname", "");
    bAddData.setEnabled(prefs.getBoolean("isEnabled", true) ? true : false);

    AddData();
} // End onCreate()

public void changeNickname(View v) {
    // I delete this method who passed an intent
}

public void AddData() { // When user click on bAddData button
    bAddData.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    nicktobesaved = prefs.getString("nickname", "");
                    nicktobesaved = editPseudo.getText().toString();

// The following code is just for save data on my database SQLite
                    boolean isInserted = myDb.insertData(editNickname.getText().toString());
                    if (isInserted == true) {
                        Toast.makeText(ProfilActivity.this, "Data saved", Toast.LENGTH_LONG).show();
                        prefs.edit().putBoolean("isEnabled", false).apply();
                        bAddData.setEnabled(false);
                    } else {
                        Toast.makeText(ProfilActivity.this, "Data not saved", Toast.LENGTH_LONG).show();
                    }
                }
            }
    );
}
}

Activity1 (Main activity):
public class MainActivity extends Activity {

TextView tv;
Button login;
public SharedPreferences prefs;
private String nickname;

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

    prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
    nickname = prefs.getString("nickname", "");

    login = (Button) findViewById(R.id.connexion);
    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intentLogin = new Intent(MainActivity.this, ProfilActivity.class);
            startActivity(intentLogin);
        }
    });

    tv = (TextView)findViewById(R.id.pseudo);

if(nickname.equals("")) {
        tv.setText("Welcome");
    } else {
        tv.setText("Welcome " + nickname);
    }
}
}

Pseudo = nickname in french,
Bienvenue = welcome in french,
Thank u all for yo help, I hope u could understand my question.
Pikkoro

A: I would recommend you to use Sharedpreferences to store basic information, and read some tutorial or documentation about how to save data on Android. Here I made an example using Sharedpreferences. Hope it helps!
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by Hasan on 4.05.2017.
 */

public class ProfilActivity extends Activity {

    EditText editName, editNickname;
    Button bAddData;
    public SharedPreferences prefs;

    //To be saved elements in sharedpreferences!!!
    private String nicktobesaved, nametobesaved;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_profil);
        prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);

        editName = (EditText) findViewById(R.id.name);
        editNickname = (EditText) findViewById(R.id.pseudo2);
        bAddData = (Button) findViewById(R.id.ajouter);

        //default values
        nametobesaved=prefs.getString("name", "");
        nicktobesaved=prefs.getString("nickname", "");

        bAddData.setEnabled(prefs.getBoolean("isEnabled", true) ? true : false);

        if(!nametobesaved.equals("")) {
            editName.setText(nametobesaved);
        }
        if (!nicktobesaved.equals("")){
            editNickname.setText(nicktobesaved);

        }

        AddData();
    } // End onCreate()

    public void AddData() { // When user click on bAddData button
        bAddData.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        nametobesaved=prefs.getString("name", "");
                        nicktobesaved=prefs.getString("nickname", "");

                        nametobesaved= editName.getText().toString();
                        nicktobesaved= editNickname.getText().toString();

                        if(nametobesaved.equals("") || nicktobesaved.equals("")){
                            Toast.makeText(ProfilActivity.this, "Fill all spaces", Toast.LENGTH_LONG).show();
                        }else {

                            SharedPreferences.Editor editor = prefs.edit();
                            editor.putString("name", nametobesaved);
                            editor.putString("nickname", nicktobesaved);
                            editor.commit();

                            Toast.makeText(ProfilActivity.this, "Data saved", Toast.LENGTH_LONG).show();
                            prefs.edit().putBoolean("isEnabled", false).commit();

                            bAddData.setEnabled(false);
                        }

                    }
                }
        );
    }
}

After saving nickname to the Sharedpreferences you need to load it in Main activity. It goes like this:
public class MainActivity extends Activity {

public static final int PROFIL_REQ = 1;
public static final String PSEUDO="nickname";
TextView tv;
Button login;

    //Sharedpreferences and nick name variables
    private SharedPreferences prefs;
    private String nickname;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView)findViewById(R.id.pseudo);

            //Load or create sharedpreferences
        prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
        nickname = prefs.getString("nickname", "");

        if(nickname.equals("")) {
            tv.setText("Welcome");
        }else{
            tv.setText("Welcome "+ nickname);
        }
    }

That's because you deleted sharedpreferences editor.
public void AddData() { // When user click on bAddData button
    bAddData.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    nicktobesaved = prefs.getString("nickname", "");
                    nicktobesaved = editPseudo.getText().toString();

//DO NOT DELETE HERE

                                    SharedPreferences.Editor editor = prefs.edit();

                                editor.putString("nickname", nicktobesaved);
                                editor.commit();

// The following code is just for save data on my database SQLite
                    boolean isInserted = myDb.insertData(editNickname.getText().toString());
                    if (isInserted == true) {
                        Toast.makeText(ProfilActivity.this, "Data saved", Toast.LENGTH_LONG).show();
                        prefs.edit().putBoolean("isEnabled", false).apply();
                        bAddData.setEnabled(false);
                    } else {
                        Toast.makeText(ProfilActivity.this, "Data not saved", Toast.LENGTH_LONG).show();
                    }
                }
            }
    );
}


text:
Q: Do functional integrals have countable or uncountable infinite dimensions? According to https://en.wikipedia.org/wiki/Functional_integration functional integrals can be written like
$$
\lim_{x->\infty}\int\limits_{-\infty}^\infty{ ... \int\limits_{-\infty}^\infty{ G[f] } }\prod_x df(x)
$$
But by using the product symbol $\prod$ this implies, that a functional integral has countable infinite dimensions. But is the space of functions used for functional integration really discrete and countable? I thought it is continuous/uncountable.


text:
Q: Access JSON Object in ajax success Somehow I can't find out how to access my json object from ajax call.
In the handler, I'm echoing next id:
echo json_encode(array(
   "nextId" => 2
));

Then I want to access it with data:
$.ajax({
   [...],
   dataType: 'json',
   success:function(data) {
       console.log(data)
       console.log(data['responseText'];
       console.log(data['responseText'].nextId);
       console.log(data['responseText']['nextId']);
   }
});

Result: Object {readyState: 4, responseText: "{"nextId":2}", responseJSON: Object, status: 200, statusText: "OK"}
Result: {"nextId":2}
Result: Undefined
Result: Undefined

I want to get the value of nextId

A: Looking at your data object, I see an object in there called responseJSON... Try this instead:
$.ajax({
   [...],
   dataType: 'json',
   success:function(data) {
       console.log(data)
       console.log(data['responseJSON'];
       console.log(data['responseJSON'].nextId);
       console.log(data['responseJSON']['nextId']);
   }
});

Hope this helps!


text:
Q: Does slew rate of an op-amp affect a low pass filter? Lets say we have an active low pass filter with an OP-AMP. Does slew rate of this op-amp affect the filter? what will change? From what I understand, since the op-amp is charging and unchanging the capacitor with different currents passing through the resisor, there will a maximum rate of change in the output voltage, ie slew rate, which make the signal distorted.
Am I thinking correctly?

A:
there will a maximum rate of change in the output voltage, ie slew rate, which make the signal distorted.

This is a correct description of slew rate limit.

Does slew rate of this op-amp affect the filter? what will change?

If correct operation of your filter requires the output of the op-amp to change faster than the slew rate limit allows, then it will not operate correctly.
Notice that the slew rate depends on both the frequency content and the amplitude of the output signal. So if you have a problem with slew rate limiting, you might be able to correct it by either using lower frequencies (reducing the cut-off frequency of your LPF), or by reducing the output amplitude (by reducing the input amplitude, or reducing the gain of the filter circuit).

A: Yes - your question touches a very imortant point.
There are many people who think that - for exampe - an active unity gain lowpass filter can be used up to some hundreds of kHz if the opamps transit frequency is 1MHz or even larger. That means: Very often the slew rate limtations are completely forgotten.a


text:
Q: Stuck in CodeIgniter Controller class implementation I am recoding my site using CodeIgniter. This is my first time using an MVC or any other type of development pattern. I am using the video tutorials off of the CI site to make a playground and get acquainted with the protocol of the system.
I've just encountered my first problem and it has to do with a parent class.
I am on the second tutorial trying to make a blog and have this:
<?php

class Test extends CI_Controller {

    function Test()
    {
        parent::CI_Controller();

        $this->load->scaffolding('entries');
    }

    function index()
    {
        $data['muck'] = 'test test test';
        $data['kookoo'] = 'howdy howdy hi';
        $data['hi'] = 'holla';
        $data['yo'] = 'fa la la';
        $data['zoom'] = '1234';
        $data['array'] = array('hi','howdy','hey','sup');
        $this->load->view('test_view', $data);
    }

}

?>

When I loaded the page without the content inside the function Test() I noticed that the system could not find "Controller". I discovered that the tutorial is using an older version of CI and that "CI_Controller" is the proper name for the class Controller. Now with the above code I'm getting this error:
Fatal error: Call to undefined method CI_Controller::CI_Controller() in /Users/michaelsanger/Sites/CodeIgniter/application/controllers/test.php on line 7

I've scoured and am really not sure why it can't define it.
thanks in advance!

A: You're mixing up things from different versions, the 1.7 one focusing mainly on PHP4-style class construction (using a method with the same name as the class as constructor, instead that the dedicated magic method __construct() available in php 5)
Also,  beware that scaffolding is not present in the latest versions. You didn't say which one are you using, I suppose V2. In case you're using an older version, 1) use the latest :) 2) the parent class was just Controller.
It should be like this
class Test extends CI_Controller {

     function __construct()
     {
         parent::__construct();

         //$this->load->scaffolding('entries');
     }

     function Test()
     {
      // this will call a method name test, so maps to a URL like Test/test

     }

}

Note that it's not needed to extends the parent controller, unless of course you want to "autoload" a library to have it available to all methods.
CI is known for its great and easy documentation, so whenever you're using tutorial found on the net, expecially if a bit old (in internet terms), make an habit of going to the user_guide (which is also shipped along with the installation files, for local browsing) whenever you have doubts or problems.
For example, check the controllers page, you'll soon see what's wrong with your snippet (and the tutorial, as of today)
UPDATE:
In routes you're setting a route, that maps to a controller(/method).
Quoting the changelog:

Version 2.0.0
Release Date: January 28, 2011 Hg Tag: v2.0.0
General changes

PHP 4 support is removed. CodeIgniter now requires PHP 5.1.6.
Scaffolding, having been deprecated for a number of versions, has been removed.

So I don't know what you mean now with scaffolding. Looking at your route, CI expects a controller named "scaffolding_trigger", which has to be rerouted to the controller "scaffolding". If any of those are present, you get the 404 error.
Please, choose a version and stick to that, don't mix things! and don't rely on tutorials, they're not always up-to-date with the latest changes.


text:
Q: Asmack File Sending Error 503 Type = cancel with openfire Login Code. Login done successfully.
        String host=AppContext.HOST;//myHost
        String [] params={"a1","aa"}
        int port=AppContext.PORT;//My Port 2777
        String service=AppContext.SERVICE;  //service = smack
        ConnectionConfiguration connConfig = new ConnectionConfiguration(
                host, port, service);
        connConfig.setDebuggerEnabled(true);
            Connection.DEBUG_ENABLED = true;
     connConfig.setSASLAuthenticationEnabled(true);
    XMPPConnection connection = new XMPPConnection(connConfig);
        Log.e("XMPP LoginActivity Username ",params[0]+" pass "+params[1]);
        try {
            connection.connect();
            connectionFlg=true;
            Log.i("XMPP LoginActivity",
                    "Connected to " + connection.getHost());
        } catch (XMPPException ex) {
            Log.e("XMPP LoginActivity", "Failed to connect to "
                    + connection.getHost());
            Log.e("XMPP LoginActivity", ex.toString());
            appContext.setConnection(null);
        }
        try {
            if(connectionFlg)
            {
            connection.login(params[0], params[1]);
            Log.i("XMPP LoginActivity",
                    "Logged in as " + connection.getUser());

            Presence presence = new Presence(Presence.Type.available);
            presence.setStatus("I'm available");
            connection.sendPacket(presence);
            loginFlg=true;
            appContext.setConnection(connection);
            }else
            {
                Log.e("XMPP LoginActivity", "Failed to connect to "
                        + connection.getHost());
            }

        } catch (XMPPException ex) {
            loginFlg=false;                     ;
            Log.e("XMPP LoginActivity", "Failed to log in as "
                    + params[0]);
            Log.e("XMPP LoginActivity", ex.toString());
            appContext.setConnection(null);
        }

My file sending code is bellow
public void sendFile(String sentTo) {
    ProviderManager.getInstance().addIQProvider("query","http://jabber.org/protocol/bytestreams", new BytestreamsProvider());
    ProviderManager.getInstance().addIQProvider("query","http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
    ProviderManager.getInstance().addIQProvider("query","http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());

    FileTransferManager manager = new FileTransferManager(connection);
    OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(sentTo);
    File file = new File(Environment.getExternalStorageDirectory()
            .getPath() + "/user.json");
    try {
       transfer.sendFile(file, "test_file");
    } catch (XMPPException e) {
       e.printStackTrace();
    }
    while(!transfer.isDone()) {
       if(transfer.getStatus().equals(Status.error)) {
          System.out.println("ERROR!!! " + transfer.getError());
       } else if (transfer.getStatus().equals(Status.cancelled)
                        || transfer.getStatus().equals(Status.refused)) {
          System.out.println("Cancelled!!! " + transfer.getError());
       }
       try {
          Thread.sleep(1000L);
       } catch (InterruptedException e) {
          e.printStackTrace();
       }
    }
    if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
     || transfer.getStatus().equals(Status.cancelled)){
       System.out.println("refused cancelled error " + transfer.getError());
    } else {
       System.out.println("Success");
    }

}

while sending i am getting this below two xml response. please take a look.
1)
12:55:16 PM SENT (1092826504): <iq id="SU8c1-17" to="a2@aaa" from="a1@aaa/Smack" type="set"><si xmlns="http://jabber.org/protocol/si" id="jsi_2427513438410796738" profile="http://jabber.org/protocol/si/profile/file-transfer"><file xmlns="http://jabber.org/protocol/si/profile/file-transfer" name="user.json" size="379" ><desc>test_file</desc></file><feature xmlns="http://jabber.org/protocol/feature-neg"><x xmlns="jabber:x:data" type="form"><field var="stream-method" type="list-multi"><option><value>http://jabber.org/protocol/bytestreams</value></option><option><value>http://jabber.org/protocol/ibb</value></option></field></x></feature></si></iq>

2)
12:55:16 PM RCV  (1092826504): <iq type="error" id="SU8c1-17" from="a2@aaa" to="a1@aaa/Smack"><si xmlns="http://jabber.org/protocol/si" id="jsi_2427513438410796738" profile="http://jabber.org/protocol/si/profile/file-transfer"><file xmlns="http://jabber.org/protocol/si/profile/file-transfer" name="user.json" size="379"><desc>test_file</desc></file><feature xmlns="http://jabber.org/protocol/feature-neg"><x xmlns="jabber:x:data" type="form"><field var="stream-method" type="list-multi"><option><value>http://jabber.org/protocol/bytestreams</value></option><option><value>http://jabber.org/protocol/ibb</value></option></field></x></feature></si><error code="503" type="cancel"><service-unavailable xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></iq>

Please Friends help. i have tried many code snippet. since three days i am working on that only :(

A: I had same problem, I investigated the stanza and solved it this way.
Many people use "/Smack" or "/Resource" as resource part in jid, but it can be configured also the another way.
Resource path is changing with every presence changed of user. Lets say we want to send image to this user:
"user1@mydomain"
You must add "/Resource" part to this jid and it become this:
user1@mydomain/Resource
But /Resource path is changing with presence so you must follow every presence change to update resource path.
Best way is to get user presence is in roster listener and in presencheChanged() method you get last user resource part like this:
Roster roster=getRoster();
roster.addRosterListener(new RosterListener() {
                @Override
                public void entriesAdded(Collection<Jid> addresses) {
                    Log.d("entriesAdded", "ug");
                    context.sendBroadcast(new Intent("ENTRIES_ADDED"));
                }

                @Override
                public void entriesUpdated(Collection<Jid> addresses) {
                    Log.d("entriesUpdated", "ug");
                }

                @Override
                public void entriesDeleted(Collection<Jid> addresses) {
                    Log.d("entriesDeleted", "ug");
                }

                @Override
                public void presenceChanged(Presence presence) {
                    Log.d("presenceChanged", "ug");
                    //Resource from presence
                    String resource = presence.getFrom().getResourceOrEmpty().toString();
                    //Update resource part for user in DB or preferences
                    //...
                }
            });
}

Resource string will be some generated string like "6u1613j3kv" and jid will become:
user1@mydomain/6u1613j3kv

That means that you must create your outgoing transfer like this:
EntityFullJid jid = JidCreate.entityFullFrom("user1@mydomain/6u1613j3kv");
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(jid)
transfer.sendFile(new File("DirectoryPath"), "Description");

And that is how i have solved my problem with file transfer on smack and Openfire.
In your case form in sendFile(String sentTo) function sentTo must be formed like my jid with resource path that is changing with every rpesence change.
Also to mention you must add following properties in your Openfire server:
xmpp.proxy.enabled - true
xmpp.proxy.externalip - MY_IP_ADDRESS
xmpp.proxy.port - 7777

Just to mention, I am using Openfire 4.0.2 and Smack 4.2.2.
Also this can be configured the easy way, just set the resource on

XMPPTCPConnectionConfiguration.Builder .

like
XMPPTCPConnectionConfiguration.Builder configurationBuilder =
XMPPTCPConnectionConfiguration.builder();

configurationBuilder.setResource("yourResourceName");


text:
Q: i tired round(7.285,-2) in SQL. What is the significance of '-' sign? round(7.285,-2) gave the output as 7.0
Can anyone pls explain how the output got generated?
round(7.285,-2);

output: 7.0

A: why are you using -2
just use round(7.285)
you will get 7.0 as output
by using -2 it will check up to 2 digits before the decimal
suppose u have a value 117.285
bu using -2 you will get 100.0
and by using +2 in 7.285
you will get output 7.29


text:
Q: How can I filter results when one item can have one or more categories? I can see the items on the list on the screen but there are some of the items missing from the list when no filters are selected but items belongs still to those categories. I have hardcoded list of categories for the category filter picker. Main issue I have here is that how can I take in account now that item can have one or more categories for example I have item on list that can have category: "Cars" and now with latest changes item can also have category: "Cars, Insurance".
How do I update the logic to handle this kind of change?
  const route = useRoute()
  const { data } = route.params
  const [services, setServices] = useState([])
  const [selectedCategory, setSelectedCategory] = useState(undefined)
  const [categories, setCategories] = useState([])
  const [citiesData] = useState(cities)
  const [city, setCity] = useState()
  const [isSelected, setIsSelected] = useState(false)
  const [cardStyle, setCardStyle] = useState(servicesCards)

useEffect(() => {
    (async () => {
      let res = await fetch(`${DEV_API_URL}/cars`)
      let resData = await res.json()
      setServices(resData)
      setCategories(data.map((item) => item.service))
    })()
  }, [data])

 useEffect(() => {
    selectedCategory || city ? setIsSelected(true) : setIsSelected(false)
  }, [selectedCategory, city])

  const resetFilters = () => {
    setSelectedCategory(null)
    setCity(null)
  }

  const ListItem = ({ data }) => {
    return (
      <View key={data.id} style={{ flexDirection: 'row' }}>
        <Text key={data.service} style={optionText}>
          {data.service}
        </Text>
      </View>
    )
  }

  const CityItem = ({ data }) => {
    const { optionText } = GlobalStyle
    return (
      <View key={data.id} style={{ flexDirection: 'row' }}>
        <Text style={optionText}>{data.city}</Text>
      </View>
    )
  }

const filteredServices = selectedCategory || selectedCategory && city
    ? services.filter((company) => company.category === selectedCategory || company.location === city)
    : services.filter((company) => categories.includes(company.category))

          <ModalSelector
            data={data}
            keyExtractor={(x) => x.id}
            labelExtractor={(x) => x.service}
            initValue={
              !selectedCategory ? 'Kategoria' : selectedCategory
            }
            initValueTextStyle={{ color: colors.white, fontSize: 18 }}
            selectStyle={categoryPicker}
            selectTextStyle={{ color: colors.white_087 }}
            optionContainerStyle={{ backgroundColor: colors.black_021 }}
            cancelStyle={{ backgroundColor: colors.red }}
            cancelText='Peruuta'
            cancelTextStyle={{
              color: colors.white_087,
              fontSize: 16,
              fontWeight: 'bold',
            }}
            onChange={(option) => setSelectedCategory(option.service)}
            componentExtractor={(option) => <ListItem data={option} />}
          />
          <ModalSelector
            data={citiesData}
            keyExtractor={(x) => x.city}
            labelExtractor={(x) => x.city}
            initValue={!city ? 'Kaupunki' : city}
            initValueTextStyle={{ color: colors.white, fontSize: 18 }}
            selectStyle={cityPicker}
            selectTextStyle={{ color: colors.white_087 }}
            optionContainerStyle={{ backgroundColor: colors.black_021 }}
            cancelStyle={{ backgroundColor: colors.red }}
            cancelText='Peruuta'
            cancelTextStyle={{
              color: colors.white_087,
              fontSize: 16,
              fontWeight: 'bold',
            }}
            onChange={(option) => setCity(option.city)}
            componentExtractor={(option) => <CityItem data={option} />}
          />
          {isSelected ? (
          <Pressable onPress={resetFilters}>
            <Ionicons
                testID='removeFilters'
                name='trash-outline'
                size={35}
                color={colors.red}
              />
            </Pressable>) : null}
        </View>
        <View style={{ flex: 2 }}>
          <FlatList
            data={filteredServices}
            contentContainerStyle={{
              flexGrow: 1,
              justifyContent: 'center',
              alignItems: 'center',
            }}
            keyExtractor={(item) => item.id}
            horizontal={true}
            renderItem={({ item }) => {
              return !selectedCategory ||
                !city ||
                item.category === selectedCategory && city === item.location ? (
                <Pressable onPress={() => Linking.openURL(`${item.homepage}`)}>
                  <Card key={item.id} style={[cardStyle]}>
                    <CardContainer
                      key={item.img_url}
                      style={{
                        flex: 1,
                      }}
                    >
                      <Image
                        key={item.img_url}
                        style={{ width: '100%', height: '100%' }}
                        resizeMode='contain'
                        source={{ uri: `${item.img_url}` }}
                      />
                    </CardContainer>
                  </Card>
                </Pressable>
              ) : null
            }}
            ListEmptyComponent={() => {
              return (
                <Text style={{ color: colors.white, fontSize: 20 }}>
                  Ei palveluita saatavilla
                </Text>
              )
            }}
          />


text:
Q: Notificaciones Alarma Estoy intentando implementar las notificaciones en mi app de Android, y no veo ningún tutorial (algo raro) sobre cómo gestionar las fechas y las horas de una base de datos para que cuando coincidan con el sistema, me lance una notificación.
Supongo que la idea es pasar la fecha y la hora a milisegundos, osea que a partir de este registro cuente el sistema X milisegundos para repetir la alarma en el sistema..
Aunque la duda que me surge respecto a esto, es como puedo hacer que esto se de forma indefinida cuando el usuario cree la notificacion o la edite...
Alguna idea?

A: yo tengo una alplicacion que te recuerda una hora antes cuando tienes una cita, la cuestion es como dices que hay que pasarlo a formato tiempo, como la hora actual, como la de tu base de datos.
Esto se consigue con un Job Service ( de esto si que hay varios tutoriales ), te paso el codigo que yo tengo ( esta hecho en kotlin ).
Esta es la clase MyJobService
class MyJobService  : JobService() {
internal var isWorking = false
internal var jobCancelled = false
// Called by the Android system when it's time to run the job
override fun onStartJob(jobParameters:JobParameters):Boolean {
    Log.d(TAG, "Job started!")
    isWorking = true
    // We need 'jobParameters' so we can call 'jobFinished'
    startWorkOnNewThread(jobParameters) // Services do NOT run on a separate thread
    return isWorking
}
private fun startWorkOnNewThread(jobParameters:JobParameters) {
    Thread(object:Runnable {
        public override fun run() {
            doWork(jobParameters)
        }
    }).start()
}
private fun doWork(jobParameters:JobParameters) {
    // 60 seconds of 'working' (6000*10ms)
    for (i in 0..60000)
    {
        recorrerMeting()
        // If the job has been cancelled, stop working; the job will be rescheduled.
        if (jobCancelled)
            return
        try
        {
            Thread.sleep(60000)
        }
        catch (e:Exception) {}
    }
    Log.d(TAG, "Job finished!")
    isWorking = false
    val needsReschedule = false
    jobFinished(jobParameters, needsReschedule)
}
// Called if the job was cancelled before being finished
override fun onStopJob(jobParameters:JobParameters):Boolean {
    Log.d(TAG, "Job cancelled before being completed.")
    jobCancelled = true
    val needsReschedule = isWorking
    jobFinished(jobParameters, needsReschedule)
    return needsReschedule
}
companion object {
    private val TAG = MyJobService::class.java.getSimpleName()
}
//*** CREA UNA NOTIFICACION QUE INDICA EN LA PARTE SUPERIOR DE LA PANTALLA QUE HAY CITAS ***
fun creaNotificacion1(whenn: Long, notificationContent: String, ctx: Context) {
    try {
        ;
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationIntent: Intent

        val largeIcon = BitmapFactory.decodeResource(ctx.resources, R.drawable.invoice)

        notificationIntent = Intent()

        /* Crea PendingIntent */
        val pendingIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)

        val notificationManager = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        /* Construye la notificacion */
        val notificationBuilder = NotificationCompat.Builder(ctx).setWhen(whenn).setContentText(notificationContent)
            .setLargeIcon(largeIcon)
            .setAutoCancel(true)   //Automatically delete the notification
            .setSmallIcon(R.drawable.ic_add_alert_black_24dp) //Notification icon
            .setContentIntent(pendingIntent)
            .setContentTitle(ctx.resources.getString(R.string.aviso))
            .setContentText(ctx.resources.getString(R.string.seeMeetings))
            .setCategory(Notification.CATEGORY_REMINDER)
            .setPriority(Notification.PRIORITY_HIGH)
            .setSound(defaultSoundUri)

        Objects.requireNonNull(notificationManager).notify(whenn.toInt(), notificationBuilder.build())

    } catch (e: Exception) {
        Log.e("Notificacion", "createNotification::" + e.message)
    }

}

//*** CREA UNA NOTIFICACION QUE INDICA EN LA PARTE SUPERIOR DE LA PANTALLA QUE HAY CITAS ***
fun creaNotificacion(context: Context) {
    try {

        // SE ELIGE EL SONIDO
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationIntent: Intent

        // SE ELIGE LA FOTO
        val largeIcon = BitmapFactory.decodeResource(
            context.resources,
            R.drawable.invoice
        )

        notificationIntent = Intent()

        /* Crea PendingIntent */
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(
            context,
            0 /* Request code */,
            notificationIntent,
            PendingIntent.FLAG_ONE_SHOT
        )

        //Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        //Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_notification_icon);

        val channel_id = createNotificationChannel(context)

        val notificationBuilder = NotificationCompat.Builder(context, channel_id!!)
            .setContentTitle(resources.getString(R.string.aviso))
            .setContentText(resources.getString(R.string.seeMeetings))
            .setStyle(NotificationCompat.BigTextStyle().bigText(resources.getString(R.string.seeMeetings)))
            .setLargeIcon(largeIcon)
            .setSmallIcon(R.drawable.ic_add_alert_black_24dp) //needs white icon with transparent BG (For all platforms)
            //.setColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
            .setVibrate(longArrayOf(1000, 1000))
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)
            .setPriority(Notification.PRIORITY_HIGH)
            .setAutoCancel(true)

        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(
            (Date(System.currentTimeMillis()).time / 1000L % Integer.MAX_VALUE).toInt() /* ID of notification */,
            notificationBuilder.build()
        )

    } catch (e: Exception) {
        Log.e("Notificacion", "createNotification::" + e.message)
    }

}

fun createNotificationChannel(context: Context): String? {

    // NotificationChannels are required for Notifications on O (API 26) and above.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        // The id of the channel.
        val channelId = "Channel_id"

        // The user-visible name of the channel.
        val channelName = "Application_name"
        // The user-visible description of the channel.
        val channelDescription = "Application_name Alert"
        val channelImportance = NotificationManager.IMPORTANCE_DEFAULT
        val channelEnableVibrate = true
        //            int channelLockscreenVisibility = Notification.;

        // Initializes NotificationChannel.
        val notificationChannel = NotificationChannel(channelId, channelName, channelImportance)
        notificationChannel.description = channelDescription
        notificationChannel.enableVibration(channelEnableVibrate)
        //            notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);

        // Adds NotificationChannel to system. Attempting to create an existing notification
        // channel with its original values performs no operation, so it's safe to perform the
        // below sequence.
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(notificationChannel)

        return channelId
    } else {
        // Returns null for pre-O (26) devices.
        return null
    }
}

//** EL PARAMETRO FECHA QUE RECIBIMOS LO CONVIERTE EN DATE PARA SER UTILIZADO **
private fun parseFecha(fecha: String): Date {
    val cal = Calendar.getInstance()
    val fechaTotal = fecha.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    val anio = fechaTotal[0].split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    cal.set(Calendar.YEAR, Integer.parseInt(anio[0]))
    cal.set(Calendar.MONTH, Integer.parseInt(anio[1]))
    cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(anio[2]))
    val hora = fechaTotal[1].split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    cal.set(
        Integer.parseInt(anio[2]), Integer.parseInt(anio[1]) - 1,
        Integer.parseInt(anio[0]), Integer.parseInt(hora[0]),
        Integer.parseInt(hora[1]), Character.MIN_RADIX
    )

    return cal.time
}

//** RECORRE LA TABLA MEETING Y SI COINCIDE LA FECHA ACTUAL CON LA FECHA DE LA CITA ABRE UNA NOTIFICACION INDICANDOLO **
@SuppressLint("ObsoleteSdkInt")
private fun recorrerMeting() {

    val db = DataBaseHelper(this)
    val cal = Calendar.getInstance()
    cal.add(Calendar.HOUR, +1); // UNA HORA ANTES DE LA CITA
    var fechaDeMeeting = ""
    for (i in 0..db.meetingsOfAll.size - 1) {

        fechaDeMeeting = db.meetingsOfAll[i].hour + " " + db.meetingsOfAll[i].date
        /*println(" fecha de la base de datos:   " + fechaDeMeeting)
        println(" fecha del sistema ahora mismo:   " + cal.getTime())
        Log.i("MALGO","Fecha del meeting   "+fechaDeMeeting);
        Log.i("MALGO","Fecha del sistema   "+cal.getTime().toString())
        Log.i("MALGO","Fecha del sistema parseada   "+getHoraPedido(cal.getTime()))*/
        if (getHoraPedido(cal.getTime()).equals(getHoraPedido(parseFecha(fechaDeMeeting)))) {
            // SE CONTROLA LA VERSION DE ANDROID, SI ES MAYOR DE OREO TIENE QUE NOTIICARSE DE OTRA FORMA
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                creaNotificacion(this)
            } else{
                creaNotificacion1(0, "", this)
            }

        }
    }
}

private fun getHoraPedido(fecha1: Date): String {
    val fechaFormateada = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault()).format(fecha1)

    return fechaFormateada
}

}
Y luego la llamo en la actividad principal.
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler

    val jobInfo = JobInfo.Builder(11, ComponentName(this@MainActivity, MyJobService::class.java))
        // only add if network access is required
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build()
    jobScheduler.schedule(jobInfo)

    val resultCode = jobScheduler.schedule(jobInfo)
    if (resultCode == JobScheduler.RESULT_SUCCESS) {

    } else {

    }
}

Espero que te sirva de ayuda.

A: Lo que tienes pensado lo puedes lograr con un Servicio en Android, el problema de implementar un servicio es que cuando el dispositivo se encuentra sobrecargado el SO lo desstruye para liberar RAM. Este sería el código para el Servicio
AlarmService.java
public class AlarmService extends Service {

    final static String DATA_BASE_NAME = "alarm_data_base";
    private NotificationCompat.Builder mBuilder;
    private NotificationManager notification;
    private SQLiteDatabase alarmDB;

    @Override
    public void onCreate() {
        super.onCreate();
        //Crear la notificación
        //...
        //Inicalizar la base de datos donde se encuentran las alarmas
        AdminSQLiteOpenHelper sqLiteOpenHelper = new AdminSQLiteOpenHelper(this, DATA_BASE_NAME, null, 1);
        alarmDB = sqLiteOpenHelper.getWritableDatabase();
    }

    /**
     * Este método se ejecuta cuando se inicia o reinicia el proceso, en caso de que
     * Android lo haya finalizado para liberar RAM
     */
    @Override
    public int onStartCommand(Intent intenc, int flags, int idArranque) {
        //Creas un contador de tiempo, el valor 10000 es el intervalo de tiempo en que
        //se llamará al método onTick() en milisegundos, un valor menor hace la alarma más
        //precisa pero sobrecarga un poco más al sistema y puede crear una mala experiencia de ususario
        //en dispositivos con poca RAM
        new CountDownTimer(Long.MAX_VALUE, 10000) {

            @Override
            public void onTick(long millisUntilFinished) {
                //Aquí verificas si hay alguna alarma a esa hora
                showNotification();
            }

            @Override
            public void onFinish() {

            }
        }.start();
        return Service.START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void showNotification() {
        //Obtener la fecha actual en minutos
        int time = getMinutes(new GregorianCalendar());
        Cursor cursor = alarmDB.rawQuery("select alarm_name from alarms where time=" + time, null);
        //Comprobar si en la hora actual hay alguna alarma
        if (cursor.moveToFirst()) {
            //Ejecutar alarma
            mBuilder.setContentText(cursor.getString(0));
            notification.notify(0, mBuilder.build());
        }
        cursor.close();
    }

    /**
     * Convierte la fecha del GregorianCalendar en un int que representa el total de minutos
     *
     * @param calendar Fecha para convertir en minutos
     * @return Total de minutos que han trasncurrido desde el inicio del año hasta la fecha
     * del GregorianCalendar
     */
    public static int getMinutes(GregorianCalendar calendar) {
        int day = calendar.get(Calendar.DAY_OF_YEAR);
        //Total de minutos que trae un día completo
        int dayMin = 1440;
        int minutes = (day * dayMin);
        minutes += calendar.get(Calendar.MINUTE);
        minutes += (calendar.get(Calendar.HOUR_OF_DAY) * 60);
        return minutes;
    }
}

AndroidManifest.xml
<service android:name=".AlarmService"
    android:description="@string/app_name"
    android:enabled="true" android:label="AlarmService" />

Para que no muera el proceso lo mejor es utilizar un Broadcast para lanzar el proceso cada vez que se llame. Para ello utilizarías el Servicio de Alarma por defecto que tiene el SO. Este sería el código:
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //Iniciar el servicio
        Intent background = new Intent(context, AlarmService.class);
        context.startService(background);
    }
}

AndroidManifest.xml
<receiver android:name=".AlarmReceiver">
    <intent-filter>
        <action android:name="REFRESH_SERVICE" />
    </intent-filter>
</receiver>

Por último en la actividad de la alarma debes instanciar el Bradcast para que se ejecute a la par con el sevicio de alarma del SO.
MainActivity.java
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Iniciar el Broadcast para que no muera el proceso
        String alarm = Context.ALARM_SERVICE;
        AlarmManager alarmManager = (AlarmManager) getSystemService(alarm);
        Intent intent = new Intent("REFRESH_SERVICE");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 123456789, intent, 0);
        int type = AlarmManager.RTC_WAKEUP;
        //Intervalo de tiempo en millisegundos que se ejecutará onReceive en el BroadCast
        long interval = 60000;
        alarmManager.setRepeating(type, System.currentTimeMillis(), interval, pendingIntent);
    }
}

Espero haberte ayudado con esto. Sólo debes añadir las alarmas a la base de datos usando la fecha convertida en minutos con el método getMinutes () y listo.


text:
Q: How to limit access to .zip files to all but a specific folder with .htaccess I have a download site where I blocked access to .zip files in order to force users to go through my download process (simply means u have to register before you download).
Now I am also making a java arcade and I want the applet to be able to download zip files from a specific directory on it and play them.
Right now I am using something like in my site's root .htaccess:
RewriteRule .*\.(zip)$ http://www.google.com [R,NC]

The question is how do I tell it not to include the folder "arcade" in it.
What do I modify in the above code or what do I put in the arcade/.htaccess file to make it possible to link to zips..
Thanks!
 - Ben

A: Try
#exclude the arcade folder
RewriteCond %{REQUEST_URI} !^/arcade [NC]
RewriteRule .*\.(zip)$ http://www.google.com [R,NC]

Instead of the redirect you could also give a 404 as below. Also simplified the match for the RewriteRule
RewriteCond %{REQUEST_URI} !^/arcade [NC]
RewriteRule  \.zip$ - [R=404,NC]

A: You should use the RewriteCond directive. You need something like:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/arcade/
RewriteRule \.zip$ - [F]

I have also changed the way you block access to .zip files. It's better to return a 403 error code.


text:
Q: Is it possible to copy a dev. database schema over a prod. one, but keep the prod. database' data? I'm using MySQL 5.6.  I have a production database and a development database.
As I'm developing the application, I sometimes need to add new columns/tables to the database.  Is it possible, when I'm ready to update the production database, to take the dev. schema and "lay it over" the production schema, but let the production server keep its data?
Currently, I'm just using mysqldump and dumping out the whole database, and then copying it over the top of the other.  It's working at the moment because the app isn't entirely in production mode, yet, but it's not gonna work forever.

A: To do this in any automated manner, you need to change your development model. Instead of just keeping the dev database as the current state and using a dump of its structure to build new databases, you should instead create scripts that transform one database version to the next - adding/dropping/altering objects as needed, and transforming data as required by those changes (new columns may need initial values, moving data to a new structure before dropping and old one, etc.). These scripts should be kept in good source control of course.
This way you can take your production database (at, say, version 2.5) and to get it up to the current development release (say, 2.8) apply the upgrade scripts for 2.5->2.6, 2.6->2.7, 2.7->2.8. Of course you can test this process in a test environment first as it should be repeatable (reset test environment to match current production, upgrade, test the application, fix upgrade scripts if something fails, repeat until everything is OK).
At some point this process will become inefficient for creating brand new databases for other instances of the application (i.e. building from the very first version onwards may become unwieldy after time) so you'll want to refactor the process slightly, picking a new starting point and building from there each time.
There are tools to help with the more manual process that you describe, but you will be much better off in the long run not arranging your release process around less automatable actions for managing schema changes. Setting up the process may seem like hassle, but it is a lot easier to do at this stage than after you have real production environments to worry about.

A: In order to synchronize(check database, object and data) the dev database with the production env you can take a look into the MySQL Utilities on these tools:

*

*mysqldbcompare

*mysqldiff
Currently I'm working frequently with the first one obtaining good results and saving time... keep in mind that you have to check the result before apply them to the destination database(there are some little bugs in some scenario with unique keys on multiple columns and other)
You can start using these tools with two test database in order to become familiar.


text:
Q: Сетевые точки безопасности На экзамене попался теоретический вопрос "Сетевые точки безопасности". Не совсем понимаю, что именно подразумевается под этим словосочетанием. Про что именно писать?
Заранее спасибо^-^

A: Подозреваю что этот термин придумал ваш преподаватель. Сам преподаю ИБ как специальность, но такого термина не слышал :)
Но могу предположить пару вариантов:

*

*Возможно это точки обмена с внешней средой, так же называемые внешним сетевым периметром безопасности, на пример такой точкой в вашей сети может быть маршрутизатор (или группы маршрутизаторов) через который осуществляется доступ к сети Интернет;

*Так же ваш преподаватель этим термином мог называть конкретное инженерно-техническое средство осуществления корпоративной политики информационной безопасности, на пример какой-то сертифицированный государством или какой-то организацией маршрутизатор;

*Ну и как вариант, композицию двух вышеперечисленных объектов сетеобразующих устройств, на пример такую как DMZ (демилитаризованную зону организованную несколькими маршрутизаторами/межсетевыми экранами);

*И последнее, возможно самое простое решение - самое верное. Ваш преподаватель мог иметь под этим термином любой сетевой сервис доступный из внешней сети и требующий обеспечения информационной безопасности, а значит внимания со стороны специалистов ИБ.


text:
Q: Any Plugin or suggested Design for user to perform an Custom action on Wordpress content I need to make a Wordpress website having lots of recipes.User will be allowed to read and click on "Cooked" button associated with that particular Article. I would like to store who all user have Cooked that recipe and show it when I am showing the Recipe.
Is there any plugin available which can store User Activities on content(like we have comments plugin) or else what should be the best way to do this?

A: Take a look at WP Favorite Posts plugin which allows visitors to add favorite posts.
and set the label as "Cooked" instead of "add to favorites" , this will be the easiest way to do it but if you are up for some custom coding then it's simply a matter of saving the recipe post id in the user meta using update_user_meta


text:
Q: How to render emojis as images in Python under Windows? My goal is to generate (in Python under Windows) a bitmap image rendering any unicode character, including in particular emojis. I have installed several emoji-friendly fonts (including Symbola) for testing purpose.
So far I've tried PIL, matplotlib and pygame, but none of these are able to do it under Windows (the first two apparently can do it on some versions of Linux / MacOS, while pygame is explicitly limited to characters up to 0xffff, which rules out emojis).
I found that reportlab is able to generate a PDF with emojis (while its bitmap renderer fails to properly render them), but I still need to find a way to extract the emoji character from the PDF and convert it to bitmap. I feel like there has to be a simpler way...
NB: this question is related to Rendering Emoji with PIL but I do not necessarily want to use PIL if another library can do the job

A: I eventually found a solution in Is there any good python library for generating and rendering text in image format?. Although it is based on a third-party executable, as mentioned it is easy to wrap in Python.
Exact steps were as follows:

*

*Install ImageMagick from https://www.imagemagick.org/script/download.php#windows

*Set environment variable MAGICK_HOME to installation folder

*Install Pillow to be able to manipulate easily the resulting image in Python (conda install pillow)

*Download and install the Symbola font from https://fontlibrary.org/en/font/symbola
And my test script:
import os
import subprocess

import PIL.Image

to_render = ''
output_file = 'rendered_emoji.bmp'

subprocess.run([
    os.path.join(os.environ['MAGICK_HOME'],  'magick.exe'),
    'convert', '-font', 'Symbola', '-size', '50x50',
    '-gravity', 'center', f'label:{to_render}', output_file])
image = PIL.Image.open(output_file)
image.show()


text:
Q: Can't connect: POP3 connection broken in response I am trying to download the attachments from a gmail account but am failing so far.
I have tried some IMAP snippet but had this error:
Cannot connect to Gmail: Can't open mailbox {imap.gmail.com:993/imap/ssl}INBOX: invalid remote specification

So decided to give POP a try but gave this error:
Can't connect: POP3 connection broken in response

The code i found for POP was:
if( $mbox = imap_open("{pop.gmail.com:995/pop3}INBOX", "me@gmail", "mypassword")){
$path = "saved_email_docs";
$check = imap_mailboxmsginfo($mbox);
function getmsg($mbox,$mid) {
    global $charset,$htmlmsg,$plainmsg,$attachments,$from,$to,$subj,$timages,$path;
    $htmlmsg = $plainmsg = $charset = '';
    $attachments = array();
    // HEADER
    $h = imap_headerinfo($mbox,$mid);
    // add code here to get date, from, to, cc, subject...
    $date = $h->date;
    $from = $h->fromaddress;
    $to = $h->toaddress;
      $subj = htmlspecialchars($h->Subject);
    // BODY
    $s = imap_fetchstructure($mbox,$mid);
    if (!$s->parts)  // simple
    getpart($mbox,$mid,$s,0);  // pass 0 as part-number
    else {  // multipart: cycle through each part
    foreach ($s->parts as $partno0=>$p)
      getpart($mbox,$mid,$p,$partno0+1);
    }
}

function getpart($mbox,$mid,$p,$partno) {
    // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
    global $htmlmsg,$plainmsg,$charset,$attachments,$partid,$last_mail_id,$patterns,$pic,$newstr,$c,$ok,$timages,$subj,$path;
    $patterns = array();
    $pic =  array();
    $image=array();
    $data = ($partno) ? imap_fetchbody($mbox,$mid,$partno) : imap_body($mbox,$mid);  // simple
    if ($p->encoding==4)
    $data = quoted_printable_decode($data);
    else if ($p->encoding==3)
    $data = base64_decode($data);
    // PARAMETERS    // get all parameters, like charset, filenames of attachments, etc.
    $params = array();
    if ($p->parameters)
    foreach ($p->parameters as $x)
        $params[strtolower($x->attribute)] = $x->value;
    if ($p->dparameters)
    foreach ($p->dparameters as $x)
        $params[strtolower($x->attribute)] = $x->value;

    // ATTACHMENT    // Any part with a filename is an attachment,
    // so an attached text file (type 0) is not mistaken as the message.
    if ($params['filename'] || $params['name']) {
    $partid = htmlentities($p->id,ENT_QUOTES);

       // filename may be given as 'Filename' or 'Name' or both
    $filename = ($params['filename'])? $params['filename'] : $params['name'];
    // filename may be encoded, so see imap_mime_header_decode()
     $attachments[$filename] = $data;  // this is a problem if two files have same name
    //store id and filename in array
    $image[$key] = $filename;

    }
    //save the attachments in the directory
    foreach( $attachments as $key => $val){
      $fname = $key;
      $fp = fopen("$path/$fname","w");
      fwrite($fp, $val);
      fclose($fp);
    }
        // TEXT
        if ($p->type==0 && $data) {
        // Messages may be split in different parts because of inline attachments,   // so append parts together with blank row.
        if (strtolower($p->subtype)=='plain')
            $plainmsg .= trim($data)."\n\n";
        else
            //preg_match_all('/]+>/i',$data, $result);
            $htmlmsg .= $data."

";
            $charset = $params['charset'];  // assume all parts are same charset
        }

    // There are no PHP functions to parse embedded messages, so this just appends the raw source to the main message.
    else if ($p->type==2 && $data) {
    $plainmsg .= $data."\n\n";
    }
    // SUBPART RECURSION
    if ($p->parts) {
    foreach ($p->parts as $partno0=>$p2)
        getpart($mbox,$mid,$p2,$partno.'.'.($partno0+1));  // 1.2, 1.2.1, etc.
    }
}

$attachments = array();
$num_msg = imap_num_msg($mbox);
if($num_msg>0) {
    getmsg($mbox,1);
}else {
     echo "Sorry!...No Messages in MailBox...
";
}

//imap_delete and imap_expunge are used to delete the mail after fetching....Uncomment it if you want to delete the mail from mailbox
//imap_delete($mbox,1);
//imap_expunge($mbox);
imap_close($mbox);

}
else { exit ("Can't connect: " . imap_last_error() ."\n");  echo "FAIL!\n";
}

Any ideas?


text:
Q: Convert SDO_ORDINATE_ARRAY to built-in VARRAY (to create function-based index) Oracle 18c:
I can get SDO_ORDINATE_ARRAY values from SDO_GEOMETRY objects:
create table test_table (shape sdo_geometry);

insert into test_table (shape) values (sdo_geometry('linestring(10 20, 30 40, 50 60)'));
insert into test_table (shape) values (sdo_geometry('linestring(70 80, 90 100)'));
insert into test_table (shape) values (sdo_geometry('linestring(110 120, 130 140, 150 160, 170 180)'));

select
    (shape).sdo_ordinates as sdo_ordinate_array
from
    test_table

SDO_ORDINATE_ARRAY
------------------
MDSYS.SDO_ORDINATE_ARRAY(10, 20, 30, 40, 50, 60)
MDSYS.SDO_ORDINATE_ARRAY(70, 80, 90, 100)
MDSYS.SDO_ORDINATE_ARRAY(110, 120, 130, 140, 150, 160, 170, 180)

db<>fiddle
For what it's worth, this is what the definition of the MDSYS.SDO_ORDINATE_ARRAY type looks like in SQL Developer:
create or replace TYPE SDO_ORDINATE_ARRAY AS VARRAY(1048576) OF NUMBER

Using a function, I want to convert the SDO_ORDINATE_ARRAYs to the built-in VARRAY datatype.
Reason: I want to experiment with storing the ordinates in a non-spatial Function-Based Index. If I understand correctly, only built-in datatypes are supported by FBIs, not Oracle-supplied types or abstract datatypes like SDO_ORDINATE_ARRAY or SDO_GEOMETRY.

*

*Idea: Support function-based indexes on Abstract datatypes.

*Function-based spatial indexes don't help me in this case either, since I want to utilize the index using the SELECT list of a query, not in a spatial operation in the WHERE clause. Why can't a spatial index be invoked by the SELECT list, yet a non-spatial index can?
For example, if I were to try to create the following FBI, it would fail:
create index sdo_ordinates_idx on test_table ((shape).sdo_ordinates);

Error:
Error starting at line : 12 in command -
create index sdo_ordinates_idx on test_table ((shape).sdo_ordinates)
Error report -
ORA-02327: cannot create index on expression with datatype ADT     ADT=Abstract Datatype
02327. 00000 -  "cannot create index on expression with datatype %s"
*Cause:    An attempt was made to create an index on a non-indexable
           expression.
*Action:   Change the column datatype or do not create the index on an
           expression whose datatype is one of  VARRAY, nested table, object,
           LOB, or  REF.

So I can't create an FBI on SDO_ORDINATE_ARRAY. But I'm hoping I can convert the ordinates to a regular VARRAY instead and make an FBI on those values.

Question:
Is there a way to convert SDO_ORDINATE_ARRAYs to built-in VARRAYs? (for the purpose of a function-based index)
I would prefer to store the ordinates as a proper VARRAYs, rather than convert them to text. Reason: I believe the SDO_GEOMETRY constructor only accepts array values, not text.

A: You state:

the definition of the MDSYS.SDO_ORDINATE_ARRAY type looks like in SQL Developer:
create or replace TYPE SDO_ORDINATE_ARRAY AS VARRAY(1048576) OF NUMBER

and then ask:

Is there a way to convert SDO_ORDINATE_ARRAYs to built-in VARRAYs? (for the purpose of a function-based index)

It is already a VARRAY, you do not need to convert it.
However
The error message states:

Error report -
ORA-02327: cannot create index on expression with datatype ADT     > ADT=Abstract Datatype
02327. 00000 -  "cannot create index on expression with datatype %s"
*Cause:    An attempt was made to create an index on a non-indexable
           expression.
*Action:   Change the column datatype or do not create the index on an
           expression whose datatype is one of VARRAY, nested table, object,
           LOB, or  REF.

In the action section it specifically states that you cannot create an index on an expression whose datatype is one of VARRAY or nested table. So what you are asking is impossible; you cannot create an index on a VARRAY.
Finally
You state:

I would prefer to store the ordinates as a proper VARRAYs, rather than convert them to text. Reason: I believe the SDO_GEOMETRY constructor only accepts array values, not text.

Looking at the source:
select text
from   all_source
where  type  = 'TYPE'
and    owner = 'MDSYS'
and    name  = 'SDO_GEOMETRY'
ORDER BY line

The MDSYS_SDO_GEOMETRY type has the constructors:

   ADD CONSTRUCTOR FUNCTION SDO_GEOMETRY(wkt IN CLOB,
     srid IN INTEGER DEFAULT NULL) RETURN SELF AS RESULT
     DETERMINISTIC PARALLEL_ENABLE,
   ADD CONSTRUCTOR FUNCTION SDO_GEOMETRY(wkt IN VARCHAR2,
     srid IN INTEGER DEFAULT NULL) RETURN SELF AS RESULT
     DETERMINISTIC PARALLEL_ENABLE,
   ADD CONSTRUCTOR FUNCTION SDO_GEOMETRY(wkb IN BLOB,
     srid IN INTEGER DEFAULT NULL) RETURN SELF AS RESULT
     DETERMINISTIC PARALLEL_ENABLE,
   ADD CONSTRUCTOR FUNCTION SDO_GEOMETRY(input_clob IN clob,
     auxiliary_info IN varchar2, crs IN VARCHAR2 DEFAULT NULL)
     RETURN SELF AS RESULT DETERMINISTIC PARALLEL_ENABLE,
   ADD CONSTRUCTOR FUNCTION SDO_GEOMETRY(input_vchar IN varchar2,
     auxiliary_info IN varchar2, crs IN VARCHAR2 DEFAULT NULL)
     RETURN SELF AS RESULT DETERMINISTIC PARALLEL_ENABLE
   CASCADE

None of those constructors take a VARRAY argument. They all take strings (VARCHAR2 or CLOB) except for one that takes a BLOB.
db<>fiddle here


text:
Q: How do I repeat an included .tex file multiple times? I would like to repeat a file in a LaTeX document multiple times:
\include{probenahme/sample}
\include{probenahme/sample}
\include{probenahme/sample}
\include{probenahme/sample}
\include{probenahme/sample}

However, if I compile the main document with latexmk -pdf main-document.tex, It will throw the following error:
 level-1 auxiliary file: probenahme/sample.aux
Already encountered file probenahme/sample.aux
---line 26 of file probenahme.aux
 : \@input{probenahme/sample.aux
 :                              }
I'm skipping whatever remains of this command
Already encountered file probenahme/sample.aux
---line 27 of file probenahme.aux
 : \@input{probenahme/sample.aux

...

*

*It works fine with a single \include{probenahme/sample}

*It works if I run pdflatex main-document.tex instead of latexmk -pdf main-document.tex

*I don't want to use the latexmk -f option because it runs in a continuous integration environment and I want that to catch other errors.

What is the problem and how do I solve it while still using latexmk?

A: You can not need \include functionality here as there is no way to use \includeonly to specify just one of the inclusions as they have the same name.
So use \input not \include then you can input the file as often as you like.


text:
Q: Changing the definition of N: unexpected $RecursionLimit::reclim error I have some objects represented as follows:
Object[data, param]

data is a list of numbers, param is an integer.
Somewhere in my program, I need to do something like that:
pseed = N[seed, prec];

In this context, seed can be either a number or my object Object. When seed is an Object I want N to be applied only to data list. But N is applied to param too, which I want always to be an Integer.
Of course, I could write:
pseed = If[Head[seed] === Object,
  MapAt[N[#, prec]&, seed, 1],
  N[seed, prec]
];

But I believe, this would make my code messy and hard to read. Therefore I decided to do something like that:
Unprotect[N];
N[Object[data_List, param_Integer], p_] := Object[N[data, p], param];
Protect[N];

Than the simple N[seed, prec] should work whether seed is Obj or Number. However, I get the following error:
$RecursionLimit::reclim: Recursion depth of 1024 exceeded.

I cannot understand, where do I have a recursion?
Thanks in advance!

Update. I have received the answer from Wolfram Support:

I understand you believe you've found a bug with N.
In this case, Mathematica is behaving as designed. N is a fairly complicated function and changing its definition arbitrarily by using the Unprotect function can lead to unforeseen consequences. While the definition we provide works as designed, the change you made to it does not behave as you expect. The TagSet and TagSetDelayed function was supplied to address just the kind of problem you are trying to solve. Try
In[1]:= f/:Verbatim[N][f[arg1_,otherArgs__]]:=f[N[arg1],otherArgs]
In[2]:= N[f[1,2]]
Out[2]= f[1.,2]

Alternatively, you can avoid the need for the Verbatim function by injecting a secondary step:
In[1]:= f/:NN[f[arg1_,args__]]:=f[NN[arg1],args]
In[2]:= NN[arg1_]:=N[arg1]
In[3]:= NN[f[1,2]]
Out[3]= f[1.,2]

Setting up the dummy function can even allow you to avoid the need for the TagSetDelayed:
In[1]:= NN[f[arg1_,args__]]:=f[N[arg1],args]
In[2]:= NN[f[1,2]]
Out[2]= f[1.,2]

For more on TagSet, TagSetDelayed and Verbatim, please see
http://reference.wolfram.com/language/ref/TagSet.html
http://reference.wolfram.com/language/ref/TagSetDelayed.html

The question seems to be solved. Thank everybody for participation!

A: The recursion limit error which you observe looks like a bug in N. Here is a shorter code to reproduce the issue:
N[obj[args__]] := obj[args]
N@obj[1, 2, 3]

During evaluation of In[2]:= $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>

obj[1, 2, 3]

In the comments Oleksandr R. provided a workaround via combined usage of Verbatim and UpValues:
ClearAll[Object];
Object /:
 Verbatim[N][Object[arg1_, arg2_, argRest__],
  Narg : _ | PatternSequence[]] :=
 Object[arg1, N[arg2, Narg], argRest]

If you wish N to affect only the first argument of Object, it is sufficient just to set the NHoldRest attribute:
ClearAll[Object];
SetAttributes[Object, NHoldRest]

Now
N@Object[1, 1]

Object[1., 1]