text:
Q: delphi convert gif to png with transparency I am trying to convert a gif to png, that's easy, but the problem is the result image is not transparent, also I would like to have in the png image the alpha channel.
This is my code:
procedure TForm1.Button1Click(Sender: TObject);
var
png: TPngImage;
 p : TPicture;
begin
 p := TPicture.Create;
 p.LoadFromFile('C:\temp\php.gif');
 png := TPngImage.CreateBlank(COLOR_RGB , 8, p.Width, p.Height);
 png.Canvas.Draw(0,0, p.Graphic);
 png.SaveToFile('C:\Windows\Temp\test.png');
end;

The new picture has the background black, should be transparent.
If I try to add the ALPHA in the constructor, is 100% transparent.
png := TPngImage.CreateBlank(COLOR_RGBALPHA , 8, p.Width, p.Height);

A: Since Delphi XE 2 GDI+ is supported, which offers real easy to use options for conversions.
You just need to create TGPImage providing the image file to load and save this image with the wished encoder, found by the desired mime type.
uses Winapi.GDIPAPI, Winapi.GDIPOBJ, Winapi.GDIPUTIL;

procedure TForm8.Button1Click(Sender: TObject);
var
  encoderClsid: TGUID;
  stat: TStatus;
  IMG: TGPImage;
begin
  IMG := TGPImage.Create('C:\temp\transparent.gif');
  try
    GetEncoderClsid('image/png', encoderClsid);
    stat := IMG.Save('C:\temp\transparent.png', encoderClsid, nil);
  finally
    IMG.Free;
  end;
  if (stat = Ok) then
    Showmessage('Success');
end;

examples for the mime types:
image/bmp
image/jpeg
image/gif
image/tiff
image/png

A: Just by drawing GIF image on PNG canvas will not move transparency information from GIF image to PNG.
You will have to do it yourself.
ForceAlphaChannel procedure will create alpha channel for any PNG image based on given TransparentColor.
procedure ForceAlphaChannel(Image: TPngImage; BitTransparency: Boolean; TransparentColor: TColor; Amount: Byte);
var
  Temp: TPngImage;
  x, y: Integer;
  Line: VCL.Imaging.PngImage.pByteArray;
  PixColor: TColor;
begin
  Temp := TPngImage.CreateBlank(COLOR_RGBALPHA, 8, Image.Width, Image.Height);
  try
    for y := 0 to Image.Height - 1 do
      begin
        Line := Temp.AlphaScanline[y];
        for x := 0 to Image.Width - 1 do
          begin
            PixColor := Image.Pixels[x, y];
            Temp.Pixels[x, y] := PixColor;
            if BitTransparency and (PixColor = TransparentColor) then Line^[x] := 0
            else Line^[x] := Amount;
          end;
      end;
    Image.Assign(Temp);
  finally
    Temp.Free;
  end;
end;

If you add call to ForceAlphaChannel after you have drawn GIF image you will get transparency based on transparent color you define.
procedure TForm1.Button1Click(Sender: TObject);
var
png: TPngImage;
 p : TPicture;
 TransparentColor: TColor;
begin
 p := TPicture.Create;
 p.LoadFromFile('C:\temp\php.gif');
 TransparentColor := clFuchsia;
 png := TPngImage.CreateBlank(COLOR_RGB , 8, p.Width, p.Height);
 // set png background color to same color that will be used for setting transparency
 png.Canvas.Brush.Color := TransparentColor;
 png.Canvas.FillRect(rect(0, 0 , p.Width, p.Height));
 png.Canvas.Draw(0, 0, p.Graphic);
 ForceAlphaChannel(png, true, TransparentColor, 255);
 png.SaveToFile('C:\Windows\Temp\test.png');
end;

A: For older/new Delphi versions (in newer version - change TPngObject to TPngImage).
If you need to save every frame of (animated) GIF into PNG (works for non-animated GIFS also):
The first variant code is compatible with the newer pngimage Version 1.56+ (which supports the CreateBlank constructor)
procedure TForm1.Button1Click(Sender: TObject);
var
  Gif: TGifImage;
  Png: TPngObject; // for new Delphi versions use "TPngImage"
  Bmp: TBitmap;
  TransparentColor, Pixel: TColor;
  I, X, Y: Integer;
  AlphaScanline: pByteArray;
  IsTransparent: Boolean;
  ColorType: Cardinal;
begin
  Gif := TGifImage.Create;
  try
    Gif.LoadFromFile('C:\Downloads\ajax-loader.gif');
    for I := 0 to Gif.Images.Count - 1 do
    begin
      IsTransparent := Gif.Images[I].Transparent;
      TransparentColor := Gif.Images[I].GraphicControlExtension.TransparentColor;
      Bmp := Gif.Images[I].Bitmap;
      if IsTransparent then
        ColorType := COLOR_RGBALPHA
      else
        ColorType := COLOR_RGB;
      Png := TPngObject.CreateBlank(ColorType, 8, Bmp.Width, Bmp.Height); // for new Delphi versions use "TPngImage"
      try
        AlphaScanline := nil;
        for Y := 0 to Bmp.Height - 1 do
        begin
          if IsTransparent then
            AlphaScanline := Png.AlphaScanline[Y];
          for X := 0 to Bmp.Width - 1 do
          begin
            Pixel := Bmp.Canvas.Pixels[X, Y];
            Png.Pixels[X, Y] := Pixel;
            if IsTransparent then
            begin
              if (Pixel = TransparentColor) then
                AlphaScanline^[X] := 0
              else
                AlphaScanline^[X] := 255;
            end;
          end;
        end;
        Png.SaveToFile(Format('%d.png', [I]));
      finally
        Png.Free;
      end;
    end;
  finally
    Gif.Free;
  end;
end;

For old pngimage version before 1.56 which do not support TPngObject.CreateBlank:
procedure TForm1.Button2Click(Sender: TObject);
var
  Gif: TGifImage;
  Png: TPngObject; // for new Delphi versions use "TPngImage"
  Bmp: TBitmap;
  TransparentColor, Pixel: TColor;
  I, X, Y: Integer;
  AlphaScanline: pByteArray;
  IsTransparent: Boolean;
begin
  Gif := TGifImage.Create;
  try
    Gif.LoadFromFile('C:\Downloads\ajax-loader.gif');
    for I := 0 to Gif.Images.Count - 1 do
    begin
      IsTransparent := Gif.Images[I].Transparent;
      Png := TPngObject.Create; // for new Delphi versions use "TPngImage"
      try
        if IsTransparent then
        begin
          Bmp := TBitmap.Create;
          Bmp.Assign(Gif.Images[I].Bitmap);
          Bmp.PixelFormat := pf24bit;
          Png.Assign(Bmp);
          Png.CreateAlpha;
          TransparentColor := Gif.Images[I].GraphicControlExtension.TransparentColor;
          for Y := 0 to Bmp.Height - 1 do
          begin
            AlphaScanline := Png.AlphaScanline[Y];
            for X := 0 to Bmp.Width - 1 do
            begin
              Pixel := Png.Pixels[X, Y];
              if (Pixel = TransparentColor) then
                AlphaScanline^[X] := 0;
            end;
          end;
          Bmp.Free;
        end
        else
          Png.Assign(Gif.Images[I].Bitmap);
        Png.SaveToFile(Format('%d.png', [I]));
      finally
        Png.Free;
      end;
    end;
  finally
    Gif.Free;
  end;
end;


text:
Q: ALSA Audio throw an erorr I run a python program that use pyaudio and try to use my computer microphone and speaker, but I got this erorr
ALSA lib pcm.c:2660:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2660:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2660:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
voice-transformation$ python: src/hostapi/alsa/pa_linux_alsa.c:3636: PaAlsaStreamComponent_BeginPolling: Assertion `ret == self->nfds' failed.
Aborted (core dumped)

And this is my python code for starting the stream
    def start(self):
        if self.in_stream is not None and self.out_stream is not None:
            return
        try:
            # Initialize PyAudio for Output
            self.p_out = pa.PyAudio()
            self.out_stream = self.p_out.open(
                format=self.FORMAT,
                channels=self.CHANNEL_OUTPUT,
                rate=self.RATE,
                output=True,
                frames_per_buffer=self.CHUNK,
            )
            self.out_stream.start_stream()

            # Initialize PyAudio for Input
            self.p = pa.PyAudio()
            self.in_stream = self.p.open(
                format=self.FORMAT,
                channels=self.CHANNEL_INPUT,
                rate=self.RATE,
                input=True,
                frames_per_buffer=self.CHUNK,
                stream_callback=self._process_stream,
            )
            self.in_stream.start_stream()
            # while self.in_stream.is_active():
            #     time.sleep(0.1)
        except KeyboardInterrupt:
            self.stop()
            pass

Is it the erorr from my computer audio for it is from python program?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Command failed: "C:\xampp\htdocs\cordova-test\node_modules\.bin\webpack.cmd" I'm beginner at Cordova. I've just started to learn it some days ago. When I try to build my Cordova app, I get this error:
Error: Command failed: "C:\xampp\htdocs\cordova-test\node_modules\.bin\webpack.cmd".
How can I fix it? I found one solution of this problem (deleting of package-lock.json and then npm install again), but it didn't help.

A: I fixed that removing my node_modules folder and my package.json.
Then -> npm init
and reinstall the packages that you need.


text: Q: emacs reftex reftex-create-bibtex-file ignores cites with optional arguments Emacs reftex has a command reftex-create-bibtex-file that searches the current .tex file and creates a bibliography (.bib) of all cited works. The problem is, that while it picks up \cite{foo} it doesn't spot \cite[bar]{foo} which is annoying. Is there a way to make this function recognise (and ignore) option arguments on cite macros?


text:
Q: How to print page without print preview from Stimulsoft in Web Api I want to run the print order when I type this url and print my desired document.
This is the url that calls this method:
http://localhost:9090/api/printPage
Api method
[HttpGet]
[Route("PrintPage")]
public boolean PrintPage()
{
    try
    {
        var p = new List<Person>()
        {
            new Person() {Id = 1, FirstName = "omid", LastName = "nasri", Gender = true}
            , new Person() {Id = 2, FirstName = "hana", LastName = "akbari", Gender = false}
            , new Person() {Id = 3, FirstName = "ali", LastName = "jahani", Gender = true }
            , new Person() {Id = 4, FirstName = "sara", LastName = "sabori", Gender = false }
        };

        var mainReport = new StiReport();

        mainReport.Load(@"D:\WebSite\Web\Print\Report.mrt");
        mainReport.RegBusinessObject("persons" , p);

        mainReport.Print(false);

        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

I use stimulsoft 2012.1.


text:
Q: When the second time using JQuery ajax to get local .HTML content, the js of the index.html is invalid I am sorry for my poor English...
Now I doing phonegap development.
I want to use JQuery ajax to get local .HTML content and insert this content into the div by id="next-page" in index.html.  And the first time I click the btn  it's everything OK.But when
the second time I click the btn,It can be jump to page, but the class of the query listview、li is missing. I think it's the jquery.js and jquery-mobile.js invalid.
Can anyone help me?
Thanks!
This is my index.html
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<title>demo</title>
<link rel="stylesheet"  href="jquery.mobile-1.0.css" />
<link rel="stylesheet" href="css/chui.css"/>
<link rel="stylesheet" href="index.css"/>

Carrier

This is my other.html

    Back

AAAAAAAAAAAAAAAAA

BBBBBBBBBBBB

AAAAAAAAAAAAAAAAA

BBBBBBBBBBBB

AAAAAAAAAAAAAAAAA

This is the Response method when "first-btn" click.
$.ajax({
           url:"carrier.html",
           async:true,
           type:'Get',
           dataType:'html',
           timeout:5000,
           error:function(data){showAlert('Error loading data')},
           success:function(data){
           console.log(data);
           $("#next-page").html(data);
           $.mobile.changePage($("#next-page"),{transition:"slide"});
   })

A: I am not sure I understand correctly.  Are you saying the second time you click the button, the content of the AJAX call shows up on the page, but it is not formatted correctly?
If that is the case, it is probably because you need to call
$('#carrier').listview('refresh');

after injecting a new listview ul dynamically.
That being said, there are other issues with your approach, but the above should fix your immediate issue.


text:
Q: Why does this function cause a Maximum recusion error? I have a very simple function in python that I made while using codecademy.com. The code passed the exercise but it does cause a maximum recursion error and I do not understand why. This is what I have:
n = [3, 5, 7]

def double_list(x):
    for i in range(0, len(x)):
        x[i] = x[i] * 2
    return double_list(x)

print double_list(n)

A: Because in your double_list you are calling double_list again?
return double_list(x)

That will cause you to enter the endless loop unless you set a condition in which it should break upon.
OP already solved it, and this is his solution:
n = [3, 5, 7]

def double_list(x):
    for i in range(0, len(x)):
        x[i] = x[i] * 2
    return x

print double_list(n)

A: You forgot a base case. Every recursive function should have a base case. It keeps calling itself and hence reaches the max depth.
The line
return double_list(x)

calls the same function again and again.


text:
Q: Check if element is in a tree I need to write a function in Lisp that checks if an element N is in a tree TREE.
(defun TREE-CONTAINS (N TREE)
    (cond ((equal TREE nil) nil)
        ((listp (CAR TREE)) (or (TREE-CONTAINS(N (CAR TREE)))
                                (TREE-CONTAINS(N (CDR TREE)))))
        (t (cond ((equal N (CAR TREE)) t)
                  (t TREE-CONTAINS(N (CDR TREE)))))
    )
)

For example, (TREE-CONTAINS (1 ((1  2 3) 4 5))) will return true. But I keep getting an error that says "Undefined function N called with arguments ((2 3))" when I test my code with this example: (TREE-CONTAINS 2 '(1 2 3)). Of course N is supposed to be 1 here but I don't know why it thinks N is a function. Any idea?

A: In the call to tree-contains, or any lisp function, you should not include parentheses around the arguments. It's (function-name arg1 arg2), not (function-name (arg1 arg2)).
So for a start, remove the parentheses around the arguments to the call (tree-contains(n (car tree))) like so: (tree-contains n (car tree)). Similarly for the next call to tree-contains in that or clause. Besides, the last condition: (t TREE-CONTAINS(N (CDR TREE))) should be called like this: (t (tree-contains n (cdr tree))).


text:
Q: Accidentally removed my entire taskbar. How do I get it back? (Kubuntu 18.04) Ok. I somehow ended up with a Chromium icon right beside ...whatever Kubuntu calls the Start button on taskbar on the bottom. In trying to remove that, the entire thing is now gone and pressing the windows key on the keyboard no longer brings up the app launcher thing.

A: right click desktop and add panel?


text:
Q: Android Notifications not showing up in one device The notification appears in 2 devices(Xiaomi, Vivo) both >26 SDK. But it doesnt show up on my Samsung device which is also >26.
This is how i implemented the notification
private NotificationManager mNotificationManager1;

public void CreateMessage(String name,String message, Context context){
        SharedPreferences prefs = context.getSharedPreferences(Activity.class.getSimpleName(), Context.MODE_PRIVATE);
        int notificationNumber = prefs.getInt("notificationNumber", 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context, "Finderr_channel_id1");

        mNotificationManager1 =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            String channelId1 = "Finderr_channel_id1";
            NotificationChannel channel = new NotificationChannel(
                    channelId1,
                    "Finderr Message",
                    NotificationManager.IMPORTANCE_DEFAULT);
            mNotificationManager1.createNotificationChannel(channel);
            mBuilder.setChannelId(channelId1);
        }

        Intent ii = new Intent(context, NotificationHandler.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, ii, 0);

        NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
        bigText.bigText(name + " sent you a message!");
        bigText.setBigContentTitle(name);
        bigText.setSummaryText(message);

        mBuilder.setContentIntent(pendingIntent);
        mBuilder.setSmallIcon(R.drawable.ic_logo_small);
        mBuilder.setContentTitle(name);
        mBuilder.setContentText(message);
        mBuilder.setPriority(Notification.PRIORITY_MAX);
        mBuilder.setStyle(bigText);

        mNotificationManager1.notify(notificationNumber, mBuilder.build());

        SharedPreferences.Editor editor = prefs.edit();
        notificationNumber++;
        editor.putInt("notificationNumber", notificationNumber);
        editor.commit();
    }

I have used shared-preferences to track count of my notifications, so that every message stacks up with previous one. Although, not even 1 notification shows up.

A: How many times do you call CreateMessage method?
This code is suppose to be called only once for your application:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            String channelId1 = "Finderr_channel_id1";
            NotificationChannel channel = new NotificationChannel(
                    channelId1,
                    "Finderr Message",
                    NotificationManager.IMPORTANCE_DEFAULT);
            mNotificationManager1.createNotificationChannel(channel);
            mBuilder.setChannelId(channelId1);
        }

Also I can say that i had some problems with Samsung devices when my app tried to start foreground service with permanent notification. See dontkillmyapp.com for details


text:
Q: Problems reshaping an array in TF I'm passing in a [64,240] tf.array.
I want to reshape this to a [64,10,24] tf.array.
I've tried various different methods but I always get the same error.
... raise ValueError("Shape %s must have rank %d" % (self, rank))
ValueError: Shape (64, 240) must have rank 1
The code fails at:
self.x_expand[i] = tf.reshape(self.input_x[i],[num_classes,data_size])
I guess i'm making a basic mistake, hopefully someone can point out what it is...
A larger fragment of the code is:
class CNN(object):
def __init__(
  self, sequence_length, num_classes, data_size,
  filter_sizes, num_filters, l2_reg_lambda=0.0, batch_size=64):

    # Placeholders for input, output and dropout
    self.input_x = tf.placeholder(tf.int32, [batch_size, sequence_length], name="input_x")
    self.input_y = tf.placeholder(tf.float32, [batch_size, num_classes], name="input_y")
    self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")

    with tf.device('/cpu:0'), tf.name_scope("reshaping"):
        self.x_expand = tf.placeholder(tf.int32, [batch_size, num_classes,data_size], name="expand_x")
        for i in range(batch_size):
            self.x_expand[i] = tf.reshape(self.input_x[i],[num_classes,data_size])
        self.x_expanded = tf.expand_dims(self.x_expanded, -1)

A: It seems you want self.x_expand to be the input reshaped I think the following might be more appropriate:
with tf.device('/cpu:0'), tf.name_scope("reshaping"):
    self.x_expand = tf.reshape(self.input_x, [batch_size, num_classes, data_size])

Two things of note:

*

*Did not use a tf.placeholder for self.x_expand. Placeholders are meant for feeding input from the user, but here it seems what you really wanted was to reshape existing feeds

*Did not change shape on a per-element basis, but rather with a single operation.
NB: I was unable to reproduce the error message you saw, possibly because we're using different versions of TensorFlow and there have been changes to the error message reporting in recent versions. I am using 1.0.0.

A: I think you should try:

self.x_expand = tf.reshape(self.input_x, [batch_size, num_classes,data_size]


text:
Q: In R Markdown in RStudio, code chunks after a four-backtick-block loses interactivity (e.g., "Run Current Chunk" button disappears) I followed Xie Yihui's tip to render a code chunk as verbatim in the output of a R Markdown document. While the result looks fine, I notice that the formatting and interactivity on the RStudio interface changes, that is, code chunks after a four-backtick block are no longer displayed with buttons such as "Run Current Chunk" at the top right. The R Markdown is inserted below.
How can I keep using the four-backtick trick (or use another trick with the same effect) while maintaining the interactivity of the interface?
---
title: "Diamond sizes"
date: '2016-08-25'
output:
  pdf_document: default
  word_document: default
  html_document: default
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
library(dplyr)
```

To show a verbatim R code chunk following Xie Yihui's trick ([link](https://yihui.org/en/2017/11/knitr-verbatim-code-chunk/)):

````
`r ''````{r}
library(gapminder)

gapminder %>% ggplot(aes(year, lifeExp, group = country)) +
  geom_line(alpha = 1/3)
```
````

```{r}
library(gapminder)

gapminder %>% ggplot(aes(year, lifeExp, group = country)) +
  geom_line(alpha = 1/3)
```

Screenshot of RStudio where the 1st code chunk displays as expected but the 2nd one doesn't come with the execution/setting buttons:

A: You need to add one last triple backticks at the end. I do see though however it does add the 3 additional tickmarks to the rendered document, but this is what I did you atleast get the other chunk mark

updated code 8/21/2021
---
title: "Untitled"
author: "Daniel"
date: "8/21/2021"
output: html_document
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
library(dplyr)
```

To show a verbatim R code chunk following Xie Yihui's trick     ([link](https://yihui.org/en/2017/11/knitr-verbatim-code-chunk/)):

````
`r ''````{r}
library(gapminder)

gapminder %>% ggplot(aes(year, lifeExp, group = country)) +
  geom_line(alpha = 1/3)
```
````

```{r}
library(gapminder)

gapminder %>% ggplot(aes(year, lifeExp, group = country)) +
  geom_line(alpha = 1/3)
```


text:
Q: How to convert parsed html object repsonse to a valid html after removing some tags in jQuery? I am trying to parse this HTML to object, remove some tags that are not necessary and then convert it back to html and pass it down to another div and show it on the front end.
This process seems a bit redundant to me too, so please tell me if you have a better approach.
This is the jquery code;
var urlData = {
    token: token,
    idnlanguage: idnlng,
    domainoption: domainsData[0],
    domains: domainsData[1],
    domainsregperiod: domainsregperiod
}
$.post(url, urlData, function(data, status) {
    var xml = data,
        xmlParse = jQuery.parseHTML(xml),
        $xml = $(xmlParse),
        $header = $xml.find("#header"),
        $menu = $xml.find("#main-menu"),
        $footer = $xml.find("#footer"),
        $body = $xml.find("#main-body")

//The parsed data is an object so this line below does not work.
$("#step2").html($body)
});

This is the response from the API

                                      // Object index 0 after parsing

    Something              // Object index 1 after parsing

    Something      // Object index 2 after parsing

    Something              // Object index 3 after parsing

The response will vary from account to account so I cannot just remove an index in this object. The original response looks exactly like this except it is a lot bigger.
Now I want to pick the body with id #someId and push it inside

Can you please tell me what am I doing wrong and do you have a better approach for this problem?


text:
Q: Extract Decimal and Integer numbers from sentences using Perl I have sentences including letters, integers, and decimals.
Example:
There are 1.6mm, 2.1mmcycst.
There are many about 3mm cysts.
There are 2 cysts about 4~5mm.

("2.1mm cyst" or "2.1 mm scysts" is the accurate sentence, but our data is "2.1mmcycst")
From these sentences, I want to extract numeri's.
For example,
1.6 and 2.1
3
4~5

I'm not familiar with regular expressions, and I cannot pick up only numeri's
including  decimals or other relative signs (eg., "~").
Here is the code:
#!/usr/bin/perl

my $qwe = "There are 1.6mm, 2.1mmcycst.";
print "$qwe\n";
if($qwe =~ /\d+(\.\d)?\d*/){
    print "$&\n";
}

From the script, I got below output:
1.6

I am expecting 1.6 and 2.1.
How can I change my regex here to match multiple patterns in single line?
I use macOS 10.14.5 and perl v5.18.4.

A: Use the /g option on your match operator, to get all matches. Then replace for with while to iterate across them.
#!/usr/bin/perl

my $qwe = "There are 1.6mm, 2.1mmcycst.";
print "$qwe\n";
while ($qwe =~ /\d+(\.\d)?\d*/g) {
    print "$&\n";
}

A: Do not reinvent the wheel. If a task seems common to you, it is likely that there is a Perl module for that. Regexp::Common can be used for matching common regular expressions, including numbers of various kinds. For example, your sample input can be extended with more complex examples of numbers, all of which can be parsed as shown below:
Create the input:
cat > in.txt <<EOF
There are 1.6mm, 2.1mmcycst.
There are many about 3mm cysts.
There are 2 cysts about 4~5mm.
The collection has 1.23E6 frozen cysts, stored at -70.5C, with cysts ranging in size from 1e-3m to 5.12E-3
EOF

Parse and print the real numbers:
perl -MRegexp::Common -lne 'print join " ", /($RE{num}{real})/g;' in.txt

Output:
1.6 2.1
3
2 4 5
1.23E6 -70.5 1e-3 5.12E-3

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
-MRegexp::Common : same as BEGIN { use Regexp::Common; }.
/($RE{num}{real})/g : Capture all real numbers in the input line $_. Parenthesis mean capture. /.../g means match multiple times. In the LIST context, imposed by join, this returns the list of all matches. These matches are then printed.
SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches

Note: you need to install Regexp::Common Perl module - it is not part of the standard Perl library.


text:
Q: how to count the number of subgroups of order n with some constraints Let $G$ be a group of order 24. How many subgroups of $G$ are there, given that there are exactly 8 elements of order 3 in $G$?
Tried: since $24=2^3\times 3$, there must be a subgroup of order 1,2,4,8,3, and 24 respectively. Also, it's easy to show that $\{a,b,c,d,a^2,b^2,c^2,d^2\}$ is the set of elements of order 3. So essentially we have 4 subgroups of order 3. But how about those of order 2,4,8?

A: There are three groups that satisfy your hypotheses $S_4$, $A_4 \times C_2$, and ${\rm SL}(2,3)$, and they each have different numbers of subgroups (30, 26, and 15), so the question does not have a unique answer.


text:
Q: how to go to next line in android xml I have a relative layout that contains two LinearLayout. So when I setText(id is companyText) and its longer text it goes to above in another TextView (id is companyDistance)
When companyName has longer text I want it go to next line and not go avobe to second layout
for more clear see attached pics

But I want it will be like in this pics

Here is my main.xml file
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/mainLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:padding="10dp">
    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true">
        <ImageView
                android:id="@+id/companyImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/secret_logo_small"
                android:layout_marginRight="10dp"/>
        <TextView
                android:id="@+id/companyName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/companyImageView"
                android:textColor="@android:color/white"
                android:layout_gravity="center"
                android:text="Secret"/>
    </LinearLayout>

    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_alignParentRight="true">
        <TextView
                android:id="@+id/companyDistance"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@android:color/white"
                android:layout_marginTop="7dp"
                android:textSize="18sp"
                android:text="154"
                android:layout_gravity="right"/>

        <Button
                android:id="@+id/companyPercentImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_below="@id/companyDistance"
                android:textColor="@android:color/white"
                android:text="@string/add"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:textSize="11sp"
                android:background="@drawable/button_indicator_dagavit"
                android:drawableLeft="@drawable/small_green_button_add_icon"/>
    </LinearLayout>
</RelativeLayout>

A: Do not use RelativeLayout use LinearLayout.
Here is complete answer for your question. Good luck.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/mainLayout"
                 android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:padding="10dp">
    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
              android:layout_weight="1"
            android:layout_alignParentLeft="true">
        <ImageView
                android:id="@+id/companyImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/secret_logo_small"
                android:layout_marginRight="10dp"/>
        <TextView
                android:id="@+id/companyName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/companyImageView"
                android:textColor="@android:color/white"
                android:layout_gravity="center"
                android:text="Secret"/>
    </LinearLayout>

    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_alignParentRight="true">
        <TextView
                android:id="@+id/companyDistance"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@android:color/white"
                android:layout_marginTop="7dp"
                android:textSize="18sp"
                android:text="154"
                android:layout_gravity="right"/>

        <Button
                android:id="@+id/companyPercentImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_below="@id/companyDistance"
                android:textColor="@android:color/white"
                android:text="@string/add"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:textSize="11sp"
                android:background="@drawable/button_indicator_dagavit"
                android:drawableLeft="@drawable/small_green_button_add_icon"/>
    </LinearLayout>
</LinearLayout>

A: Put this in your textview:
android:maxLines="10"

Then use \n in the text of your TextView.
maxLines makes the TextView be at most this many lines tall. You may choose another number :)

A: First, add an ID to your first LinearLayout:
<LinearLayout
    android:id="@+id/left_linear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true">

And in your second LinearLayout you need to add the attribute
android:layout_toRightOf="@id/left_linear

so your xml will look like this:
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@id/left_linear">


text:
Q: Stanford NER - Extract Multi word entities How can I tag collocations in Stanford NER? Currently it tags Federal Reserve Bank of New York as
<wi num="11" entity="ORGANIZATION">Federal</wi> <wi num="12" entity="ORGANIZATION">Reserve</wi> <wi num="13" entity="ORGANIZATION">Bank</wi> <wi num="14" entity="ORGANIZATION">of</wi> <wi num="15" entity="ORGANIZATION">New</wi> <wi num="16" entity="ORGANIZATION">York</wi>

I want it to be recognized as
<wi num="11" entity="ORGANIZATION">Federal Reserve Bank of New York</wi>

Is this possible?

A: Something similar is, yes.  If you give the flag
-outputFormat inlineXML

then you'll get:
<ORGANIZATION>Federal Reserve Bank of New York</ORGANIZATION>

(Note that this isn't really changing how Stanford NER works but just the formatting of output.  If you don't like any of the provided output formats, it is fairly simple to write your own.)


text:
Q: Will using the include method in Javascript cause additional HTTP requests? I want to break up my index.js file into multiple files. For example, it would be nice to move all of my linked list implementation code into a linkedList.js file to keep things organized.
If I organize my code like this will it cause additional http requests? Is this something I need to worry about as far as load time?


text:
Q: can i have more than one java application server on one server? is it possible to install more than one java application server on one server or VPS ?
i want to install JBOSS , TOMCAT , WEBLOGIC and my be more.
how this is possible and what the benefits and disadvantages ?!

A: It is possible, if you want to try all of them. You just have to select different port for each services.
Is there a real use-case ? You could have an application bound to your application server, and you could want to run different applications.

A: Yes.  The usual problem is that a given port can only be used by a single process.
Hence you cannot have both JBoss and Weblogic on port 8080.  Also a lot of extra ports are needed for normal operation.  This is at best tedious.

A: This is possible. You need to take care about port's these servers use.
Also you need to check what resources (cpu's/core/RAM) you have on your server. Your system should have ample resources to Run multiple servers.
I don't know whats use case, But if possible I would prefer having various webapps on single Java applicationserver.

A: As already mentioned above it is possible but it is a configuration management nightmare.
If it is for compatibility testing, I would look at EC2 or similar timebased hosting and , put an 1 app server in 1 image and spin up each image in turn and shut it down after the test is finished.
The money that costs is paid 10x by not having to edit all kind of configuration files and debugging weird conflicts.

A: Yes, it is possible.
Pros:

*

*You don't need extra servers to run your appservers, so you save in physical/virtualmachines. This helps a lot when you're prototyping something, and also in functional testing, because you can share servers between applications.

*Some applications may need incompatible appserver settings, so you must run them in different appservers, side by side.

*Downtime of one appserver doesn't affect other appservers.

Cons:

*

*You must make sure that every appserver gets enough share of CPU, memory, etc.

*You must assign port numbers to each appserver

*You are making each environment's performance dependent on each other's.

So, it is something that you do mainly to experiment/develop/test. In production environments you have to be much more careful when running appservers side by side..


text:
Q: Swift limit number of rows in section & extend limit once bottom reached Problem:
I would like to limit the amount of cells shown. For example, 100.
Once the tableView has reached the bottom I would like to extend that limit further since the data is already there, I do not need an activity loader.
I simply would like to tableView refresh and exceed the minimum of 100 in a smooth manner
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if(delegate.groupedSessions[section].count > 100){
            return 100
        }else{
            return delegate.groupedSessions[section].count
        }

    }

Pseudocode:
(If scrolled to bottom or indexPath.row >= 100)
Exceed numberOfRowsInSection limit to 200 and so on.

A: let increment = 100
var limit == 100

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Not sure how your code is set up or what "delegate" is but I'm assuming that's your model that holds the data
    if limit < delegate.groupedSessions[section].count {
        return limit
    } else {
        return delegate.groupedSessions[section].count
    }
}

// This is a Delegate Method
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard indexPath.row == limit - 1 else { return }

    limit += increment
    tableView.reloadData()
}

I'm also not sure what you're trying to achieve. Even if you do this, the tableview would just keep scrolling smoothly like the limits weren't even there. But you asked, so.


text:
Q: Best way to parse parts of HTML in Cocoa I downloaded a webpage into a NSString but am only interested in certain pieces of the webpage.  I used "componentsSeparatedByString" to get to one of the 8 parts of the page, but it seems very inefficient to keep repeating this for each piece, as well as each sub piece that gets processed after getting the result of that function.  What is the best way to do this?

A: Module HTMLparser from libxml2
this module implements an HTML 4.0 non-verifying parser with API compatible with the XML parser ones. It should be able to parse "real world" HTML, even if severely broken from a specification point of view.


text:
Q: Python Indentation Error, but there is no actual error? Not really sure why I keep getting this error:
Indentation Error Photo
Everything is spaced out by 4 spaces (or 1 tab). When I change this one function to 5 spaces, it fixes the problem, but then creates new problems in 2 other methods. Could someone help me out here?


text:
Q: Как сделать поиск в глубину максимально быстро во внешней памяти? Интересует алгоритм или/и пример кода на C++.
Дополнительная информация из комментариев:
Граф задан списками смежности: один файл с вершинами + указателями на место в другом файле, где находятся смежные этой вершине вершины. Но можно преобразовать это в другой формат, конечно, если будет быстрее.
Размер графа на порядок больше размера оперативной памяти. Вершины для простоты -- натуральные числа. Можно использовать сколько угодно потоков, но не понимаю, как это поможет. Задача не в использовании чего-то готового, а в придумывании алгоритма/кода по алгоритму.
Надо придумать алгоритм, который минимизирует количество чтений из внешней памяти во внутреннюю, потому что это узкое место.

A: Поиск в глубину можно реализовать ака рекурсивно, так и итеративно. В данном случае первый вариант алгоритмам может не подойти из-за глубокого дерева рекурсии, которое получается в ходе выполнения алгоритма и может вызвать ошибку переполнения памяти.
А во втором варианте используется стек. С примером кода на С++ можно познакомиться здесь: Нерекурсивный поиск в глубину


text:
Q: Different behaviour when using single supercap vs several in series I'm designing a circuit where I need a supercapacitor to continue powering the circuit for a few seconds after the main power has been removed. A simplified schematic of the circuit is shown below.

The circuit consumes 200mA and needs to remain on for 3 seconds. I've calculated the required capacitance as follows:

*

*Regulator dropout voltage is 250mV, therefore min input voltage = 3.3V + 0.25 = 3.55V

*Diode Vf is 0.4V, therefore max input voltage is 4.6V

*Capacitor V = 4.6V-3.55V = 1.05V

*Combining the Q=CV and Q=It equations results in C=It/V. Plugging in the numbers results in a required capacitance of 0.2*3/1.05 = 0.57F

I've tested the circuit out with a few supercaps and here are my results (time measured using a stopwatch and stopped when multimeter shows that voltage has reached 3.55V):

*

*1.6F (3x4.7F, 2.3V caps in series). Calculated time = 8.2s, actual time = 8.5s

*2.35F (2x4.7F, 2.3V caps in series). Calculated time = 12.3s, actual time = 13.2s

*0.5F (2x1F 2.7V caps in series). Calculated time = 2.6s, actual time = 3s

*A single 1.5F, 5.5V cap. Calculated time = 7.9s, actual time = "instantaneous".

*A single 1F, 5.5V cap. Calculated time = 5.3s, actual time = "instantaneous".

*A single 0.33F, 5.5V cap. Calculated time = 1.73s actual time = "instantaneous".

What I'm confused about is why the single 1.5F and 1F capacitors don't seem to behave at all according to my calculations, whereas the capacitors formed for more than one in series work just as calculated.

A: I was intrigued by this problem; but I came across this answer which might explain it : look up the ESR (equivalent series resistance) - for your supercaps - some are as high as 80 ohms which would explain what you are seeing.


text:
Q: How to merge 2 version of same very large project So, i am in charge of a migration from Java 1.5 to Java 1.8. First at all we change the compiler (from Ant to Maven), and later we reformat a lot of code.
We also removed Seam framwork, that took us a considerable time.
up here all right.
the problem is that other colleagues continued working in version 1.5 and now I need to bring all those changes made. This includes new entities, packages, datas, Hibernate configurations and even a change in the database schema.
The question is, how can I move these changes without an eternal headache? Note that there has been a change in basically 75% of the files, since almost all the annotations in the project were changed.
Thank you very much and sorry for my bad English.

A: So there is not going to be any magic tool that will automatically merge all the changes but there are definitely tools out there that will help with looking at and keeping track of the differences between all the versions you need merged.
Situations like this are why its imperative to use good common coding practices and version control! I recommend taking a look a setting up a GIT repository or some form of modern version control for your project.
The way I would go about making this merge is as follows:

*

*Create an initial Git repository of the project before any of the changes were  made (before the 1.8 changes  / or colleagues changes)

*Copy the files of the project with the most changes made to the repository ensuring that you preserve the git settings for the repository (hidden .git folder)

*You should be able to run a git status to see the files that were added/modified/removed and 'git diff' to see the actual changes

*Commit the changes

*Bring in the next of changes into the GIT repository

*Using git status / git diff to look at the differences in the files, look through the changes keeping what you need (repeat until all colleagues changes are merged)

There are different tools that will help look at differences ( diff ) in files
With proper version control and a good diff tool should be able to merge your changes :)


text:
Q: Python printing "import numpy as np
arr = list(map(float,input().split()))
print(np.array(arr.reverse))

Why is this printing this instead of the contents of the list?
# outputs "<built-in method reverse of list object at 0x107eeeec8>"

A: You have two problems.
The first problem is that you are not actually calling the reverse method on your array arr.
You have this: arr.reverse
You have to actually call it -> arr.reverse()
Simple example below:
>>> [1,2,3].reverse
<built-in method reverse of list object at 0x100662c68>

Without calling reverse, the output you get is the uncalled reverse method of the list object. Which is very similar to the output you were getting.
The second problem you have is that reverse() method does the reverse in place, which means it performs the reverse on arr (your arr will be reversed) and returns None. So, when you are passing this:
np.array(arr.reverse())

You are returning the return of arr.reverse() to your np.array call, which is None.
So, fixing those two items, by calling arr.reverse() on its on, and then passing arr, will give you the result you are expecting:
import numpy as np
arr = list(map(float,input().split()))
arr.reverse()
res = np.array(arr)
print(res)

Demo:
1 2 3 4
[ 4.  3.  2.  1.]


text:
Q: Images Uploading PHP I've been working on a project that is relevantly easier than what it took me to do it.
I made an entire website that is between doctors and patients;
I'm badly stuck in uploading and retrieving images!!
Here is the code I've been building..

<?php session_start();

$un = "xxx";
$pw = "xxx";
$hn = "xxx";
$dbhandle = mysql_connect($hn, $un, $pw) or die("Couldn't connect to the database");
mysql_set_charset('utf8');
$selected = mysql_select_db("dsnnet_login", $dbhandle);
$myusername = $_SESSION['snamed'];

$target_dir = "uploaded/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$sql = mysql_query("UPDATE docTable set photoname='$target_file' WHERE Username= '$myusername'");
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

header("location: docp.php");

?>

and the "working page" is as follow:

<?php session_start();

$un = "xxx";
$pw = "xxx";
$hn = "xxx";
$dbhandle = mysql_connect($hn, $un, $pw) or die("Couldn't connect to the database");
mysql_set_charset('utf8');
$selected = mysql_select_db("dsnnet_login", $dbhandle);
$myusername = $_SESSION['snamed'];

$target_dir = "uploaded/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$sql = mysql_query("UPDATE docTable set photoname='$target_file' WHERE Username= '$myusername'");
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

header("location: docp.php");

?>

Can anyone help me figure it out?
I've been trying for at least 4 days now..
I'm not giving up.. I'm open to learn..
thank you guys:)
cheers

A: check below
1.tag form have enctype="multipart/form-data"
2.if not localhost ,folder upload must set permittion 777

A: May I know error message which make you stuck?
before that, please check your form enctype attribute. Your upload form must be :

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>


text:
Q: grabbing div id by click I am using $('.startb').click(function() {
var myId = $(this).attr("id");
}); to capture the id "startb1" what do I need to add to also capture the id "test1" by the class "flashObj" by using the fact they are all in the same div container "audioContainer"

hi

A: var myId = this.id;
var otherId = this.parentNode.querySelector(".flashObj").id;

This method of getting the "startb1" id is approximately 150 times more efficient than yours, due to the amount of steps jQuery has to go through just to create the $(this) object, by the way.
Also, querySelector is supported in IE8 whereas getElementsByClassName isn't.
If IE7 and below is required, and the structure is reliable (ie. it will always be the fourth child div you need), use: var otherId = this.parentNode.children[3].id;.

A: You could search for siblings of the div having the class flashObj:
$('.startb').click(function() {
   var myId = $(this).attr("id");
   var flashObjID = $(this).siblings('.flashObj').attr('id');
});

A: Use .on() instead of .click() if you are using latest jQuery release:
$(".audioContainer").on("click", ".startb", function(e){
    var _this = $(this);
    var id = _this.attr("id");
    var oId = _this.closest(".audioContainer").find(".flashObj").attr("id");
}

Now you can also map multiple events, keep events for later on and even pass data to the event.data object and etc.
Read more at: jQuery .on()

A: Assuming you want to use the same "click" event, the following should do the trick:
$('.startb').click(function() {
    var myId = $(this).attr("id");
    var flashID = $(this).parent().find(".flashObj").attr("id");
});


text:
Q: first name and title without parenthesis in a single regex how to put the following 2 regex together to capture both groups in one expression:
(^[a-zA-Z]*) should capture the first name, first_here
\((.+?)\) should capture the title
to extract:
Donald President
Mike Vice President

from:
Donald Trump (President)
Mike Pence (Vice President)

A: You can combine as follows to match first name and title. then use first and second captured group to form output.
^([a-zA-Z]*).*?\(([^)]+?)\)

Demo

A: You might use
^(?P<name>\w+)[^()]+\((?P<function>[^()]+)\)

See a demo on regex101.com.

Obviously this will work for
Cake Cookie (Sugar)

as well. If you want to limit it to names only, use a database.


text:
Q: Visual Studio Drag and Drop Arrangement of Web Controls Just curious,
I remember way back in the ASP.Net 1.0 Visual Studio 2002? days you could just drag a web control onto your visual web form interface to where you wanted it and it would fill in all the CSS styling to make sure that control was in the right spot when viewing the app in a browser.
Did that go away?  I haven't used it in years as I have been hand coding stuff, but for some quick and dirty prototyping I thought it might be useful. Is that capability gone, or do I need to enable that somewhere?
Thanks for your time.

A: In ASP.NET 1.0 - 1.1  the style attribute was automatically added but in ASP.NET 2.0 onwards this is not a default behavior.
However here is a workaround

*

*To set the style properties for each control you add

*[VS2010]You can set Tools->Options->HTML Designer->CSS Styling

Check -> Change positioning to absolute for controls added using Toolbox, paste or drag and drop
Choose -> Auto Style Application

A: That was a horrible, disgusting feature that they got rid of for excellent reason. It used absolute positioning to place the control at the particular point on the page, as though the page were a VB6 form. It produced horrible, unmaintainable results.


text:
Q: What is difference between factory design pattern and DAO design pattern Comparing these two patterns - Factory and DAO patterns, I see that they are quite similar:
Both of them have interface (Product/Dao), Factory (ProductFactory/DaoFactory) and concrete implementation (ConcreteProduct,ConcreteDao).
Factory creates some concrete implementation object and this object is used by client via interface.
So are they similar or I don't understand something? Or maybe is Dao pattern a specific implementation of factory pattern?
Thanks in advance.

A: The Data Access Object (DAO) pattern abstract away the details of persistence in an application. Instead of having the domain logic communicate directly with the database, file system, web service, or any other persistence mechanism : The domain logic speaks to a DAO layer instead. This DAO layer then communicates with the underlying persistence system or service.
The advantage of the DAO layer is that if you need to change the underlying persistence mechanism you only have to change the DAO layer, and not all the places in the domain logic where the DAO layer is used from.
Look at this article for better understanding.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

The client needs a product, but instead of creating it directly using the new operator, it asks the factory object for a new product, providing the information about the type of object it needs.
The factory instantiates a new concrete product and then returns to the client the newly created product(casted to abstract product class).

The client uses the products as abstract products without being aware about their concrete implementation.
Read this article for better understanding.
Factory pattern talks about creation of object & DAO patterns talks about management of data

A: IMO They are pretty different
DAOs are used to transform between serialized (normally sql) versions of the data and Java objects
On the other hand, a Factory can be used to facilitate generic solutions for problems where a significant proportion of the work is similar. An example of this that I created a while back was a SocketHandlerFactory, to be used by a generic ServerSocket, so that however the generated Socket needs to be handled, you can configure this in the Factory.
Does that shed some light?

A: I'm assuming that when you are referring to the DAO pattern then you have something like this in mind:

source
However DAO's don't necessarily require factories to create them. For example in the Spring context there is no difference between Repositories and DAOs and there are no Repository factories as far as the client is is involved.
Quoting the Oracle article, that the diagram was taken from, they are in fact making use of a the GoF factory patterns (there are 2 in the Gang of Four book; Abstract Factory and Factory Methods):
The DAO pattern can be made highly flexible by adopting the Abstract Factory [GoF]
and the Factory Method [GoF] patterns (see "Related Patterns" in this chapter).

In  summary, there is a clear difference in use-case if not structure of both patterns and that the factory within the DAO-pattern likely refers to a 'real' factory patterns that was added as an additional benefit, not as integral part of said pattern.

A: The major difference lies in the semantic context in which these design patterns are used.
DAO is used to abstract away the domain logic of Database Handling.
Fatory is used to abstract away the object creation logic.
Dont bother about the implementation/interface details.
Separate your application into layers and if you require a database, then, Having DAO is one option, which could be used across layers.


text:
Q: How to preprocess c/h files in Android so that they get the exact CFLAGS and C_INCLUDES as c source are built? I am parsing some C headers in Android project using pycparser. For pycparser to work, C headers must be preprocessed (cpp or gcc -E).
How do I write an Android.mk to preprocess C headers so they gets the same compile options (CFLAGS, C_INCLUDES) as C sources files would be compiled by Android.mk?
Thanks!
PS:
Run mm showcommands is a way to get actual compile flags manually. Yet I'm looking for a way to intergrate this in automatic build process.


text:
Q: Codeigniter custom routing issue This is my routes setup code
$route['general/(:any)'] = "videos/filter/$1/1";
$route['general/(:any)/(:num)'] = "videos/filter/$1/1/$2"; //pagination

Following link works fine.
www.example.com/general/latest

But below link doesn't work like what i want
www.example.com/general/latest-trending/5

$route['general/(:any)'] only executes always.
How to solve this issue?

A: Reverse the order:
$route['general/(:any)/(:num)'] = "videos/filter/$1/1/$2"; //pagination
$route['general/(:any)'] = "videos/filter/$1/1";

You want more specific routes first, because if the shorter one matches first, it will ignore all other routes.


text:
Q: URL re-writing without affecting ajax functions I am making classifieds ad web site. In that I need to load one ad without URL parameters. I did it with URL parameters successfully. Now I want to remove parameters from the URL. I stored URL-slug which is constructed saving time of ad in database.  In ad page load time there are many functions called. Those functions asks data from database according to URL parameter value. I tried with htaccess rules. But rest of page and details load as before. But ajax functions called data which are supposed to display on div tags not working. They show whole page inside those divs.
I tried following htaccess rules so far.
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]

ReWriteRule ^ad/([a-zA-Z0-9-/]+)$ ad.php?url=$1
ReWriteRule ^ad/([a-zA-Z0-9-/]+)/ ad.php?url=$1

Now I will show sample of my function.
  function load_reviews(){
        var id = "<?php echo $ad->get_ad_id($unique_ad_url) ?>";
        $.ajax({
            url: './middle/review/load_reviews',
            cache:true,
            type: 'GET',
            async: false,
            data:{
                id: id
            },
            success: function(response){
                $('#chat_area').html(response);
            },
            error: function (x, e) {
                if (x.status == 0) {
                    console.log('You are offline!! -  Please Check Your Network.');
                } else if (x.status == 404) {
                    console.log('Requested URL not found.');
                } else if (x.status == 500) {
                    console.log('Internal Server Error.');
                } else if (e == 'parsererror') {
                    console.log('Error. - Parsing JSON Request failed.');
                } else if (e == 'timeout') {
                    console.log('Request Time out.');
                } else {
                    console.log('Unknown Error. - ' + x.responseText);
                }
            }
        });
        return false;

    }

In the top of ad.php file I include these code lines to grab last part of url and store it in variable.
$url=$_SERVER['REQUEST_URI'];
//echo $url;
$unique_ad_url = basename(parse_url($url, PHP_URL_PATH));

Likewise in JavaScript functions I passed ad_id to retrieve it to ajax get relevant data for current viewing ad page.
In ad list page I showed ads with their' url. That is done by as below,
<a href="ad/'.$this->url_slug($ad['AD_URL']).'" class="card all-card">

More =>
When I see network responses from chrome develop tools it shows infinitely loading same css, js, other external library files and ajax function called responses recursively. Also it added id parameter to end of ajax URLs.
In the top of ad.php file I echo $unique_ad_url to see value. It also shows inside all divs which are supposed to show only retrieved data. As I mentioned above along with whole ad page it shows that echo value.
At the end I want load ajax retrieved values to present on ad page without such problems. And URL is expected to be like,
http://ads.com/ad/daihatsu-boon-m700s-new-2016-2019-04-05-22-49-04
I appreciate your help for this issue.

A: hey I also faced that problem. You might find help from this.
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]

ReWriteRule ^ad/([a-zA-Z0-9-/]+)$ ad.php?url=$1
ReWriteRule ^ad/([a-zA-Z0-9-/]+)/ ad.php?url=$1

A: Try these rule in your .htaccess:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
ReWriteRule ^ad/([\w-]+)/?$ ad.php?url=$1 [L,NC,QSA]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]


text:
Q: AngularJS Smarttable - event on select Is there a way to trigger an event on row select in AngularJS Smart Table?
This was a subject in other thread but still no answer to this point.
Unable to select the grid item using SmartTable in Angular JS

A: I needed this functionality in order to show a panel whenever at least 1 row was selected. I originally set up a watch, but decided that was too expensive.
I ended up adding a callback inside the stSelectRow directive.
ng.module('smart-table')
  .directive('stSelectRow', function () {
    return {
      restrict: 'A',
      require: '^stTable',
      scope: {
          row: '=stSelectRow',
          callback: '&stSelected' // ADDED THIS
      },
      link: function (scope, element, attr, ctrl) {
        var mode = attr.stSelectMode || 'single';
        element.bind('click', function ($event) {
          scope.$apply(function () {
              ctrl.select(scope.row, mode, $event.shiftKey);
              scope.callback(); // AND THIS
          });
        });

        //***///
      }
    };
  });

I was then able to pass a function from my controller to the directive (note: you could pass the selected row back, I didn't need to)
tr ng-repeat="row in customerResultsTable" st-select-row="row" st-select-mode="multiple" st-selected="rowSelected()">

Referenced this post for help Callback function inside directive attr defined in different attr

A: Here is an easy watch to place on a Smart Table:
// fired when table rows are selected
$scope.$watch('displayedCollection', function(row) {

  if(!row) return;

  // get selected row
  row.filter(function(r) {
     if (r.isSelected) {
       console.log(r);
     }
  })
}, true);

related html:
<table st-table="displayedCollection" st-safe-src="rowCollection" class="select-table table">

This github issue was helpful.


text:
Q: read.table multiple Txt files in R I need to read multiple Txt file in R to create a unique dataset and export it on Excel. this is what I used
BHCFYYMM <- read.table('bhcf1803.txt''bhcf1806.txt''bhcf1809.txt''bhcf1812.txt', sep="^", nrows=1300, comment.char="", header=TRUE, quote="", na.strings="--------", as.is=TRUE)
setwd("/Users/marco/Desktop/research/silvio")
getwd()
write.table(BHCFYYMM, file = "HoldingCompanyData.csv", sep = ",")

but i get this error:
Error: unexpected string constant in "BHCFYYMM <- read.table('bhcf1803.txt''bhcf1806.txt'"
Any idea how I can approach this?

A: Your code likely failed because you can not give read.table() multiple file paths at once.
You can instead use lapply() to feed a list of file paths to read.table(). The tables can then be combined using dplyr::bind_rows().
(assuming the other parameters you have provided are correct)
# Load dplyr
# install.packages("dplyr")
library(dplyr)

# It is usually best practice to set your working directory before you do anything else.
setwd("/Users/marco/Desktop/research/silvio")

# Make list of files.
files <- c("bhcf1803.txt", "bhcf1806.txt", "bhcf1809.txt", "bhcf1812.txt")

# Read files into a list of tables.
tables <- lapply(X = files, FUN = read.table, sep = "^", nrows = 1300, comment.char = "", header = TRUE, quote = "", na.strings = "--------", as.is = TRUE)

# Bind tables together into a single table.
BHCFYYMM <- bind_rows(tables)

# Write table to a new file.
write.table(BHCFYYMM, file = "HoldingCompanyData.csv", sep = ",")

A: I don't know what is in a text file but this is what I generally do if I want to import multiple files and bind them
#set working directory
setwd("C:/xxxx/xxxx/Desktop/DUMP/")
#select the pattern of the file extension
files <- list.files(pattern=".txt")
#read all the files and bind the rows
tbl<-lapply(files, read.table) %>% bind_rows()


text:
Q: How does subscription.request(n) in Flow API perform backpressure at any n value? I'm playing around with the Flow API and, so far, I understand that the request() method is used for back pressure. Most articles state that this is akin to controlling the speed of consumption.
However, almost every example code I see passes the value 1 into the request() method, like, subscription.request(1). But I don't quite understand how does the request() method control the speed of consumption.
I have tried to run a test by sending a bunch of items to the publisher and print the thread name and it seems like every single onNext() is running on the same worker thread be it I was using request(1) or request(50) :
@Override
public void onNext(T item) {
   System.out.println(Thread.getCurrent().getName());
   Thread.sleep(5000);
   subscription.request(50);
}

If the onNext() were running in different threads, I can understand how that the n value passed into request(n) will affect the rate at which the items are being processed in parallel (running in n threads). But it doesn't seem to be the case in my test as they are all running under the same thread name.
In this case, what's the difference between request(1) and request(50) when they are all still going to be run sequentially one after another on the same thread? Wouldn't the consumption rate still be the same then?

A: The n in request indicates how many elements the subscriber can accept and gives a limit on how many items the upstream Publisher can emit. Therefore, the slowing down of this generator is not per individual item but the average time for each batch generated interleaved by the consumer's processing time.
onNext is executed in a serialized fashion and depending on the upstream, on the same thread as well. Thus, calling request in there usually indicates the upstream it can call the same onNext, after the current call has ended, with the next value if available. I.e., calling Thread.sleep will postpone this next invocation of onNext.
Generally, there is no reason to call request in onNext an end-Subscriber because it is run synchronously with respect to its immediate upstream Publisher and there is no practical difference between a single request(Long.MAX_VALUE) and repeated request(1).
One of the few reasons to call request if the onNext forks off asynchronous work itself and only at the end of that work should more items be requested:
Executor executor = ...

Subscription upstream;

@Override public void onSubscribe(Subscription s) {
    this.upstream = s;
    executor.execute(() -> {
       Thread.sleep(5000);
       s.request(1);
       return null; // Callable
    });
}

@Override public void onNext(T item) {
    System.out.println("Start onNext");
    executor.execute(() -> {
       System.out.println("Run work");
       Thread.sleep(5000);
       System.out.println("Request more work");
       upstream.request(1);
       return null; // Callable
    });
    System.out.println("End onNext");
}

With this setup, the upstream will call onNext once and will call it only when the task executed by the executor has issued the next request. Note though that unless the Publisher emits from a dedicated thread, the example above will eventually drag the onNext invocation onto the executor's thread.

A: Invocations of onNext() are not supposed to run in parallel. They can run from different threads (depends on implementation), but always sequentially. But even sequentially, they can be called with higher rate than the subscriber can handle. So subscriber calls request(n) only when it has room for n incoming items. Usually it has room for only one value, so it calls request(1) when this variable is free.


text:
Q: Error: Multiple databases for CI4 and its uses default database as object validation in inserting data By the way, this is not really a question. I just want really to share how to validate using a specific database in multiple database connections. Since I got this error and it took almost 2 days and thank you to the members of the Codeigniter 4 community who help me how to solve it.
I would like to share it also here for future references if someone encounters this error. Shout out to kenjis for the help!
At first, I thought it was just a bug in the codeigniter4 that if I have a multiple database connections the validation rules only use the default DB group. But unfortunately, No. I just don't specify what DB group  I should verify.
In case you encounter this error, just add this on your controller:
protected function validate($rules, array $messages = []): bool
{
    $this->validator = \Config\Services::validation();

    // If you replace the $rules array with the name of the group
    if (is_string($rules)) {
        $validation = config('Validation');

        // If the rule wasn't found in the \Config\Validation, we
        // should throw an exception so the developer can find it.
        if (! isset($validation->{$rules})) {
            throw ValidationException::forRuleNotFound($rules);
        }

        // If no error message is defined, use the error message in the Config\Validation file
        if (! $messages) {
            $errorName = $rules . '_errors';
            $messages  = $validation->{$errorName} ?? [];
        }

        $rules = $validation->{$rules};
    }

    return $this->validator->withRequest($this->request)->setRules($rules, $messages)->run(null, null, 'other-db-group-name');
}

reference: https://github.com/codeigniter4/CodeIgniter4/issues/5654


text:
Q: Visual Studio 2017 Enable SSL How do you enable SSL for a project in Visual Studio 2017?
In VS15, I could select Project -> Properties -> Debug -> Enable SSL. This option is not available in VS2017. Where has it moved to?
Edit:
I've even tried editing .\vs\config\applicationhost.config to no avail:
        <listenerAdapters>
            <add name="http" />
            <add name="https" />
        </listenerAdapters>

        <sites>
            <site name="WebSite1" id="1" serverAutoStart="true">
                <application path="/">
                    <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation=":8080:localhost" />
                </bindings>
            </site>
            <site name="Filters" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="c:\Users\Ashley\documents\visual studio 2017\Projects\Filters\src\Filters" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:51107:localhost" />
                    <binding protocol="https" bindingInformation="*:43107:localhost" />
                </bindings>
            </site>
            <siteDefaults>
                <logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
                <traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
            </siteDefaults>
            <applicationDefaults applicationPool="Clr4IntegratedAppPool" />
            <virtualDirectoryDefaults allowSubDirConfig="true" />
        </sites>

        <webLimits />

Edit:
Another option I've tried, which just feels clunky, and kind of defeats the point of an IDE, is to configure Kestrel to use HTTPS. This isn't ideal since I had to export a copy of a certificate for localhost from IIS, and IIS Express still tries to load the site on a different port.
public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel(options =>
                options.UseHttps(new X509Certificate2("path/to/cert.pfx", "password")))
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseUrls("http://localhost:5100", "https://localhost:4300")
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

Sadly, this doesn't work when run from VS17. The first time around I got a 502.2 (I think) error, now all I get is an unable to connect error in Chrome. I can run dotnet run from PowerShell and it works fine.
As a workaround, it does the trick. But it doesn't seem neat.

A: Ports are locked down in IIS Express so that it doesn't have to be run as Administrator...
Valid Ports are 44300 - 44399
Check out the Dev Community article
https://developercommunity.visualstudio.com/content/problem/39430/changing-port-number-in-a-web-project-does-not-imm.html
You can edit launchSettings.json, but the ssl ports must fall in this range.

A: This is for an Asp.Net MVC .Net Framework Project

*

*Select your Project by highlighting it.

*Then hit F4 to open its Properties pane.

*Find the SSL Enabled item on list and set its value to True, and
copy SSL URL value onto your clipboard.

*Whilst your Project is highlighted, hit Alt + Enter to open
the Properties dialogue - paste the copied SSL URL into the project url
under the Web menu input box.

A: In Solution Explorer right click on your website name and select "Properties Window", or simply hit F4. Under the Developer Web Server section change SSL Enabled from False to True.

A: For those running asp.net core 1.x in Visual Studio 2017 RC, you should be able to change the "sslPort": 0 line in the launchSettings.json file to whatever port number you would like to use for SSL. This effectively changes the bindings in the .\vs\config\applicationhost.config file mentioned in the previous answers.

A: This is for an Asp.Net Core 2.0:

*

*Open up your Solution Explorer in VS2017.

*Doubleclick Properties (yes, it's an object itself too, not just a folder)

*Open Debug on the left side

*Scroll down and select Enable SSL
If it's already enabled, open up launchSettings.json (unfold Properties) and set "sslPort" to 0, then do the steps again.
VS2017 should now ask you if you want to add an SSL certificate (something it doesn't do if you changed launchSettings.json on your own) and it'll set a port for you.

A: Editing the .\vs\config\applicationhost.config actually worked for me.
<site name="Filters" id="2">
  <application path="/" applicationPool="Clr4IntegratedAppPool">
    <virtualDirectory path="/" physicalPath="c:\Users\Ashley\documents\visual studio 2017\Projects\Filters\src\Filters" />
  </application>
  <bindings>
    <binding protocol="http" bindingInformation="*:51107:localhost" />
    **<binding protocol="https" bindingInformation="*:43107:localhost" />**
  </bindings>
</site>

It does however load the app up in the browser using the non-https port by default.  If you manually point your browser to the 43107 port it should work.
Edit
This worked for me a few times but stopped working.  Subsequent testing revealed that whenever I would click the button to start debugging in VS 2017 RC it would remove the binding I manually added.
I fixed that by making the file read-only now it's starting with HTTPS support again.

A:
I unfortunately had the same issue, couldn't see the "enable SSL" checkbox in the Debug tab of the Project's properties...
Finally found it! --> Set the launch on "IIS Express", then you will be able to select it ;-)

A: For Visual Studio 2019 and 2017:

*

*In Solution Explorer, right click the project > Properties

*Select the Debug Tab

*Check Enable SSL

A: One important point you may be missing is that you have to Run Visual Studio as adminsitrator (right vlick VS icon and select 'Run as Administrator'.
I have been strugling with this SSL problem and after by running VS as adminstrator I made it work.

A: If you see the SSL Enabled option under the project's Properties window, but it is greyed out

*

*Close Visual Studio

*Edit the vwd.webinfo file and add the sslPort="44317" attribute to the iisExpressSettings element.

*Alternatively, you can delete the vwd.webinfo file and Visual Studio will create a new one when you open the project


text:
Q: Android music player source code I need native (default) android music player source code. Where can I find it?

A: Take a look, here is the link for platform/frameworks/base:
https://android.googlesource.com/platform/frameworks/base

A: It's all on source.android.com; you can browse the list of packages, and the Music app is located at platform/packages/apps/Music.git.
There's a mirror on github.com/android. You can browse the source code of the Music app online at platform_packages_apps_music, with GitHub's fancier interface.


text:
Q: Broken links on terms list page I've registered a custom taxonomy for a custom post type. Every term on the admin term list page has a link to the list of posts filtered by that term.

This link should look like this:
for a custom post type:
.../edit.php?taxonomy-name=taxonomy-term-name&post_type=post-type-name
for posts:
.../edit.php?taxonomy-name=taxonomy-term-name
However, for my taxonomy the links do not have the post_type argument, resulting in links like .../edit.php?taxonomy-name=taxonomy-term-name which makes the links lead to regular posts list filtered by a term of a taxonomy they don't have. I can't figure out why this is.
My code:
//register a post type in a plugin
add_action( 'init', 'register_post_type_tdlrm_store_item', 10 );
function register_post_type_tdlrm_store_item() {
    $labels  = array(
        //omitted
    );
    $args = array(
        'label'                 => __( 'Item', 'text_domain' ),
        'description'           => __( 'Store items', 'text_domain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'thumbnail', 'comments', 'revisions' ),
        'taxonomies'            => array( 'store-category' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => false,
        'menu_position'         => 5,
        'menu_icon'             => 'dashicons-cart',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'post',
        'rewrite'               => array('slug' => 'product')
    );

    $args = apply_filters('tdlrm_filter: tdlrm_store_item: alter register_post_type arguments', $args);

    register_post_type( 'tdlrm_store_item', $args );

}

//register taxonomy in another plugin
add_action( 'init', 'register_ingredients_taxonomy', 99);
function register_ingredients_taxonomy(){
        $labels = array(
            //omitted
        );

        $args = array(
            'labels'            => $labels,
            'hierarchical'      => true,
            'public'            => true,
            'show_ui'           => true,
            'show_admin_column' => true,
            'show_in_nav_menus' => true,
            'show_tagcloud'     => false,
            'rewrite'           => array( 'slug' => 'ingredient' ),
        );

        register_taxonomy( 'tdlrm_ingredients', array( 'tdlrm_store_item' ), $args );
    }

//I tried to fix the situation
add_filter('tdlrm_filter: tdlrm_store_item: alter register_post_type arguments', 'alter_post_type_arguments');
function alter_post_type_arguments($arguments){
        if(!in_array('tdlrm_ingredients', $arguments['taxonomies'])){
            $arguments['taxonomies'][] = 'tdlrm_ingredients';
        }

        return $arguments;
    }

I don't understand why this gives me wrong links.
Also, I have re-saved permalinks just in case, to no effect.
Update
I get to the term list page via a custom link in a sub-menu. The link have been added like this:
add_action('admin_menu', 'add_menu_link', 50);
function add_menu_link(){
        add_submenu_page(
            'TDLRM',
            'Ingredients',
            'Ingredients',
            'edit_posts',
            'edit-tags.php?taxonomy=tdlrm_ingredients',
            ''
        );
    }

A:
However, for my taxonomy the links do not have the post_type argument

Yes, and it's because that argument does not exist in your submenu slug or relative URL (the 5th parameter for add_submenu_page()), therefore WordPress would not know that you're targeting your post type, and WordPress also would not add that argument to the links for filtering posts by your taxonomy at wp-admin/edit.php.
Remember that taxonomies can be attached to two or more post types, hence you should always include the post_type argument in your submenu link, even if your taxonomy will only ever going to have one post type. Because when that argument is missing or not specified, WordPress will not default to using the only post type attached to a taxonomy having just one post type attached.
So make sure to include that argument, just like WordPress does it when show_in_menu is not specified or is set to true:
add_submenu_page(
    'TDLRM',
    'Ingredients',
    'Ingredients',
    'edit_posts',
    'edit-tags.php?taxonomy=tdlrm_ingredients&post_type=tdlrm_store_item',
    ''
);

Additional Notes

*

*As I commented, you could actually set show_in_menu to the slug of a top-level menu page added using add_menu_page(), but you would want to use 9 or lower as the action's priority as in add_action( 'admin_menu', 'your_function', 9 ). More details here (see the 1st note)
And if that's not preferred (e.g. because you want another submenu item as the first one, but you need to use 10 or more as the action's priority), then just use 'show_in_menu' => false and manually call add_submenu_page() to add your post type as a submenu of your admin menu.


text:
Q: Abstracting mongo functions with NextJS I'm working on a new NextJS project that uses MongoDB.
Right now I'm having a hard time finding the best practices for next + mongo.
Would it be a good setup to have a /util/mongo folder where I store all my queries and mutations?
I could then use those in getServerSideProps.
Would appreciate any pointers to good reading material as well.
Thanks!


text:
Q: TS/ReactJS: can't change i18n language I am now using TypeScript on my project and my i18n system was working fine until then. Now I can't toggle my languages with "i18n.changeLanguage([language])" and I don't find where is the problem.
import "./App.css";
import React from "react";
import { Header } from "./Header/Header";
import { useTranslation } from "react-i18next";
import i18n from "./i18n";

export const App = () => {
  const { t } = useTranslation();

  const changeLanguage = (lng: string) => {
    i18n.changeLanguage(lng);
  };

  return (

       // the toggle is here and works just fine

  );
};

My i18n.ts file looks like this:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import fr from "./assets/locales/fr/translation.json";
import en from "./assets/locales/en/translation.json";

export const defaultNS = "fr";
export const resources = {
  fr: { fr },
  en: { en },
};

i18n.use(initReactI18next).init({
  lng: "fr",
  fallbackLng: "fr",
  ns: ["fr", "en"],

  interpolation: {
    escapeValue: false,
  },
  defaultNS,
  resources,
});

export default i18n;

I don't know if it could be important but I changed my "whitelist:" for "ns:" since it doesn't work with TS.

A: I finally find another way to process, but without the i18n library.
My i18n.ts file:
import french from "./assets/locales/fr/translation.json";
import english from "./assets/locales/en/translation.json";

export interface Translations {
  welcome: string;
  lang: string;
  // more variables and types...
}

const fr: Translations = french;
const en: Translations = english;

function getTranslations(language: string): Translations {
  switch (language) {
    case "fr":
      return fr;
    default:
      return en;
  }
}

export default getTranslations;

In my App.tsx :
import "./App.css";
import React, { useState } from "react";
import getTranslations from "./i18n";

export const App = () => {
  const [translate, setTranslate] = useState(getTranslations("fr"));

  const changeLanguage = (code: string) => {
    setTranslate(getTranslations(code));
  };
return (

       // the toggle is here
       // I can use the translated variables here

  );
};

In the end, I needed an interface for my JSON files, a switch case to change the languages and a state to update.


text:
Q: Using Regex to 'Clean Up' a List of Names I am using Regex to clean up a list of names so that they are normal. Let's say this list was...
000000AAAAAARob Alsod     ## Notice multiple 0's and A's?
AAAPerson Person          ## Here, too
Jeff the awesome Guy      ## Four words...
Jenna DEeath              ## A name like this can exist.
GEOFFERY EVERDEEN         ## All caps
shy guy                   ## All lowercase
Theone Normalperson       ## Example name. This one is fine.
  Guywith Whitespace      ## Trailing or leading whitespace is a nono.

So, as you can see, people don't format their names correctly, so I need a program to highlight all the unwanted stuff. This includes:

*

*Numbers at the start of the name.

*Any uppercase without lowercase after. i.e. AAAAAAAJosh

*Anything that is all uppercase.

*Anything that doesn't start with uppercase. i.e. josh

*Trailing and leading whitespace.
I think that is all I need to filter out. The ending product should look something like this:
Rob Alsod              ## No more 0's and A's.
Person Person          ## No more leading A's (or other letters).
Jeff Guy               ## No lowercase words in his name.
Jenna DEeath           ## HASN'T removed the D in the middle.
                       ## Name removed as it was all uppercase.
                       ## Name removed as it was all lowercase.
Theone Normalperson    ## Nothing changed.
Guywith Whitespace     ## Removed whitespace.

EDIT: Sorry about that. Here is my current code:
# Enter your code for "Name Cleaning" here.
import re
namenum = []
num = 0
for sen in open('file.txt'):
  namenum += [sen.split(',')]
  namenum[num][0] = re.sub(r'\s[a-z]+', '', namenum[num][0])
  namenum[num][0] = re.sub(r'^([0-9]*)', '', namenum[num][0])
  namenum[num][0] = re.sub(r'^[A-Z]*?\s[A-Z]*?$', '', namenum[num][0])
  namenum[num][0] = re.sub(r'[^a-zA-Z ][A-Z]*(?=[A-Z])', '', namenum[num][0])
  namenum[num][0] = re.sub(r'\b[a-z]+\b', '', namenum[num][0])
  namenum[num][0] = re.sub(r'^\s*', '', namenum[num][0])
  namenum[num][0] = re.sub(r'\s*$', '', namenum[num][0])
  if namenum[num][0] == '':
    namenum[num][0] = 'Invalid Name'
  num += 1
for i in range(len(namenum)):
  namenum[i][1] = int(namenum[i][1].strip())
namenum = sorted(namenum, key=lambda item: (-item[1], item[0]))
for i in range(0, len(namenum)):
  print(namenum[i][0]+','+str(namenum[i][1]))

It does half the job, but it misses out on some stuff for some reason.
Here is the output:
AAAAAARob Alsod
AAAPerson Person
Guywith Whitespace
Invalid Name
Invalid Name
Jeff Guy
Jenna DEeath
Theone Normalperson

I also tried inputting a name like harry hamilton and it gave back harry, which it should have removed.

A: This regex removes all your invalid examples. None of your examples requires the for loop which filters banned words, but I think you will need it.
Although this code removes all invalid names from a list it should be easy to modify it to request a new input from the user. Also it doesn't let you know why a name is invalid, but you could just display all the rules.
from re import match

def rules(name):
    for badWord in bannedWords:
        if name.lower().find(badWord) >= 0:
            return False
    return match(r'^([A-Z][a-z]+(?:[A-Z]?[a-z]+)* ?){1,}$', name)

bannedWords = ('really', 'awesome')
input = ['000000AAAAAARob Alsod', 'AAAPerson Person', 'Jeff the awesome Guy', 'Jenna DEeath', 'GEOFFERY EVERDEEN', 'shy guy', 'Theone Normalperson', '  Guywith Whitespace', 'Someone Middlename MacIntyre', '', 'Jack Really Awesome']
results = filter(rules, input)
print results

Produces the result:
['Theone Normalperson', 'Someone Middlename MacIntyre']

Without the for loop:
from re import match

def rules(name):
    return match(r'^([A-Z][a-z]+(?:[A-Z]?[a-z]+)* ?){1,}$', name)

input = ['000000AAAAAARob Alsod', 'AAAPerson Person', 'Jeff the awesome Guy', 'Jenna DEeath', 'GEOFFERY EVERDEEN', 'shy guy', 'Theone Normalperson', '  Guywith Whitespace', 'Someone Middlename MacIntyre', '', 'Jack Really Awesome']
results = filter(rules, input)
print results

Produces the result:
['Theone Normalperson', 'Someone Middlename MacIntyre', 'Jack Really Awesome']


text:
Q: Cannot find module error using jest on Next.js Hello i have some troubles making jest work on my nextjs application, when i use the script "jest" i always get a failed execution and this result

 FAIL  __tests__/index.test.tsx
  ● Test suite failed to run

    Cannot find module '@components/Layout' from 'pages/404.tsx'

    Require stack:
      pages/404.tsx
      __tests__/index.test.tsx

    > 1 | import { Layout } from '@components/Layout'
        |                                            ^
      2 | import { ContainerChild } from '@components/Container'
      3 | import { Button } from '@castia/components.ui.button'
      4 | import Image from 'next/image'

      at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:491:11)
      at Object.<anonymous> (pages/404.tsx:1:44)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.31 s
Ran all test suites.

this is my test file
import renderer from "react-test-renderer";
import NotFound from "../pages/404";

describe("404 NotFound page", () => {
  const tree = renderer.create(<NotFound />).toJSON();
  expect(tree).toMatchSnapshot();
});

and this is my component file
import { Layout } from '@components/Layout'
import { ContainerChild } from '@components/Container'
import Image from 'next/image'

import styles from '@styles/404.module.scss'

const metaTags = {
  title: 'Castia | 404',
  description: 'No encontramos la página que buscabas',
}

export default function NotFoundPage() {
  return (
    <Layout metaTags={metaTags}>
      <ContainerChild composition={'default'}>

            <Image
              src="/assets/image/error-404.png"
              alt="No encontramos la página que buscabas"
              width={475}
              height={304}
            />

¡Ups! No encontramos la página que buscabas.

            Revisa que hayas escrito correctamente el enlace o regresa a la
            página principal.

      </ContainerChild>
    </Layout>
  )
}

I have my jest.config.js file configured like this
const nextJest = require('next/jest')
const createJestConfig = nextJest({
  dir: './',
})
const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '^@/components/(.*)$': '<rootDir>/components/$1',
    '^@/pages/(.*)$': '<rootDir>/pages/$1',
    '^@/ui/(.*)$': '<rootDir>/ui/$1',
    '^@/api/(.*)$': '<rootDir>/api/$1',
    '^@/components/(.*)$': '<rootDir>/components/$1',
    '^@/context/(.*)$': '<rootDir>/context/$1',
    '^@/styles/(.*)$': '<rootDir>/styles/$1',
    '^@/lib/(.*)$': '<rootDir>/lib/$1',
    '^@/hooks/(.*)$': '<rootDir>/hooks/$1',
    '^@/utils/(.*)$': '<rootDir>/utils/$1',
  },
  testEnvironment: 'jest-environment-jsdom',
}

module.exports = createJestConfig(customJestConfig)

and my tsconfig.json like this
{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@ui/*": ["ui/*"],
      "@api/*": ["pages/api/*"],
      "@components/*": ["components/*"],
      "@context/*": ["context/*"],
      "@styles/*": ["styles/*"],
      "@lib/*": ["lib/*"],
      "@hooks/*": ["hooks/*"],
      "@utils/*": ["utils/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

but i dont know why this is happening to me

A: It seems you forgot to add the absolute path mapping in your tsconfig.json for the 'pages' directory.
Try adding this to your tsconfig.json
{...
"paths": {
   ... other paths mappings
  "@pages/*": ["pages/*"],
...
}

A: I think it should be "@/components" in your component file


text:
Q: How to get proportion of specific value across columns? I have a sample dataframe as below:
   self race1 race2 race3 race4
    1    1      2      2    1
    2    1      1      1    1
    3    1      3      1    1
    4    2      1      3    1

I would like to get the proportion of 1s in the race columns as a new column. So for each row, I would count the number of 1 and divide it by 4. The desired output dataframe would look like below.
   self race1 race2 race3 race4 prop_race_as1
    1    1      2      2    1     2/4
    2    1      1      1    1     4/4
    3    1      3      1    1     3/4
    4    2      1      3    1     2/4

How do I write a function that incorporate rowwise() to get the desired output?

A: Assuming your data is in df, you can get ratios as
ratios <- apply(data.matrix(df)[,-1], 1, function(x) length(which(x == 1)) / (ncol(df)-1))

then cbind(df, ratios).

A: Please find below two possibilities.
Reprex
1. With dplyr (and rowwise())

*

*Code

library(dplyr)

df %>%
  dplyr::rowwise() %>%
  dplyr::mutate(prop_race_as1 = sum(c_across(starts_with("race")) < 2) / 4)

*

*Output

#> # A tibble: 4 x 6
#> # Rowwise:
#>    self race1 race2 race3 race4 prop_race_as1
#>   <int> <int> <int> <int> <int>         <dbl>
#> 1     1     1     2     2     1          0.5
#> 2     2     1     1     1     1          1
#> 3     3     1     3     1     1          0.75
#> 4     4     2     1     3     1          0.5

2. Using only base R

*

*Code

df$prop_race_as1 <- rowSums(df[startsWith(names(df), "race")] < 2) / 4

*

*Output

df
#>   self race1 race2 race3 race4 prop_race_as1
#> 1    1     1     2     2     1          0.50
#> 2    2     1     1     1     1          1.00
#> 3    3     1     3     1     1          0.75
#> 4    4     2     1     3     1          0.50

Data
df <- structure(list(self = 1:4, race1 = c(1L, 1L, 1L, 2L), race2 = c(2L,
1L, 3L, 1L), race3 = c(2L, 1L, 1L, 3L), race4 = c(1L, 1L, 1L,
1L)), class = "data.frame", row.names = c(NA, -4L))

Created on 2022-02-16 by the reprex package (v2.0.1)