text:
Q: process hangs my application I am working on a university assignment, I have to lunch 3 servers that deal with client and a leader for the group of servers, here is the scenario:

*

*leader starts.

*leader runs 3 servers ( MUST run them as jar files using Runtime.getRuntime().exec();

*send activation message to the servers to start serving the clients

*client start to communicate with servers.

the problem is after 3 or 4 requests from the client the server hangs, and only complete its work if the the leader terminates.
If I run the jar files manually from the cmd everything works fine, the problem only rise if the leader lunch the jar files through process.
here is some code - server main node, which accept any new connection, either from the leader of the group or from the clients to be served:
public void startServer () throws IOException{
        //new LogSetup ( "logs/server/server.log" , Level.ALL );
        this.serverStatus = ServerStatuses.UNDER_INITIALIZATION;
        running = initializeServer ();
        if ( serverSocket != null ) {
            while ( isRunning () ) {
                try {
                    Socket client = serverSocket.accept ();
                    ConnectionThread connection = new ConnectionThread (
                            client , this );
                    new Thread ( connection ).start ();

                    logger.info ( "new Connection: Connected to "
                            + client.getInetAddress ().getHostName ()
                            + " on port " + client.getPort () );
                } catch ( IOException e ) {
                    logger.error ( "Error! "
                            + "Unable to establish connection. \n" , e );
                }
            }
        }
        logger.info ( "Server stopped." );
    }

thread for new connection:
public void run () {
        try {
            output = clientSocket.getOutputStream ();
            input = clientSocket.getInputStream ();

            while ( isOpen ) {
                try {
                    AbstractMessage msg = receiveMessage ();
                    handleRequest ( msg ); // to determine the connection type
                    /*
                     * connection either terminated by the client or lost due to
                     * network problems
                     */
                } catch ( IOException ioe ) {
                    logger.error ( "Error! Connection lost!" +ioe.getStackTrace ());
                    isOpen = false;
                }
            }

        } catch ( IOException ioe ) {
            logger.error ( "Error! Connection could not be established!" , ioe );

        } finally {

            try {
                if ( clientSocket != null ) {
                    input.close ();
                    output.close ();
                    clientSocket.close ();
                }
            } catch ( IOException ioe ) {
                logger.error ( "Error! Unable to tear down connection!" , ioe );
            }
        }
        logger.info ( "exit the thread" );
    }
private void handleRequest ( AbstractMessage msg ) throws IOException {
        logger.info ( "inside handling abstract message" );
        if ( msg.getMessageType ().equals ( MessageType.CLIENT_MESSAGE ) ) {
            handleClientRequest ( ( ClientMessage ) msg );
        } else if ( msg.getMessageType ().equals ( MessageType.SERVER_MESSAGE ) ) {
            handleServerRequest ( ( ServerMessage ) msg );
        } else if ( msg.getMessageType ().equals ( MessageType.ECS_MESSAGE ) ) {
            handleECSRequest ( ( ECSMessage ) msg );
        }
        logger.info ( "finish handling " );

    }

A: The Leader process has to process the input/output/error from your servers. When a server loggs something, this is written to System.out (thats the default behaviour of most log frameworks). Since your leader startet the server process the output is written to a pipe. If the pipe buffer is full, the log blocks and your server 'hangs'.


text:
Q: rspec: syntax error, unexpected keyword_end, expecting end-of-input (SyntaxError) This is completely stumping me. Similar threads have suggested this error message:
syntax error, unexpected keyword_end, expecting end-of-input (SyntaxError)
is because I am missing an "end" somewhere in my rspec file. I have combed through it and can't see where an end would be suitable. Here is my program and spec file:
require "calculator"

describe "add" do
  it "adds 0 and 0" do
    add(0,0).should == 0
  end

  it "adds 2 and 2" do
    add(2,2).should == 4
  end

  it "adds positive numbers" do
    add(2,6).should == 8
  end
end

describe "subtract" do
  it "subtracts numbers" do
    subtract(10,4).should == 6
  end
end

describe "sum" do
  it "computes the sum of an empty array" do
    sum([]).should == 0
  end

  it "computes the sum of an array of one number" do
    sum([7]).should == 7
  end

  it "computes the sum of an array of two numbers" do
    sum([7,11]).should == 18
  end

  it "computes the sum of an array of many numbers" do
    sum([1,3,5,7,9]).should == 25
  end
end

describe "#multiply" do

  it "multiplies two numbers" do
      mutiply([3, 4]).should == 12
  end

  it "multiplies several numbers"
    multiply([2, 5, 8]).should == 80
  end
end
describe "#power" do
  it "raises one number to the power of another number" do
      power(2, 3).should == 8
  end
end

describe "#factorial" do
  it "computes the factorial of 0" do
      factorial(0).should == 1
  end
  it "computes the factorial of 1"
        factorial(1).should == 1
  end
  it "computes the factorial of 2"
        factorial(2).should == 2
  end
  it "computes the factorial of 5"
        factorial(5).should == 120
  end
  it "computes the factorial of 10"
    factorial(10).should == 3628800
  end
end

My code:
def add(x, y)
  x + y
end

def subtract(x, y)
  x - y
end

def sum(an_array)
  if an_array = []
    return 0
  else
  sum = 0
  an_array.each { |n| sum += n }
  sum
  end
end

def multiply(some_array)
  if some_array == []
    return 0
  else
  product = 1
  some_array.each { |n| product = product * n }
  product
  end
end

def power(base, exp)
  out = 1
  exp.times { out = out * base }
  out
end

def factorial(n)
  if n = 0
    1
  else
    n * factorial(n - 1)
  end
end

The full error message is:
Juliuss-MacBook-Pro:02_calculator juliushamilton$ rake
(in /Users/juliushamilton/learn_ruby-master)
/Users/juliushamilton/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `load': /Users/juliushamilton/learn_ruby-master/02_calculator/calculator_spec.rb:89: syntax error, unexpected keyword_end, expecting end-of-input (SyntaxError)
    from /Users/juliushamilton/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `block in load_spec_files'
    from /Users/juliushamilton/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `each'
    from /Users/juliushamilton/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:896:in `load_spec_files'
    from /Users/juliushamilton/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/rspec-core-2.14.8/lib/rspec/core/command_line.rb:22:in `run'
    from /Users/juliushamilton/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/rspec-core-2.14.8/lib/rspec/core/runner.rb:80:in `run'
    from /Users/juliushamilton/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/rspec-core-2.14.8/lib/rspec/core/runner.rb:17:in `block in autorun'
/Users/juliushamilton/.rvm/rubies/ruby-2.0.0-p451/bin/ruby -S rspec /Users/juliushamilton/learn_ruby-master/02_calculator/calculator_spec.rb -I/Users/juliushamilton/learn_ruby-master/02_calculator -I/Users/juliushamilton/learn_ruby-master/02_calculator/solution -f documentation -r ./rspec_config failed

Thanks very much.

A: Got it..
Look below -
describe "#multiply" do

  it "multiplies two numbers" do
    mutiply([3, 4]).should == 12
  end

  it "multiplies several numbers"  # you missed "do" here
    multiply([2, 5, 8]).should == 80
  end
end

Corrected one is -
describe "#multiply" do

  it "multiplies two numbers" do
    mutiply([3, 4]).should == 12
  end

  it "multiplies several numbers" do
    multiply([2, 5, 8]).should == 80
  end
end

This things can be easily find out by using editor specifc indentation. I use Gvim, where I used gg=G, which has shown me where is wrong indentation. You can use your editor specific one to do the same.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Manipulating Multi Dimensional array and representation I want to find out which user is not part of other games available in database  i get an array as following
$arr2=Array
(
    (0) => Array
        (
            (uid) => 1,
            (game_id) => 22
        ),

    (1) => Array
        (

            (uid) => 2,
            (game_id) => 22
        )
    (2) => Array
        (

            (uid) => 1,
            (game_id) => 23
        )
    (3) => Array
        (

            (uid) => 3,
            (game_id) => 24
        )
);

For example User 1 is in Game 22,23 BUT NOT IN 24 user 3 is in only game 24
I want to find out which user is not participating in other game, Issue is effeciency(speed of execution)
and how to represent in array so as i can use it to display.Is it god idea to have it like
userid=> notInGame,notInGame (CSV)?

A: An example of how to do it in PHP:
$array = array(
    array
    (
        'uid' => 1,
        'game_id' => 22
    ),
    array
    (
        'uid' => 2,
        'game_id' => 22
    ),
    array
    (
        'uid' => 1,
        'game_id' => 23
    ),
    array
    (
        'uid' => 3,
        'game_id' => 24
    ),

);

$games = $users = array();

foreach($array as $value)
{
    $games[]                = $value['game_id'];
    $users[$value['uid']][] = $value['game_id'];
}

foreach($users as $uid => $user)
{
    $users[$uid] = array_diff($games, $user);
}

print_r($users);

Result (key is the uid):
Array
(
    [1] => Array
        (
            [3] => 24
        )

    [2] => Array
        (
            [2] => 23
            [3] => 24
        )

    [3] => Array
        (
            [0] => 22
            [1] => 22
            [2] => 23
        )

)

A: Below is quite simple query if You don't need id of groups. The num field is a number of groups the user is in.
SELECT `uid`, COUNT(*) AS `num`
FROM `a_table`
GROUP BY `uid`;

You will get something like this
$arr2=Array
(
    (0) => Array
        (
            (uid) => 1,
            (num) => 2
        ),

    (1) => Array
        (

            (uid) => 2,
            (num) => 1
        )
    (2) => Array
        (

            (uid) => 3,
            (num) => 1
        )
);


text:
Q: Printing Present working directory in c using pointers Aim : Print present working directory in c on Linux machine.
Without using pointers, it is giving correct output..
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
int main()
{
    //char buf[1024];

    char * buf;
    char * cwd;
    buf = (char *)malloc(sizeof(char) * 1024);

    if((cwd = getcwd(buf, sizeof(buf))) != NULL)
            printf("pwd : %s\n", cwd);
    else
            perror("getcwd() error : ");
    return 0;
}

But with pointer it shows following error
getcwd() error : : Numerical result out of range

A: This is because when buf is a pointer, sizeof(buf) is the number of bytes required to store a pointer, not the size of the array, as in the code that you commented out.
You need to pass the size that you allocated (i.e. 1024) instead, like this:
size_t allocSize = sizeof(char) * 1024;
buf = (char *)malloc(allocSize);
if((cwd = getcwd(buf, allocSize)) != NULL) ...

A: sizeof(buf) will return the size of char* which will be however many bits wide your processor is (32 bits or 64 bits).
What you want is to use the magic number you malloc'ed with, in this case 1024.
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main()
{
    //char buf[1024];

    char * buf;
    char * cwd;
    buf = (char *)malloc(sizeof(char) * 1024);

    if((cwd = getcwd(buf, 1024)) != NULL)
            printf("pwd : %s\n", cwd);
    else
            perror("getcwd() error : ");
    return 0;
}

A: char *getcwd(char *buf, size_t size);
Here you are giving the size as sizeof(buf) which will return the size of the buf pointer which will be machine dependent.
You have to specify 1024 in the argument to getcwd.


text:
Q: spliting string with double new line characters I have a .txt file, the data of which I have stored in a long string. There are many single new line characters in the string after every line. And there are double new line characters at the end of paragraphs. What I want is to split the string into an array of paragraphs.
what I thought is the following but it is not working
string filePath = "C:\\Users\\Data.txt";
StreamReader readFile = new StreamReader(filePath);
string Data = readFile.ReadToEnd();
string[] paragraphss = Regex.Split(Data, "(^|[^\n])\n{2}(?!\n)");

please help
thank you

A: If you're OK with not using regex, Data.Split("\n\n") should do the trick.

A: On windows systems the newline character is \r\n, on Unix systems it is \n.  This may be why the lines aren't being split, because you're specifically looking for \n\n instead of \r\n\r\n.
You can however use Environment.Newline, which will return the correct newline character for whatever environment the software is running on.

A: Inspired by @LueTm's answer and @Traubenfuchs' comment, just making it look compiler friendly and complete. Here's how to split a string with double new line characters:
Data.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.None);


text:
Q: Given $\sec \theta + \tan \theta = 5$ , Find $\csc \theta + \cot \theta $. The question is to find the value of $ \csc  \theta + \cot \theta $ if $\sec  \theta + \tan \theta = 5$ .
Here is what I did :
$\sec  \theta + \tan \theta = 5$
$\sec  \theta = 5 -  \tan \theta $
Squaring both sides ,
 $$\sec^2  \theta = 25  + \tan^2 \theta -10\tan \theta$$
Substituting $1+\tan^2 \theta$ for $\sec^2 \theta$ ,
$$1+\tan^2 \theta = 25 + \tan^2 \theta -10\tan \theta$$
Thus , $$\tan \theta=24/10$$
So , $\cot \theta = 10/24 $ and $\csc \theta=26/24$
Thus $ \csc  \theta + \cot \theta =3/2$ .
But I checked the answer sheet and the answer is not 3/2 but $(3+\sqrt5 )/2$ .
Where have I went wrong ? Please help.

A: As noted in the comments, you are correct, and the answer key is wrong here.
In cases like these, it's sometimes helpful to check to make sure that you didn't make a mistake in reading the question.

A: Here is a simpler solution to this problem:
$$\left(\sec(\theta)+\tan(\theta) \right)\left(\sec(\theta)-\tan(\theta) \right)=\sec^2(\theta)-\tan^2(\theta)=1$$
Since $\sec(\theta)+\tan(\theta)=5$ you get $\sec(\theta)-\tan(\theta)=\frac{1}{5}$.
Adding and subtracting these two relations you get
$$2\sec(\theta)=5+\frac15=\frac{26}{5} \,;\, 2\tan(\theta)=5-\frac15=\frac{24}{5}$$
Thus $\tan(\theta)=\frac{24}{10}$ and
$$\sin(\theta)=\frac{\tan(\theta)}{\sec(\theta)}=\frac{24}{26} \,.$$

A: The problem is that the methods you have give all ok so long it works but nothing if it fails.
When in doubt it is better to check with nearby approximate solutions learning to guide/trust yourself.
Say even if you took very approximately 60 degrees as solution and calculated $  sec  (\theta) + tan(\theta) $ it will be nearer to what you got than the way off value   provided by key!

A: Too long for a comment:
...
THIS IS HOW I THINK THE ANSWER SHEET WRITER DID THE MISTAKE:
Normally the equation is
$$\sin\theta+1=5\cos\theta.$$
Squaring they  "mistakenly" got $\sin^2\theta+2\sin\theta+1=5\cos^2\theta\implies$ $\sin^2\theta+2\sin\theta+1=5-5\sin^2\theta\implies$ $3\sin^2\theta+\sin\theta-2=0\implies$ $(3\sin\theta-2)(\sin\theta+1)=0$.
Thus, $\sin\theta=\frac{2}{3}$ is a solution. Finally, $\csc\theta=\frac{3}{2}$, $\cot\theta=\frac{\sqrt{5}}{2}$ and $\csc\theta+\cot\theta=\frac{3+\sqrt{5}}{2}$.
CORRECT SOLUTION:
But in fact squaring we get $(13\sin\theta-12)(\sin\theta+1)=0$.
Thus, $\sin\theta=\frac{12}{13}$ is a solution. Finally, $\cot\theta=\frac{5}{12}$, $\csc\theta=\frac{13}{12}$ and
$$\csc\theta+\cot\theta=\frac{13+5}{12}=\frac{3}{2}.$$


text:
Q: Android Studio doesn't install SDKs... what? I'm trying to use Cordova to build a hello world app and after adding ANDROID_HOME variable (You'd be shocked how long that took to figure out) all I keep seeing when building is this:

BUILD FAILED
Total time: 1 mins 6.679 secs Error:
  /Users/vladdy/Desktop/laboratory/cordovaBackgroundApp/platforms/android/gradlew:
  Command failed with exit code 1 Error output:
FAILURE: Build failed
  with an exception.

*

*What went wrong: A problem occurred configuring root project 'android'.

Failed to find target with hash string 'android-25' in: /Users/vladdy/Library/Android/sdk

*Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Ok fair enough so let's go install it:

Waiting patiently for the install, and same error running cordova build.
I wonder what else we need to install? But look, it seems that Android Studio still has Nougat and 25 available:

Why is Android Studio not installing anything?
I can see why PhoneGap Build is so popular...
Edit:
cordova requirements is now broken reporting the following:

My ~/.bash_profile:
export ANDROID_HOME=/Users/vladdy/Library/Android/sdk/

A: Requirements?
If you don't need Android Studio, I recommend not downloading it, instead, as @Tom-Esendam also suggest, go for the command-line tool.
Android Studio and Command Line Tool
Direct download link of Command Line Tool for OSX (2017-03-21)
Proxy?
And if your behind a proxy server, don't forget to add it to the settings in the SDK Manager Settings.
What does the different programs and commands?
cordova build doesn't download any SDK's.
cordova prepare appends the necessary SDK files to the cordova build folders.
After download of Command Line Tool:
After unzipping it, set ANDROID_HOME to it's root, so you have:

*

*build-tools

*extras

*platforms

*platform-tools

*system-images

*tools

catalogs under the root.
Adding SDK's:
Then install SDK's with ./tools/android.
Android SDK Manager downloads the SDK's, so you check what you need and hit OK to download it.
Preparing the build

*

*Make sure all proxy settings are set if your behind a proxy.

*Before running cordova build run cordova prepare. This shouldn't be necessary, but least I need to run that even thou cordova build should include that.

A: I don't know about the mac version. But on windows you have a standalone sdk manager. If there is one on mac try that?


text:
Q: "interrupt function contains function calls" gcc error In my code I get this

"error: interrupt function contains function calls: foo"

when compiling with the toolchain: riscv32-unknown-elf-gcc (gcc version 5.2.0 (GCC))
but not with this toolchain riscv32-corev-elf-gcc (gcc version 11.0.0 20200813 (experimental)
Having function call in ISR could be bad but that is not the point, I can't get rid of legacy.
How could I disable this error?
in my code I have defined interrupt using:
__attribute__((interrupt))

could this be the cause? not supported attribute?
when I remove the attribute, the error disappears, so I'll need to have prologue/epilogue sequences in assembly I guess
but this is strange because it says it supports it:
https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html#RISC-V-Function-Attributes
could it exist any gcc flag that could disable this error?
note: hard to have a minimal reproducible example as there is no gcc riscv compiler < 8.0 on godbolt.com

A: using gcc version 5.2.0 (GCC),
you are not allowed to have the attribute keyword with the interrupt declaration, only with the interrupt definition.
BUT, that SHOULD not be used, because epilogue/prologue are not well generated, so interrupt won't work, you'll have to manually write a generic epilogue and prologue for all irqs.


text:
Q: AWS Cognito - returning user - how to design well I have a question relating designing a Cognito Authentication and its flow in my app.
I managed to get logging in etc. However, a great "pain" happens when I have to reauthenticate users (as they access expires every 60 minutes as we all know). Now I am thinking how to solve it for a returning user.

*

*Set a service which would every 59 minutes relog the user (if he does not sign out) - do it somehowe all the time in the background.
a) how not to lose it when the app is turned on?

*Set in the SplashScreen automatical relog - everytime I turn on the app, I relog in the background (update my session). This can work after a long time, as Refresh Token is valid for 30 days. After 30 days of not using the app we might expect the user to write down his details again. However, how to get a Refresh Token from a previous session? I would not like to store it in SharedPreferences or anything like that.
Which one to choose? What advice would you give me?
Thank you in advance!
Grzegorz

A: When you successfully authenticate, do you get a refresh token? The access token expires after 60 minutes, but you can use the refresh token to get new access token without re-authentication.


text:
Q: how to disable one button when clicked in mat table Angular material I have a problem, I have a mat table and inside this table I have a column to display buttons. The problem is that when I click on one button, all of them disable when I only want to disable the one I click...
my .html:
<table *ngIf="buildingImageList.length > 0" mat-table [dataSource]="buildingImageList" class="mat-elevation-z8">
<ng-container matColumnDef="buildId">
<th mat-header-cell *matHeaderCellDef> Cancel </th>
<td mat-cell *matCellDef="let element">
<button mat-flat-button color="accent" [disabled]="clicked"
(click)="cancelBuildingImage(element.buildId); clicked = true;">
Cancel build
</button>
</td>
</ng-container>
</table>

my .ts:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { BuildingImage } from "../buildingImage.model";
import { BuilderService } from "../../builder.service";
import { SnackMessageService } from "app/main/common/services/snackMessage.service";

@Component({
  selector: "building-images",
  templateUrl: "./building-images.component.html",
  styleUrls: ["./building-images.component.scss"]
})
export class BuildingImagesComponent implements OnInit, OnDestroy {
  buildingImageList: BuildingImage[];
  displayedColumns: string[] = ["tag", "created", "startedBuilding", "finishDate", "buildId"];
  buildingImageErrorMessage: string;
  callLoop: any;
  clicked: boolean;

  constructor(private builderService: BuilderService, private snackMessageService: SnackMessageService) {
    this.buildingImageList = new Array();

    this.clicked = false;

A: How about to translate clicked to an array.
my .ts:
clicked  = new Array();

ngOnInit() {
  this.buildingImageList.foreach(el => {
    this.clicked.push(false);
  });
}

Then you just need to be aware of which line number you are clicking. For that, you can append let i=index to your for loop (which is matCellDef in matTable).
my.html
<table *ngIf="buildingImageList.length > 0" mat-table [dataSource]="buildingImageList" class="mat-elevation-z8">
<ng-container matColumnDef="buildId">
<th mat-header-cell *matHeaderCellDef> Cancel </th>
<td mat-cell *matCellDef="let element; let i=index">
<button mat-flat-button color="accent" [disabled]="clicked[i]"
(click)="cancelBuildingImage(element.buildId); clicked[i] = true;">
Cancel build
</button>
</td>
</ng-container>
</table>


text:
Q: Gecko XPCOM usage vs WebKit I need to embed a web browser in C++ application. As well, I need to reach its javascript methods from Delphi components.
I know that for FF there is Gecko with XPCOM. Is there something like this for WebKit?

A: WebKit first: there's project called Chromium embedded (Chromium is basically WebKit rendering engine and V8 Javascript engine), that has also Delphi support. After a quick look into headers, I did not find a way to access JS methods, but it allows executing javascript snippets in given frame:
// Execute a string of JavaScript code in this frame. The |script_url|
// parameter is the URL where the script in question can be found, if any. The
// renderer may request this URL to show the developer the source of the
// error.  The |start_line| parameter is the base line number to use for error
// reporting.
execute_java_script: procedure(self: PCefFrame; const jsCode, scriptUrl: PWideChar; startLine: Integer); stdcall;

So the pieces are there, you just need to figure out how to patch them together.
For Gecko, there are Delphi bindings available under a project called d-gecko. But it seems to be a bit outdated and also does not seem to allow accessing the Javascript.

A: You may take a look at this project which allows you to embed the chromium web browser in Delphi applications.


text:
Q: Configuring solr to match over punctuation, e.g. 'tshirt' matches 't-shirt' I'm using Solr to index products on a clothing website. At the moment I'm trying to get Solr to match t-shirt based on the search term tshirt, but I'm a little bit lost as to what filters to I need.
This is the general purpose field type that I'm using to index most fields at the moment:
<fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="lang/stopwords_en.txt" enablePositionIncrements="true" />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.EnglishPossessiveFilterFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
    <filter class="solr.PorterStemFilterFactory"/>
    <filter class="solr.WordDelimiterFilterFactory" catenateWords="1" catenateAll="1" preserveOriginal="1"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="lang/stopwords_en.txt" enablePositionIncrements="true" />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.EnglishPossessiveFilterFactory"/>
    <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
    <filter class="solr.PorterStemFilterFactory"/>
    <filter class="solr.WordDelimiterFilterFactory" catenateWords="1" catenateAll="1" preserveOriginal="1"/>
  </analyzer>
</fieldType>

I tried removing WordDelimiterFilterFactory from the index and query analyzers, but it didn't help. Any advice/best practice would be really appreciated.

A: You'll want to have the WordDelimiterFilter further up your chain, and you'll want to use the Whitespace Tokenizer instead. The example on the wiki does just that.
The issue now is that the tokens are split into separate tokens earlier on, and the worddelimeterfilter is only seeing each token by itself. So it sees the t, then shirt and doesn't really have anything to do.
By using the whitespace tokenizer you'll get the WDF to see "t-shirt", allowing it to generate t, shirt, tshirt, etc.
Use the "Analysis" page under the Solr Admin to see each step in the analysis and what the result is.


text:
Q: How to show a notice to plugin update I would like to show an admin notice (https://codex.wordpress.org/Plugin_API/Action_Reference/admin_notices) when my plugin has a update.
Like this:

How to do this?

A: Assuming that your plugin is in the WordPress repository, then you can do this by hooking into the WordPress update functionality. Note that get_site_transient() is always used by falls back to the get_option() when it is not a multisite install..
// Your plugin file
$plugin = 'plugin-dir/plugin-file.php';

// Check for Plugin updates, if you want to (not recommended for all pages)
// wp_update_plugins();

// Results of the update check
$update_plugins = get_site_transient( 'update_plugins' );
if ( isset( $update_plugins->response[ $plugin ] ) ) {
    // Your plugin needs an update
}

In the result of update_plugins the $update_plugins->response is an array() that will be something like this:
'response' =>
  array (
    'plugin-dir/plugin-file.php' =>
    stdClass::__set_state(array(
       'id' => '12345',
       'slug' => 'plugin-file',
       'plugin' => 'plugin-dir/plugin-file.php',
       'new_version' => '1.2.3',
       'url' => 'https://wordpress.org/plugins/plugin-dir/',
       'package' => 'https://downloads.wordpress.org/plugin/plugin-dir.1.2.3.zip',
    )),
),


text:
Q: Key value parser implementation with CSV parser in java I am writing a program to parse key value based log like this:
dstcountry="United States" date=2018-12-13 time=23:47:32

I am using Univocity parser to do that. Here is my code.
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.getFormat().setDelimiter(' ');
parserSettings.getFormat().setQuote('"');
parserSettings.getFormat().setQuoteEscape('"');
parserSettings.getFormat().setCharToEscapeQuoteEscaping('"');
CsvParser keyValueParser = new CsvParser(parserSettings);
String line = "dstcountry=\"United States\" date=2018-12-13 time=23:47:32";
String[] resp = keyValueParser.parseLine(line);

But the parser gives me this output:
dstcountry="United,
States",
date=2018-12-13,
time=23:47:32

where the expected output was
dstcountry="United States",
date=2018-12-13,
time=23:47:32

Is there any problem with the code or is this a parser bug?
Regards,
Hari

A: Author of the lib here. This is not a parser bug. The problem you have here is that you are NOT parsing a CSV file.
When the parser sees: dstcountry="United, followed by a space (which is your delimiter), it will consider that as a value.
The quote setting only applies to fields that start with a quote character. As your input is not "dstcountry=""United States""", the parser won't be able to process this as you want. There is no CSV parser that can do that for you.
Again, you are not processing a CSV. The only thing you could do here is to use 2 parser instances: one to break down the row around the = and another one to break down values separated by  in the result of the first parser. For example:
    CsvParserSettings parserSettings = new CsvParserSettings();
    //break down the rows around the `=` character
    parserSettings.getFormat().setDelimiter('=');

    CsvParser keyValueParser = new CsvParser(parserSettings);
    String line = "dstcountry=\"United States\" date=2018-12-13 time=23:47:32";
    String[] keyPairs = keyValueParser.parseLine(line);

    //break down each value around the whitespace.
    parserSettings.getFormat().setDelimiter(' ');
    CsvParser valueParser = new CsvParser(parserSettings);

    //add all values to a list
    List<String> row = new ArrayList<String>();

    for(String value : keyPairs){
        //if a value has a whitespace, break it down using the the other parser instance
        String[] values = valueParser.parseLine(value);

        Collections.addAll(row, values);
    }

    //here is your result
    System.out.println(row);

This will print out:
[dstcountry, United States, date, 2018-12-13, time, 23:47:32]
You now have the key values. The following code will print this out as you want:
    for (int i = 0; i < row.size(); i += 2) {
        System.out.println(row.get(i) + " = " + row.get(i + 1));
    }

Output:
dstcountry = United States
date = 2018-12-13
time = 23:47:32
Hope this helps and thank you for using our parsers!

A: I ended up writing my own parser. I am pasting here for future references if anybody needs. suggestions and comments are welcome.
private static final int INSIDE_QT = 1;
private static final int OUTSIDE_QT = 0;

public String[] parseLine(char delimiter, char quote, char quoteEscape, char charToEscapeQuoteEscaping, String logLine) {
           char[] line = logLine.toCharArray();
    List<String> strList = new ArrayList<>();
    int state = OUTSIDE_QT;
    char lastChar = '\0';
    StringBuffer currentToken = new StringBuffer();
    for (int i = 0; i < line.length; i++) {
        if (state == OUTSIDE_QT) {
            if (line[i] == delimiter) {
                strList.add(currentToken.toString());
                currentToken.setLength(0);
            } else if (line[i] == quote) {
                if (lastChar == quoteEscape) {
                    currentToken.deleteCharAt(currentToken.length() - 1);
                    currentToken.append(line[i]);
                } else {
                    if (removeQuotes == false) {
                        currentToken.append(line[i]);
                    }
                    state = INSIDE_QT;
                }
            } else if (line[i] == quoteEscape) {
                if (lastChar == charToEscapeQuoteEscaping) {
                    currentToken.deleteCharAt(currentToken.length() - 1);
                    currentToken.append(line[i]);
                    continue;
                } else {
                    currentToken.append(line[i]);
                }
            } else {
                currentToken.append(line[i]);
            }
        } else if (state == INSIDE_QT) {
            if (line[i] == quote) {
                if (lastChar != quoteEscape) {
                    if (removeQuotes == false) {
                        currentToken.append(line[i]);
                    }
                    if (currentToken.length() == 0) {
                        currentToken.append('\0');
                    }
                    state = OUTSIDE_QT;
                } else {
                    currentToken.append(line[i]);
                }
            } else if (line[i] == quoteEscape) {
                if (lastChar == charToEscapeQuoteEscaping) {
                    currentToken.deleteCharAt(currentToken.length() - 1);
                    currentToken.append(line[i]);
                    continue;
                } else {
                    currentToken.append(line[i]);
                }
            } else {
                currentToken.append(line[i]);
            }
        }
        lastChar = line[i];
    }
    if (lastChar == delimiter) {
        strList.add("");
    }
    if (currentToken.length() > 0) {
        strList.add(currentToken.toString());
    }
    return strList.toArray(new String[strList.size()]);
}


text:
Q: Distributing gloves to six sisters
Given $6$ distinct pairs of gloves, $12$ distinct gloves in all, how many ways are there to distribute $2$ gloves to each of $6$ sisters, regardless of whether they receive a wearable pair of a right handed glove and a left handed glove.

I'm having trouble with this problem. Can someone give me some hints on how to approach it?

A: It's $\frac{12!}{(2!)^6}$, consider all possible permutations of the gloves, and then give the first two to the first sister, the next two to the second and so on.


text:
Q: Do Python's `*` and `**` specifiers have a name?
Possible Duplicate:
proper name for python * operator?

* is clearly used when unpacking an arbitrary number of arguments and
** is used when unpacking keyword arguments as a dictionary.
It is conventional to use *args and **kwargs, and I tend to pronounce these as "args" and "quargs", ignoring the *s.
In this question, the asterisk was referred to as a pointer.
How does the BDFL refer to these symbols?

Following closure.
Thanks for finding the linked question, this is what I was looking for. It's really tricky to search (even very specific areas of) the web accurately for *!
To the commentators who responded with how they pronounce "*", that was not the question I was asking (and apologies if my question mislead you). What I wanted to know is how these specifiers are named in Python, this was not a subjective question (hence the reference to the BDFL).


text:
Q: Correct use of Reap/Sow to optimize the code I am trying to compare two functions on the end points of an interval.
For instance, $f_1(t)=t^3$ and $f_2(t)=t^4$. From my code below I check whether $f_1(t)\leq f_2(t)$ when $t=50$ on $[50, 51]$ and if it is then I store values $\{\{f_1(50), f_2(50)\}\}$ and then I move to $t=51$ and store it as $\{f_1(50), f_2(50)\},\{f_1(51), f_2(51)\} \}$ and so on until I reach $t=55$. I am using Sow/Reap to build my list. Here is my code:

f1[t_] := t^3
f2[t_] := t^4

n = 0;
T = 50;
k = 1;
lst = {};
Reap[While[T + n*k <= 55,
  If[f1[T + n*k] <= f2[T + n*k], Sow[{f1[T + n*k], f2[T + n*k]}];
   n = n + 1, Print[T + n*k]]]
 ]
lst

My questions:

*

*Using Reap/Sow in this manner gives me some extra $\{\}$ and an output of "Null" as my first element. What would be the correct way of using them in this case? (I wasn't able to get this clarification from their documentation.)

*Is there a quicker way to build such a list since in application I will have large "t" of the order of $10^6$ or $10^7$ instead of $50$ (and complicated $f_1, f_2$)? So far Reap/Sow I found to be the fastest.

A: The extra Null and {} is just Reap/Sow working as expected, there is nothing to fix. The Null is the value of the expression. The extra {} that wraps the result is there because if you use tags then the values will be grouped by those tags:
Reap[
 Sow[a, "key1"];
 Sow[b, "key1"];
 Sow[c, "key2"];
 value
 ]

{value, {{a, b}, {c}}}

So then clearly, if you only have one group, the form of the expression should be {{a, b, c}} (i.e., there should be an extra set of brackets.)
Reap/Sow is usually what we resort to when we have lists of unknown length, to avoid having to use the awfully slow Append. But for your case, there may be much faster solutions because as long as you don't run into memory problems, you shouldn't need to grow the list dynamically. Here's something that I would try:
With[
   {range = Range[10^6]},
   f1Values = f1[range];
   f2Values = f2[range];
   res = Pick[Transpose[{f1Values, f2Values}],
     UnitStep[f2Values - f1Values], 1];
   ]; // AbsoluteTiming

{7.39647, Null}

In practice, you should probably only go for the loop solution if you run into memory problems. If your functions are not listable then that may also affect the type of solution. Perhaps the best solution will then be a "bag" data structure used in conjunction with Compile.


text:
Q: I can't send data to database using ajax and php For some reason I can't get data to send to my database using ajax and php.
I click the add to cart button, the success message doesn't show up at all, and no data is sent to the database. No errors show up at all. What is going on here?
<form action="includes/addcart.inc.php?id=<?= $row['id'] ?>" class="cart-form">
    <input type="hidden" class="pid" value="<?= $row['id'] ?>">
    <input type="hidden" class="pname" value="<?= $row['product_name'] ?>">
    <input type="hidden" class="pprice" value="<?= $row['product_price'] ?>">
    <input type="hidden" class="pimage" value="<?= $row['product_image'] ?>">
    <input type="hidden" class="pcode" value="<?= $row['product_code'] ?>">
    <input type="submit" class="atcbutton btn btn-info btn-block" name="Add To Cart" value="Add To Cart">
  </form>

Here is the form I'm using.
$(document).ready(function() {
  // Send product details in the server
  $('.cart-form').submit(function(e) {
    e.preventDefault();
    var $form = $(this).closest(".cart-form");
    var pid = $form.find(".pid").val();
    var pname = $form.find(".pname").val();
    var pprice = $form.find(".pprice").val();
    var pimage = $form.find(".pimage").val();
    var pcode = $form.find(".pcode").val();

    var pqty = $form.find(".pqty").val();

    $.ajax({
      url: 'includes/addcart.inc.php',
      method: 'POST',
      data: {
        pid: pid,
        pname: pname,
        pprice: pprice,
        pqty: pqty,
        pimage: pimage,
        pcode: pcode
      },
      success: function(response) {
        $("#message").html(response);
      }
    });
  });
});

Here's the js and ajax.
<?php
require 'dbh.inc.php';

if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
    $pname = $_POST['pname'];
    $pprice = $_POST['pprice'];
    $pimage = $_POST['pimage'];
    $pcode = $_POST['pcode'];
    $pqty = $_POST['pqty'];
    $total_price = $pprice * $pqty;

    $sql = ('SELECT product_code FROM cart WHERE product_code=?');
    $stmt = mysqli_stmt_init($conn);
    mysqli_stmt_prepare($stmt, $sql);
    mysqli_stmt_bind_param($stmt, 's', $pcode);
    mysqli_stmt_execute($stmt);
    $res = mysqli_stmt_get_result($stmt);
    $r = mysqli_fetch_assoc($res);
    $code = $r['product_code'] ?? '';

    if (!$code) {
      $query = ('INSERT INTO cart (product_name, product_price, product_image, qty, total_price, product_code) VALUES (?,?,?,?,?,?)');
      mysqli_stmt_init($conn);
      mysqli_stmt_bind_param($query, 'ssssss', $pname, $pprice, $pimage, $pqty, $total_price, $pcode);
      mysqli_stmt_execute($query);

      echo '

              <button type="button" class="close" data-dismiss="alert">×</button>
              Item added to your cart!

';
    } else {
      echo '

              <button type="button" class="close" data-dismiss="alert">×</button>
              Item already added to your cart!

';
    }
  }
  header("location: ../shop");
  exit();

and that's the php. (dbh.inc.php is just a simple database connection)
I have tried double checking for typos/errors and I can't seem to find anything wrong.


text:
Q: help with stokes theorem problem Suppose $F=(5x−5y)\hat{i}+(x+2y)\hat{j}$. Using Stokes' Theorem
Find the circulation of $F$ around the circle $C$ of radius $7$ centered at the origin in the $yz$-plane, oriented clockwise as viewed from the positive $x$-axis.

A: Your curl is correct but your final result is not. Even though you seem to understand what you're doing I will give full detail for my own benefit and the benefit of future readers:
Let $F: \mathbb R^3 \to \mathbb R^3$ be given by $F(x,y,z) = (5x -5y) \textbf{i} + (x + 2y)\textbf{j}$.
$F$ is the flow velocity of your liquid. By definition, the circulation is given by
$$ \oint_C F \cdot dl$$
And by Stokes' theorem, if we let $C=\partial S$ be the boundary curve of some area $S$ then
$$ \oint_C F \cdot dl = \int \int \nabla \times F \cdot \textbf{n} dS$$
where $\textbf{n}$ is the normal to the surface we're integrating over. So in our case, $\textbf{n}=\textbf{i}$.
$\nabla \times F$ is given by
$$ \left( {\partial F_z \over \partial y}- {\partial F_y \over \partial z} \right) \textbf{i} + \left( {\partial F_x \over \partial z}- {\partial F_z \over \partial x} \right)\textbf{j } + \left( {\partial F_y \over \partial x}- {\partial F_x \over \partial y} \right)\textbf{k} = (0-0)\textbf{i} + (0-0)\textbf{j} + (1+5)\textbf{k} = 6 \textbf{k}$$
So that
$$ \oint_C F \cdot dl = \int \int \nabla \times F \cdot \textbf{n} dS = \int_0^7 \int_0^{2\pi} 6 \textbf{k} \cdot \textbf{i} dr d\phi = \int_0^7 \int_0^{2\pi}0 dr d\phi=0$$
To be sure let's see if we get the same result by direct calculation (without using Stokes):
$C = \gamma(t) = (0, 7\cos t, 7\sin t)$
$\gamma'(t) = (0, -7\sin t, 7 \cos t))$
$F(x,y,z) = (5x -5y, x + 2y, 0)$.
Then
$$ \oint_C F dl = \int_0^{2\pi} f(\gamma(t)) \cdot \gamma'(t) dt = -98 \int_0^{2\pi}  \sin t \cos t dt = 0$$


text:
Q: Time series filtering notation I am looking at some suggested filters for tidal data but am having trouble understanding the notation. For example, Godin (1972) suggests a low-pass filter  for tidal data that is a combination of 24-hour and 25-hour averages, using the notation
$$
\frac{A_{24}^2}{24^2}\frac{A_{25}}{25}
$$
My understanding of this filter is that it consists of a 25-hour average and two 24-averages (one leading, one lagging). However, I don't understand how the notation communicates this.
Another filter, referred to as the "even species filter", has the notation
$$
\frac{1}{16}A_{12}^2A_{13}^2
$$
Which I presume is using two 12-hour and 13-hour averages each, but I don't know the orientation.
Any help with understanding this notation would be appreciated.

Godin, G., 1972. The Analysis of Tides. University of Toronto Press, 264 pp.


text:
Q: MongoDB not showing the Data sent or created from the Model I have been working on  CRUD app with express and mongoDB using mongoose, for some reason all the data created on model schema is not being reflected on MongoDB. I am not sure what I am getting wrong but I am asking someone to help me with why the data created on model is not showing in the mongoDB as if I go postman and excute get method for http:/localhost:5001/jobs it gives me the output shown below. Also below are all my files to get your guidance.
sample data posted on POSTMAN using post router:
{
     "username": "test",
     "job_title": "DevOps",
     "job_comp_image": "https://pixabay.com/images/id-1869401/",
     "job_comp_name": "Training Academy",
     "job_description":"Web Developer",
     "job_location": "City",
     "job_field": "IT",
     "job_closing_date": "2021-11-07T04:11:08.924Z",
     "job_date_created" : "2021-11-07T04:11:08.924Z"
}

POSTMAN GET output after a sample job was posted:
        "_id": "618bb690fbef67502a29854b",
        "username": "test",
        "job_closing_date": "2021-11-10T12:09:52.427Z",
        "job_date_created": "2021-11-10T12:09:52.427Z",
        "createdAt": "2021-11-10T12:09:52.428Z",
        "updatedAt": "2021-11-10T12:09:52.428Z",
        "__v": 0

jobs.model.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const jobsiteSchema = new Schema ({

    username: String,
    job_title: String ,
    job_comp_image: String,
    job_comp_name: String,
    job_description: String,
    job_location:  String,
    job_field: String ,
    job_closing_date: { type: Date, default: Date.now},
    job_date_created: { type: Date, default: Date.now },
}, {
    timestamps: true,
});

const Job =  mongoose.model("Job", jobsiteSchema) ;

module.exports = Job;

jobs.js
const router = require('express').Router();
let Job = require('../models/jobs.model');

router.route('/').get((req, res) => {
  Job.find()
    .then(jobs => res.json(jobs))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/add').post((req, res) => {

  const username = req.body.username;
  const jobTitle = req.body.job_title;
  const JobCompImage = req.body.job_comp_image;
  const JobCompName = req.body.job_comp_name;
  const JobDescription = req.body.job_description;
  const JobLocation = req.body.job_location;
  const JobField = req.body.job_field;
  const JobClosingDate = req.body.job_closing_date ;
  const JobPostingDate = Date.parse(req.body.job_date_created) ;

  console.log(username)
  console.log(jobTitle)
  console.log(JobCompImage)
  console.log(JobCompName)
  console.log(JobDescription)
  console.log(JobLocation)
  console.log(JobField)
  console.log(JobClosingDate)
  console.log(JobPostingDate)

  // Create new Job using the fields above
  const newJob = new Job({
    username:username,
    jobTitle : jobTitle,
    JobCompImage : JobCompImage,
    JobCompName: JobCompName,
    JobDescription: JobDescription,
    JobLocation: JobLocation,
    JobField : JobField,
    JobClosingDate : JobClosingDate,
    JobPostingDate : JobPostingDate
  });

  //Save the new Job
  newJob.save()
    .then(() => res.json('Job added!'))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/:id').get((req, res) => {
  Job.findById(req.params.id)
    .then(job => res.json(job))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/:id').delete((req, res) => {
    Job.findByIdAndDelete(req.params.id)
    .then(() => res.json('Job deleted.'))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/update/:id').post((req, res) => {
    Job.findById(req.params.id)
    .then(job => {

     // username = req.body.username;
      job.jobTitle = req.body.job_title;
      job.JobCompImage = req.body.job_comp_image;
      job.JobCompName = req.body.job_comp_name
      job.JobDescription = req.body.job_description;
      job.JobLocation = req.body.job_location;
      job.JobField = req.body.job_field;
      job.JobClosingDate = req.body.job_closing_date ;

      job.save()
        .then(() => res.json('Job updated!!!'))
        .catch(err => res.status(400).json('Error: ' + err));
    })
    .catch(err => res.status(400).json('Error: ' + err));
});

module.exports = router;

server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const path = require("path");

require('dotenv').config();

const app = express();

const jobsRouter = require('./routes/jobs');
const usersRouter = require('./routes/users');

app.use(cors());
app.use(express.json());

// ... other app.use middleware
app.use(express.static(path.join(__dirname, "backend", "build")));

const uri = process.env.ATLAS_URI;
mongoose.connect(uri,
                  { useNewUrlParser: true,
                    //useCreateIndex: true,
                    useUnifiedTopology: true
                 }
);
const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})

app.use('/jobs', jobsRouter);
app.use('/users', usersRouter);

const port = process.env.PORT || 5001;

// Right before your app.listen(), add this:
app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "backend", "build", "index.html"));
});

app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
})

A: It's due to wrong variable names: Your schema has variable names defined in the underscore case and you are passing data in MongoDB in camelCase.
As username matches you get that value stored. All the timestamp have default values so you get those values too.
const jobsiteSchema = new Schema ({

    username: String,
    job_title: String ,
    job_comp_image: String,
    job_comp_name: String,
    job_description: String,
    job_location:  String,
    job_field: String ,
    job_closing_date: { type: Date, default: Date.now},
    job_date_created: { type: Date, default: Date.now },
}, {
    timestamps: true,
})

Change your routing hander to following:
router.route('/add').post((req, res) => {
    const newJob = new Job(req.body);

    //Save the new Job
    newJob.save()
        .then(() => res.json('Job added!'))
        .catch(err => res.status(400).json('Error: ' + err));
    });

It's ideal to add validation of the req body before storing it to DB.


text:
Q: selector for selecting only checked items in list in jquery I am using jquery multiselect plugin
I have some item disabled and some item checked in the list
I want to extract only text of checked item
my code is
var cval2 = $('#lsltrXYAxis option:checked').not(":disabled").map(function () {
            return this.value.replace('ltrXYAxis', '');
        }).get().join('@@');

HTML of disabled item is

<input id="ui-multiselect-lsltrXYAxis-option-0" type="checkbox" aria-disabled="true" disabled="disabled" title="" value="ltrXYAxisApple Identifier" name="multiselect_lsltrXYAxis">
Apple Identifier

and HTML of checked Item is

<input id="ui-multiselect-lsltrXYAxis-option-1" type="checkbox" aria-selected="true" checked="checked" title="" value="ltrXYAxisCustomer Price" name="multiselect_lsltrXYAxis">
Customer Price

But it also returns me disbaled item added with @@
Whats wrong with selector
Any Help will be highly appreciated
Thanks

A: You're mistakenly using option tag selector while in your HTML you have input.
Try this:
$('#lsltrXYAxis input:checked:not(:disabled)');

Also, if you need to associate some data with your elements, you better use the data attribute instead of extracting and replacing data from the value attribute.
Instead of:
<input value="ltrXYAxisCustomer Price" ... />

Try:
<input data-val="Price" ... />

And in your JavaScript:
return $(this).data('val');

A: Try some thing below
 var cval2 = $(':#lsltrXYAxis option:selected:not(:disabled)').map(function () {
                return this.value.replace('ltrXYAxis', '');
            }).get().join('@@');

A: You have to use the :checked selector.
The documentation of the :selected selector specifies, that "The :selected selector works for <option> elements. It does not work for checkboxes or radio inputs; use :checked for them."


text:
Q: How can i prove 2 sets in a Metric Space are separated if they are open or closed It actually says:
a) If $A\cup B=\emptyset$ and both are open (or both closed) then they are separated.
b)If $A$ and $B$ are separated then:
i) If $A\cup B$ is open $\Rightarrow A$ and $B$  are open.
ii) If $A\cup B$ is closed $\Rightarrow A$ and $B$  are closed.

A: Remember that two sets are separated if neither has a point in the other's closure. So for $(a)$ we have:

*

*Suppose $A\cap B=\emptyset$, $A, B$ are open. Assume they're not separated - WLOG, we have $x\in A\cap \overline{B}$. Since $A$ is open, there's some small $\epsilon$ such that $B_\epsilon(x)\subseteq A$ - but since $x\in \overline{B}$, what can you say about $B_\epsilon(x)\cap B$? Do you see why this means $A\cap B\not=\emptyset$?

*Suppose $A\cap B=\emptyset$, $A, B$ are closed. Again, assume $x\in A\cap \overline{B}$ for a contradiction. Do you see why this means $x\in A\cap B$?

For $(b)$, we'll use similar arguments. First suppose $A\cup B$ is closed and $A$ is not closed. Let $x\in \overline{A}\setminus A$. Since $A\cup B$ is closed, this means $x\in B$ - contradicting the assumption that $A$ and $B$ are separated. Similarly, if $A\cup B$ is open and $A$ is not open, we can find some $x\in A$ with an open ball $B_\epsilon(x)$ disjoint from $A\setminus\{x\}$. Do you see how to use the assumption that $A\cup B$ is open to get a contradiction, now?


text:
Q: illegal operation on empty resut set I get "Illegal operation on empty result set" whenever I execute this code for the first time when the database base is empty, but the values still get stored in the database. When I re-run the code, I get "Duplicate entry '1000' for key 1". What can I do to make the code run smoothly both when I run it when there are no values at the database and when I re-run consecutively?
ResultSet rs = stmt.executeQuery(id);
rs.next();
int custId =1000;
if(rs.wasNull()) {
    custId = 1000;
} else {
    custId =  rs.getInt(8)+1;
}
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, name);
ps.setString(2, fname);
ps.setString(6, phone);
ps.setString(4, email);
ps.setString(5, sex);
ps.setString(7, date);
ps.setString(3, address);
ps.setInt(8, custId);

A: Try this:
ResultSet rs = stmt.executeQuery(id);
boolean thisResultSetHasRecords;
if (rs.isBeforeFirst()) {
  thisResultSetHasRecords = true;
  while(rs.next()) {
    //do stuff with every record,
    //rs.next() returns false if empty or after last
  }
} else {
  thisResultSetHasRecords = false;
}

This one
rs.wasNull()

checks if a column of an existing row (->non empty ResultSet) had the SQL value NULL, not to be confused with Java null.
Also, you probably won't need to manually increment the id field; you can just make the field in the table AUTO_INCREMENT to avoid the second error -> See http://www.w3schools.com/sql/sql_autoincrement.asp


text:
Q: Endpoint that loads javascript file without javascript extension I am building a widget, the code snippet that loads the widget is created dynamically just like tawk.to works.
Example of the code snippet might look like this
(function(){
    var s1=document.createElement("script"),
        s0=document.getElementsByTagName("script")[0];

    s1.async=true;
    s1.src='https://embed.tawk.to/*8jjnjk*****1/****1gf****';
    s1.charset='UTF-8';
    s1.setAttribute('crossorigin','*');

    s0.parentNode.insertBefore(s1,s0);
})();

Now, if you look at the https://embed.tawk.to endpoint it loads just the js file.

How do I create something like that, an endpoint that loads another javascript file so that I can get user information from the first url before initializing the main Widget.
Any reference would be highly appreciated


text: Q: How do I find Sxx in a Simple linear regression model? In a Simple linear regression model, I have only Sxy and Syy data with me. How shall I derive Sxx, linking Sxy and Syy based on first principles? I know the formulas separately. I want to find Sxx, given only Sxy and Syy.


text:
Q: Uploading files gives ERR_CONNECTION_RESET When uploading files that are larger and take longer I get this response:
First time I try to upload a big file it seem to get: ERR_CONNECTION_ABORTED
after that it becomes ERR_CONNECTION_RESET
I checked all the upload limits etc all are 240seconds or higher and 256mb
I tried uploading 200mb file.
It always seems to happen at the same moment which is at 1 min.
There are no 60 second limits or anything in the phpinfo.
Also tried locally upping all the limits with no result.
Here is the main upload part. If additional info required I'll update the question A.S.A.P
Edit: Just came across this which is being used as well: SWFUpload
Getting error code 2038
Reinstalling flash doesn't work, neither do other browsers!

A: increase upload_max_filesize, max_input_time, and post_max_size an memory_limit in your php.ini. eventhought 200MB it is too big. if it is text/csv you might want to split the file in multiple files.


text:
Q: Batch XML/CONF modify Good afternoon guys, I'm having a lot of difficulties trying to modify two values inside an exe.conf file, the values are <add key="FileName" value="20220623.txt"/>, I need to modify the value of value.
The truth is that I am not very aware of the batch language, but if you give me a hand I will be very grateful.
I tried to do it with this line, and some variants but I couldn't modify it.
setlocal enableDelayedExpansion
set "newValue='20221008.txt'"
type "test.exe.conf"|findstr  /v "(<add key="row_process" value="$!newValue!"/>) >fileName.conf.new
move /y "fileName.conf.new" "fileName.conf"

A: In windows, you can use MSXML and JavaScript from cscript.exe
You'd run the following command
cscript xmlbatch.wsf file.xml "new value"

Here's a sample xmlbatch.wsf script, written in JavaScript.
<package>
<job id="t1">
<script language="JScript">

    var fso = new ActiveXObject( "Scripting.FileSystemObject" );
    var objArgs = WScript.Arguments;

    var strDOMObject = "MSXML2.FreeThreadedDOMDocument";
    var xml = new ActiveXObject( this.strDOMObject );

    if( objArgs.length < 2 ) {
        WScript.Echo( "Usage: cscript xmlbatch.wsf file.xml value");
        WScript.Echo( "Outputs the value(s) of all matching nodes" );
        WScript.Quit( 1 );
    }
    var strFileName = objArgs(0);
    var strValue = objArgs(1);

    var strXPath = "//add[@key='FileName']";

    if (fso.FileExists(strFileName) == false) {
        WScript.Echo( "Cannot locate " + strFileName );
        WScript.Quit( 1 );
    }

    try {
        if( !xml.load( strFileName ) ) {
            // output any errors, for invalid XML
            var strErrMsg = '';
            strErrMsg = xml.parseError.reason;
            if( xml.parseError.srcText != "" )
                strErrMsg += "Source: " + xml.parseError.srcText + "\r\n";
            if( xml.parseError.line != 0 )
                strErrMsg += "Line: " + xml.parseError.line + "\r\n";
            if( xml.parseError.linepos != 0 )
                strErrMsg += "Position: " + xml.parseError.linepos + "\r\n";
            throw new Error( xml.parseError.errorCode, strErrMsg );
        }

        var nodeList = xml.selectNodes( strXPath );
        if( nodeList != null ) {
            for( var i = 0; i < nodeList.length; i++ ) {
                nodeList[i].setAttribute( "value", strValue );
            }
            xml.save( strFileName );
        } else {
            WScript.Echo( "No matching nodes found in " + strFileName + " with XPath \"" + strXPath + "\"" );
            WScript.Quit( 1 );
        }

        WScript.Quit( 0 ); // success
    } catch( e) {
        WScript.Echo( e.description );
    }

</script>
</job>
</package>

You may need to install MSXML if your machine doesn't have it already.

A: It seems to me that this is an "XY" problem in SO parlance, that is the problem presented is a faulty solution to an unstated problem.
The fundamental problem appears to be: Starting with a template file test.exe.conf which contains a line <add key="FileName" value="20220623.txt"/>, produce a new file having substituted a new value for 20220623.
OP's code is designed to remove the <add key.. line, and there's nothing in that code to make a substitution.
Consequently, I'll present a solution aimed at curing the problem, not the code.
Since I'm making some assumptions about the problem, it may not be quite what is desired.
The first issue is what string to substitute for 22020623 - I'd conclude it's likely to change over time, so I've added a few line to enable that data to be supplied or entered instead of changing the batch file. This means that you could execute thisbatchname 20221008 to run the batch and produce a file with 20221008 substituted for 22020623, or execute thisbatchname and the batch will prompt for the string to substitute for 22020623. Be warned though that whatever string is entered in either case will be literally substituted.
The second issue is that I'm assuming that test.exe.conf is a template file, so it can be manipulated - hence, take the original test.exe.conf and modify it so that each <add key... line is replaced by a unique string. I chose substitute line here - but it could be almost any string - @#123 for instance.
@ECHO OFF
SETLOCAL
rem The following settings for the source directory, destination directory,
rem filename, and output filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "destdir=u:\your results"
SET "filename1=%sourcedir%\q73308290.txt"
SET "outfile=%destdir%\outfile.txt"

:: Get `newvalue`
SET "newvalue=%1"
IF NOT DEFINED newvalue SET /p "newvalue=New value ? "
IF NOT DEFINED newvalue GOTO :eof

(
FOR /f "usebackqdelims=" %%b IN ("%filename1%") DO (
 IF /i "%%b"=="substitute line here" (
  ECHO                     ^<add key="FileName" value="%newvalue%.txt"/^>
 ) ELSE ECHO %%b
)
)>"%outfile%"

GOTO :EOF

Always verify against a test directory before applying to real data.
Note that if the filename does not contain separators like spaces, then both usebackq and the quotes around %filename1% can be  omitted.
The filenames shown suit my system and allow me to isolate the unique data for a question.
The file is assigned line-by-line to %%b. If %%b is not the trigger line substitute line here then it's simply reproduced by the echo %%b, but if it is a trigger line, then the required substitute line is generated instead.
All output from the echos is gathered into a new file outfile.txt by means of surrounding the code causing the echoes with a pair of parentheses and >filename.
--- revision after comments
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the source directory, destination directory,
rem filename, and output filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "destdir=u:\your results"
SET "filename1=%sourcedir%\q73308290.txt"
SET "outfile=%destdir%\outfile.txt"

:: Get `newvalue`
SET "newvalue=%1"
IF NOT DEFINED newvalue SET /p "newvalue=New value ? "
IF NOT DEFINED newvalue GOTO :eof

FOR /f "tokens=5delims==/ " %%e IN ('FINDSTR /i /R /c:".*add key=\"FileName\" value=\"[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].txt\"/." "%filename1%"') DO SET "oldfn=%%~e"&GOTO process

:process
(
FOR /f "usebackqdelims=" %%b IN ("%filename1%") DO (
 ECHO "%%b"|FINDSTR /i /R /c:".*add key=\"FileName\" value=\"[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].txt\"/."  >nul
 IF ERRORLEVEL 1 (
  ECHO %%b
 ) ELSE (
  SET "line=%%b"
  echo !line:%oldfn%=%newvalue%.txt!
 )
)
)>"%outfile%"

:done
FC /w "%outfile%" "%filename1%"

GOTO :eof

Always verify against a test directory before applying to real data.
Note that if the filename does not contain separators like spaces, then both usebackq and the quotes around %filename1% can be  omitted.
This time, %%e acquires the ????????.txt string from the line in question and assigns it to oldfn.
The file is then processed, simply regurgitating lines that do not contain the required string, otherwise substituting the new value for the old filename, using DELAYEDEXPANSION
... although a solution using SED would probably be cleaner if 3rd party utilities are allowed.

A: Batch can't officially parse/edit XML, so it's highly recommended to use an XML-parser like xmlstarlet, or xidel instead.
xmlstarlet.exe ed -O -u "//add[@key='FileName']/@value" -v "20221008.txt" "fileName.conf"
<add key="FileName" value="20221008.txt"/>

xidel.exe -s "fileName.conf" -e "x:replace-nodes(//add[@key='FileName']/@value,function($x){attribute {name($x)} {'20221008.txt'}})" --output-node-format=xml
<add key="FileName" value="20221008.txt"/>


text:
Q: Percent Variance Explained - Factor Analysis I am doing factor analysis using the factanal() function in R, estimating 4 factors on 60 variables of data (~1500 total observations) using the varimax rotation (so not PCA). I want to compute the percent variance explained by each factor, for only a specific subgroup of variables in the data. I could then compare this to the total percent variance explained for a factor model estimated separately only for that subgroup of variables of interest. This would tell me if my 'full' factor model does a good job of explaining the variables in the subgroup relative to a factor model estimated only on that subgroup, or a 'partial' model.
Normally, I understand you would compute the Sum of Squared Loadings/N for the percent variance explained overall of each factor. I.E. Factor 1 explains x% of the data, Factor 2 explains y% etc. Does this method also work if I want to see how much of the variation, for example, Factor 1 explains for only variables 1 through 10? I'm computing the SSL/N only for those variables where N is 10. Is this is a valid procedure?
Threads such as this provide a good overview of using SSL/N for a rotated factor model, but in SPSS: https://stats.stackexchange.com/questions/205459/whats-the-relationship-between-initial-eigenvalues-and-sums-of-squared-loadings


text:
Q: Solve equation $X^r=Id$ in $\operatorname{SL}_n(\Bbb F_q)$ Let $q$ be an odd prime power. Solve equation $X^r=Id$ in $\operatorname{SL}_n(\Bbb F_q)$ where $r$  divides
$$|\operatorname{SL}_n (\Bbb F_q)| = \frac{1}{q-1} \prod_{i=0}^{n-1}(q^n-q^i)$$
A solution $X$ should be diagonalizable. Hence the eigenvalues of $X=PDP^{-1}$ should be all $r$-th roots of unity lying on the diagonal matrix D. I don't know how to proceed from here, How can we fully describe $P$ and therefore describe a solution $X$.
Edit
My statement above about the fact that solutions should be diagonalisable is false. I had also in mind a related question

*

*Is it possible to link the number of solutions to the number $r$?

Many thanks for your help.


text:
Q: Can't resolve server by fqdn when search domain is enabled I have a server named site.dpt.myorg.local, which i want to access both with short name and with fqdn.
When i try to use short site or site.dpt form, everything works just fine. However when i use fqdn - lookup works when using dig or nslookup, but fails when i use web browser, ssh and other tools.
I.e. ssh and ping fail with following error:
$ ssh -vvvv site.dpt.myorg.local
OpenSSH_7.2p2, OpenSSL 1.0.2j-fips  26 Sep 2016
debug1: Reading configuration data /home/user/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 25: Applying options for *
debug2: resolving "site.dpt.myorg.local" port 22
ssh: Could not resolve hostname site.dpt.myorg.local: Name or service not known

$ ping site.dpt.myorg.local
ping: unknown host site.dpt.myorg.local

I have a following resolv.conf file:
search myorg.local dpt.myorg.local
nameserver 10.0.0.1
nameserver 10.0.0.2

My OS is Opensuse 42.3
Can anyone point me to the cause of this problem? Thanks!

A: I found the answer to my question: https://superuser.com/questions/704785/avahi-ping-cant-resolve-hostname-but-nslookup-can
the problem was in avahi service, configured by default for .local domain. fixing part of /etc/avahi/avahi-daemon.conf as
[server]
domain-name=.alocal

solved my problem.
Edit: Ended by disabling avahi since i had no need in it in my environment.

A: The local TLD is reserved for use with mDNS and should not be used with regular DNS.
The proper solution would be to stop misusing local in this way.


text:
Q: jQuery, editing inline style tag I'm having a problem with some css+javascript. You see, I'm trying to make some sort of a wysiwyg webpage style editor in which there is an iframe which load a webpage containing code of something like this.

Other, quite a lot autogenerated stuff along with javascript that add some interactivity.

Now, I need to modify the content of #mystyle so that it reflect to the page in realtime. Using jquery, I tried to do so using several technique, like:

*

*$(#mystyle).html(newcss);

*$(#mystyle).replaceWith("")

*$(#mystyle).after("the newcss along with style tag"), then delete the old one.

*$(#mystyle).delete() //just to see what happen.

All of the above fail to change the look of the webpage. In fact, deleting the tag (4.), did not turn the page ugly and I did check using "Inspect Element", the html does change but the appearance do not. So.... what did I do wrong?

A: using html seems to work just fine. see:
http://jsfiddle.net/tGSkS/

A: if there are specific elements that you want to style on page load, you can do the following
$(function(){

  $('element-selector').css({
     style1:'value',
     style2:'value',
     style2:'value',
   });

});

or on the server, conditionally render or dynamically build your style sheet.


text:
Q: Sync Outlook 2016 Calendar to outlook.com Windows10 Office365 Outlook2016   /   outlook.com
emails sync; calendars do not; contacts sync but without categories.
It is possible to sync calendars without a third party app?
Thanks
Frank


text:
Q: adding a list of vectors to a data.frame in R How can I add a list of vectors to a preallocated data.frame such that the vectors form the rows of the data.frame?
eg.
ll<-list(c(1,2,3),c(2,3,4))
dd<-data.frame(matrix(nrow=10,ncol=3))

I need dd to look like
1 2 3
2 3 4

A: There's something odd about the question: You construct a dataframe with 10 rows, filled with NA values, but you need dd to have only 2 rows.
To answer your question first : sometimes the obvious isn't a bad solution.
ll<-list(c(1,2,3),c(2,3,4))
dd<-data.frame(matrix(nrow=5,ncol=3))

for(i in 1:length(ll)){
  dd[i,] <- ll[[i]]
}
dd

If you're staring at the ugly for-loop: this is a case where you could actually use a for-loop without problems. But this keeps dd having tons of NA values. If you want to get rid of them, you either initialize your dataframe as
dd<-data.frame(X1=numeric(0),X2=numeric(0),X3=numeric(0))

which gives you an empty dataframe, or you use complete.cases() to remove all NAs :
dd <- dd[complete.cases(dd),]

A: do.call(rbind, ll)

To add to an existing data frame
rbind(dd, do.call(rbind, ll)
# OR
do.call(rbind, c(ll, list(dd))

If you're doing this for many data frames, see rbind.fill in the plyr package for a much more efficient approach.


text:
Q: scrollIntoView onClick reactjs hello I have a few buttons and I want to scroll to them when clicked.
 const [active, setActive] = useState(0);

 useEffect(() => {
     // I´m not using useRef. is there other way to automatically scroll to the element and stop at 0 0 of the page?
 })

<button onClick={() setActive(1)}>button 1</button>
<button onClick={() setActive(2)}>button 2</button>
<button onClick={() setActive(3)}>button 3</button>

as you can see there´s a lot of scroll caused by those 2 divs. the idea is to scroll down and when you reach the buttons and click the one you need. the page scrolls to that button leaving it in the top of the page

image 1: scroll in random position
image 2: when you click on button 1
image 3: when you click on button 2
image 4: when you click on button 3

A: For scrolling react view to top there is a simple function.
use window.scrollTo(0, 0);
inside your code try this.
<button onClick={()=> window.scrollTo(0, 0) }>button 1</button>
edited:
I could come up with this solution after you edited your question.
import React, { useRef } from "react";

export default function App() {
  const button1Ref = useRef();
  const button2Ref = useRef();
  const button3Ref = useRef();

  const handleScroll = ref => {
    window.scrollTo({
      behavior: "smooth",
      top: ref.current.offsetTop
    });
  };

  return (

        <button ref={button1Ref} onClick={() => handleScroll(button1Ref)}>
          button 1
        </button>

        <button ref={button2Ref} onClick={() => handleScroll(button2Ref)}>
          button 2
        </button>

        <button ref={button3Ref} onClick={() => handleScroll(button3Ref)}>
          button 3
        </button>

  );
}

Please try it out. Let me know if this is what you asked for.
Edited after question asked in comment for using single component with Ref and using that component in multiple numbers:
If you want to use a single component for button then try this,
import React, { useRef } from "react";

export default function App() {
  return (

      <MyButton>button 1</MyButton>
      <MyButton>button 2</MyButton>
      <MyButton>button 3</MyButton>

  );
}

const MyButton = props => {
  const buttonRef = useRef();

  const handleScroll = () => {
    window.scrollTo({
      behavior: "smooth",
      top: buttonRef.current.offsetTop
    });
  };

  return (

      <button ref={buttonRef} onClick={handleScroll}>
        {props.children}
      </button>

  );
};

A: Here you want to use an event handler.
  const handleClick = (e) => {
   //  scrollIntoView logic and set state
  }

A:

//action
const goDown= (e) => {
    const anchor = document.querySelector('#some-id')
    anchor.scrollIntoView({ behavior: 'smooth', block: 'center' })
}

// click to scroll
<Link onClick={goDown}>Choose Health</Link>

//element you want to scroll to


text:
Q: How to resend double opt-in e-mail for newsletter subscriptions How does one resend the newsletter confirmation (double opt-in) emails to unconfirmed subscribers. Using mage 1.9.0
We recently had a problem resulting in about 400 people signing up for the newsletter without receiving a confirmation email.

A: I don't think resend Possible but if you use this wile register time customer got a conformation mail
GO to Your Backend
Magento Admin Area-> System-> Configuration-> Customers-> Newsletter. Expand the Subscription Options area and change the Need to Confirm field value to Yes.


text:
Q: How to exclude a specific subdomain from wildcard domain (Nginx) For example, I have a domain example.com, the web app will create subdomain when user sign up.

*

*foo.example.com will point to the same site

*bar.example.com will point to the same site

But I want to create a testing environment, e.g. demo.example.com which will point to another project. When user sign up, it will have

*

*foo.demo.example.com

*bar.demo.example.com
Currently what I have
| Name           | Type  | Value           |
|----------------|-------|-----------------|
| example.com.   | A     | 123.123.123.123 |
| *.example.com. | CNAME | example.com.    |

And my nginx config
server {
    listen 80;

    root /var/www/example.com/public;
    index index.html index.htm index.php;
    server_name example.com *.example.com;

    location / {
       try_files $uri $uri/ /index.php?$query_string;
    }
    location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

How can I create 1 for testing environment?

A: You will need to create a new server block with subdomain fqdn as server_name and nginx will follow this order of precedence.

*

*Exact name

*Longest wildcard name starting with an asterisk, e.g. "*.example.org"

*Longest wildcard name ending with an asterisk, e.g. "mail.*"

*First matching regular expression (in order of appearance in a configuration file)

For more info.: http://nginx.org/en/docs/http/server_names.html


text:
Q: Generators for regular graphs {p,q} on Poincaré disk We consider a particular class of tessellations $\{p,q\}$ on a Poincaré disk. There are few examples where a regular graph for a particular tessellation has been obtained. It is done by identifying the vertices at the boundaries and then connecting them to generate a regular graph, which, in general, can be a non-trivial problem. For instance, for {3,7} tessellation, Klein obtained the 7-regular graph with 24 vertices and 84 edges  as shown below-

The compact Riemann surface of the above regular graph is a genus 3 surface. That just means the above regular graph can be embedded on a genus 3 surface. However, I am not interested in any kind of embedding.
Just to illustrate my point further. The next candidate for regular graph (or map) in {3,7} has a compact Riemann surface or Hurwitz surface with genus 7, also known as Macbeath surface. This can easily be shown for the dual graph of {3,7}, i.e., {7,3}. However, this can be extended to higher genus $g = 14, 17, 118,..$. Maybe the reason is that at these $g$, a regular map $M$ can be obtained because the automorphism group $A(M)$ contains two particular automorphisms: (1) Let us say $f$, which cyclic permutes the edges that are successive sides of one face of $M$; this is like a rotation. And (2), let us say $e$, which cyclically permutes the successive edges meeting at one vertex of this face; this is like a reflection of the face about that edge. These are the automorphism referred to as $\bf{R}$ and $\bf{S}$ in Coxeter's notation (from Generators and Relations for Discrete Groups). Lastly, as a verification, if we have a regular map, we correspondingly have a Petrie polygon of that map.
$\textbf{Question}$:
Is there a way to generate a regular map (or graph) for any tessellation $\{p,q\}$ on a Poincaré disk, even if for a particular genus?
If yes, is there an algorithm in the sense that there exist generators that can produce the whole regular map on applying to some set of vertices respecting the right edges for $\{p,q\}$  for a genus $g$?
EDIT:
My question is different from this question on the existence of regular tessellation on a closed surface $S$, which concerns mostly about the existence of such regular tessellation embedding on $S$. However, I am concerned about how can such regular tessellation be obtained?


text:
Q: EditText drawable left will not be changed I have an EditText box that I want to change the background color and drawable left of when the character count is greater than or equal to 4. As seen in my code snippet below I used a TextWatcher to capture typing  events and at the moment the background color changes, but the setCompoundDrawable does not change the drawable on the EditText box.
Am I doing something wrong, or is it a glitch of some sort?
final EditText input = (EditText)view.findViewById( R.id.editText );
    input.addTextChangedListener( new TextWatcher() {
        @Override
        public void beforeTextChanged( CharSequence charSequence, int i, int i2, int i3 ) {   }

        @Override
        public void onTextChanged( CharSequence charSequence, int start, int count, int after ) {  }

        @Override
        public void afterTextChanged( Editable editable ) {
                if(editable.length() <= 3 ){
                    input.setBackgroundColor( getResources().getColor( R.color.edittext_background_red) );
                    input.setCompoundDrawables( getResources().getDrawable( R.drawable.ic_cross ), null, null, null );
                }else if(editable.length() >= 4 ){
                    input.setBackgroundColor( getResources().getColor( R.color.edittext_background_green ));
                    input.setCompoundDrawables( getResources().getDrawable( R.drawable.ic_tick ), null, null, null );
                }
        }
    } );

A: use setCompoundDrawablesWithIntrinsicBounds(...) or call setBounds on your left Drawable before calling setCompoundDrawables


text:
Q: Second order correction to $ {\epsilon} +{\epsilon^{1/2}}+{\epsilon^{1/3}}+\dots+{\epsilon^{1/(-b\ln \epsilon)}}$? Background
I recently asked myself the following where $\epsilon > 0$ and $b > 0$
$$ {\epsilon} +{\epsilon^{1/2}}+{\epsilon^{1/3}}+\dots+{\epsilon^{1/(-b\ln \epsilon)}} = ?$$
After some fiddling around I was able to show:
$$ {\epsilon} +{\epsilon^{1/2}}+{\epsilon^{1/3}}+\dots+{\epsilon^{1/(-b\ln \epsilon)}} \sim - \ln(\epsilon) \times \int_0^{b} e^{-1/|x|} dx$$
Question
Is my fiddling correct? I suspect there is an $(\ln \epsilon)^2$ term as well but I cannot find it. Any help?
My Fiddling
Consider:
$$ f(x) = e^{-1/x} $$
Now,
$$ \int_0^b f(x) dx = \lim_{\delta \to 0} \sum_{n=1}^{N} f(n \delta) \delta $$
with $N = \frac{b}{\delta}$ and $\delta> 0$. Let us replace $\delta =\frac{-1}{\ln(\epsilon)}$
$$ \int_0^b f(x) dx = \lim_{\epsilon \to 0} \sum_{n=1}^{N} f\left(\frac{-1}{\ln ( \epsilon^{1/n})} \right) \frac{-1}{\ln \epsilon} $$
with $N=-b \ln(\epsilon)$. Substituting $f(x)$:
$$\int_0^b  e^{-1/x} = \lim_{\epsilon \to 0} \sum_{n=1}^{N} \epsilon^{1/n} \frac{1}{\ln \epsilon} $$
Using asymptotics:
$$ - \ln \epsilon  \int_0^b  e^{-1/x} \sim  {\epsilon} +{\epsilon^{1/2}}+{\epsilon^{1/3}}+\dots+{\epsilon^{1/N}} $$

A: Your approximation is (now) fine. The next-order correction should take into account the continuity correction in the integral.
Notice first that, using the trapezoid rule, the last term in the sum should be divided by two. (The first term does not matter, because the function starts at zero).
But notice also that, assuming $\epsilon, b$ are given, $-b \ln \epsilon$ is not an integer in general. Then, the last index of the sum is actually given by a rounding to the nearest integer  $ N = \lfloor N' \rceil = \lfloor  -b \ln \epsilon\rceil$.
Let $d = N - N'$, with $-\frac12 \le d \le \frac12$.
Then the integral is better approximated by
$$ \int_0^b  e^{-1/x} dx \approx \frac{-1}{\ln \epsilon} \left( \epsilon + \epsilon^{1/2} + \epsilon^{1/N}\right)- \frac{-1}{\ln \epsilon} \epsilon^{1/N}(d+1/2) \tag2$$
Or
$$\left( \epsilon + \epsilon^{1/2} + \epsilon^{1/N}\right) \approx -\ln \epsilon \int_0^b  e^{-1/x} dx - \epsilon^{1/N}(d+1/2) \tag 2$$
The graph compares the approximation in $(2)$ for $b=5$ (yellow line the zero order approximation; the red line, the corrected one, is indistinguishable from the exact integral value: $2.87100322120604$). The abscisa corresponds to $1/\epsilon$; in that range of values we get $N=37,38,39$.


text:
Q: Android notification swipe delete disabling Is it possible to disable the swipe delete feature of an android notification from the notifications list in android. Please help me.
Thanks in advance.

A: notificationBuilder.setOngoing(true);

not allow to cancel notification by swipe.

A: Try this code
builder.setOngoing(true); // Cant cancel your notification (except notificationManager.cancel(); )

Above code in Notifcation Builder.
public void DisplayNotification() {

// Use NotificationCompat.Builder to set up our notification.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

//icon appears in device notification bar and right hand corner of notification
builder.setSmallIcon(R.drawable.ic_stat_notification);

// This intent is fired when notification is clicked
Intent tapIntent = new Intent(CurrentActivity.this, SecondActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, tapIntent, 0);

// Set the intent that will fire when the user taps the notification.
builder.setContentIntent(pendingIntent);

builder.setOngoing(true); // Cant cancel your notification (except NotificationManger.cancel(); )

// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Notifications Title");

// Content text, which appears in smaller text below the title
builder.setContentText("Your notification content here.");

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

// Will display the notification in the notification bar
notificationManager.notify(NOTIFICATION_ID, builder.build());
}

Cancel Notification
public void cancelNotification() {
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(NOTIFICATION_ID); // Notification ID to cancel
    }

Happy Coding :)

A: you can mark your Notification as an 'ongoing' notification.
--> Notification.Builder setOngoing


text:
Q: How to create more edittext fields in android? I am working on android project. I need to create some fields like the following image.
Here I am showing only 4 columns but I have 8 to 10 columns.
In one way I can generate edit texts dynamically.
How can I create these fields in android screen?

A: You can make ListView with 4 EditTexts as row of your table. Count of rows would be generated automatically by ListView.

A: Hi you may use the TableLayout,TextView and EditText as below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TableLayout android:layout_width="match_parent"
    android:layout_height="match_parent"

   >
        <TableRow android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1">
            <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"/>
            <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
     android:text="Location"
      android:layout_weight="1"/>
            <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
     android:text="Name"
      android:layout_weight="1"/>
            <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
     android:text="Age"
      android:layout_weight="1"/>
            <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Gender"
     android:layout_weight="1"/>
        </TableRow>
         <TableRow android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1" >
             <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="1"
    android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

     android:layout_weight="1"/>
         </TableRow>
           <TableRow android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >
             <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="2"
    android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

     android:layout_weight="1"/>
         </TableRow>
          <TableRow android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >
             <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="3"
    android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

     android:layout_weight="1"/>
         </TableRow>
          <TableRow android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >
             <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="4"
    android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

     android:layout_weight="1"/>
         </TableRow>
          <TableRow android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >
             <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="5"
    android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

      android:layout_weight="1"/>
            <EditText android:layout_width="match_parent"
    android:layout_height="match_parent"

     android:layout_weight="1"/>
         </TableRow>
    </TableLayout>

</LinearLayout>


text:
Q: Распарсить json в python import requests
import json

# Получаем HTML-код страницы
url = 'https://www.geooptic.ru/product/lasernyi-skanner-trimble-x7-kit-with-t10x'
response = requests.get(url).text
#html = response.content

# Ищем строку с информацией о файлах
start = 'files:['
end = '],'
start_index = response.index(start) + len(start)
end_index = response.index(end, start_index)
files_str = response[start_index:end_index]
print(files_str)

out:
{file_name:"obzor-skanerov-trimble.pdf",name:"Сравнение сканеров TRIMBLE X7, TX6, TX8 и тахеометра SX10 (2019 год)",type_id:eW},{file_name:"Trimble T10x tablet_Datasheet.pdf",name:"Trimble T10x tablet_Datasheet",type_id:4},{file_name:"Сравнение приборов Trimble 2022 X7 X12 SX12.pdf",name:"Сравнение приборов Trimble 2022 X7 X12 SX12",type_id:eW}

я хочу его распарсить:
# Извлекаем информацию о файлах
files_info = json.loads('[' + files_str + ']')

# Выводим результат
for file_info in files_info:
    print(f"{file_info['name']} : {file_info['file_name']}")'''

у меня выходить ошибка:
Возникло исключение: JSONDecodeError
Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
  File "/home/artddss/python/em/de.py", line 18, in <module>
    files_info = json.loads('[' + files_str + ']')
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)

A: Ошибка возникает потому, что строка files_str не является валидным JSON-объектом. В JSON-формате строки должны быть заключены в двойные кавычки, а не в одинарные.
Первый вариант решения:
Замените строку files_info = json.loads('[' + files_str + ']') на files_info = json.loads('[' + files_str.replace("'", '"') + ']').
Второй вариант решения:
Делаем следующую конструкцию
files_str = files_str.replace("'", '"')
files_info = json.loads('[' + files_str + ']')

A: Ошибка говорит о том, что параметры словаря должна быть заключены в двойные кавычки - в вашем случаи таково нет. Для таково типа данных придется писать свой парсер.


text:
Q: How to add Broadcast in Android? I want android to notify me of an app launch by sending a broadcast whenever there is a launch. Where to put the broadcast? I don't want to poll continuously and look for changes in the list of running apps.

A: Sending a Broadcast is as easy as few lines of code. Just pass an Intent object with with sendBroadcast() method:
Intent intent = new Intent();
intent.setAction("com.example.Broadcast");
intent.putExtra("MyData", 1000);
sendBroadcast(intent);


text:
Q: [Docker][PHP] NumberFormatter::formatCurrency incompatible between 7.4.29 and 7.4.28 (Same as https://github.com/docker-library/php/issues/1301 )
The results of running the following script were different between php:7.4.29-fpm-alpine and php:7.4.28-fpm-alpine.
<?php

$fmt = new \NumberFormatter('JA_JP', \NumberFormatter::CURRENCY);
$formatString = $fmt->formatCurrency(0, 'JPY');

var_dump($formatString);

Result

*

*php:7.4.28-fpm-alpine (I expects)
string(4) "¥0"

*php:7.4.29-fpm-alpine
string(3) "¥0"

(My) problem
Is there any way to get the results in php:7.4.29-fpm-alpine to be what they were in php:7.4.28-fpm-alpine ? (Is there a workaround?)
Way to reproduce
see https://github.com/sogaoh/reproduce-incompatibility-of-format-currency (README.md)
Remarks
( unconfirmed ) I'm guessing that there is a similar problem between

*

*8.0.19 and 8.0.18

*8.1.6 and 8.1.5

A: The difference between the two is that the .28 version uses \uffe5 'Fullwidth Yen Sign, and the .29 version uses \u00a5 'Yen Sign.
As noted in the github issue comment, it's likely a change in the underlying ICU library between builds of the image, as opposed to an issue in the image, Alpine, or PHP themselves. As an interim fix you could use a modified image that installs a pinned version of ICU, but YMMV.
Alternatively you could shim in a simple replacement like:
str_replace("\xc2\xa5", "\xef\xbf\xa5", $formatter_output);

Though the issue itself is fairly cosmetic, and IMO the original use of a fullwidth glyph for the currency symbol was the more questionable option.

A: My solution:
Install package: icu-data-full additionally.
refs

*

*https://github.com/sogaoh/reproduce-incompatibility-of-format-currency/pull/2/files

*https://github.com/docker-library/php/issues/1301#issuecomment-1139142261


text:
Q: How to Close modal window and refresh parent window in salesforce? My Requirement is when we click on edit button open child visualforce page as modal window when we save that record close that modal window and refrsh parent page.

A: function closeAndRefresh(){
  opener.location.reload(); // or opener.location.href = opener.location.href;
  window.close(); // or self.close();
}

This will work for you.


text:
Q: Having problems with dropped hard disk I was playing Xbox and my 3TB Seagate external hard drive fell and hit the floor. I plugged it back into the Xbox and now it wont detect my games from the hard drive. is there a way to fix this. The hard drive turns on and acts normal but it wont move my games over.

A: Please be aware, that an HDD (Hard drive disk) consists of mechanical parts moving to write & read the data on the disks. If you drop an HDD it can happen that you won't have any real option other to get it to a data recovery service which can cost up to many hundreds or thousands of dollars/euros to get the undamaged data.
The question is if it's cheaper in your case to buy a new HDD and the games which you don't have any longer available (I'm not the console type of player)


text:
Q: Why does my picture with curved borders go square on mobile devices? It works in most situations. My needs should look like this:

I have a section where I want to show a few needs in one row and scroll horizontally. When I try to set display: flex on the parent div (or white-space: nowrap and display: inline-block so I can use overflow-x: scroll, etc...) I get something more like this:

Here's some simplified test HTML:

Needs

And I got CSS for 'ya
#needs {
    background-color: #CDDC39;
    color: #757575;
    /*padding: 35px 20px;*/
    height: 700px;
}
#needs-wrapper{
    overflow-x: scroll;
    overflow-y: hidden;
    display: flex;
    /*overflow: auto;*/
    /*white-space: nowrap;*/
}
.test-need{
    /*display: inline-block;*/
    text-align: center;
    margin-right: 30px;
}
img {
    width: 100%;
}
#cover-image{
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
}
.imgwrapper {
    width: 100%;
    height: 200px;
    overflow: hidden !important;
    background: #c1c1c1;
    border-radius: 30px 30px 0 0 !important;
    margin-top: 10px;
}
.needSecTest {
    width: 286px;
    margin: auto;
    margin-top: 20px;
    margin-bottom: 5px;
}

The problem only happens on mobile. When I figured this at first I thought it was a problem with Chrome Dev. Tools (god knows there's enough of them) but then I deployed to a test server and opened on my phone and sure enough, square images... so actually kudos to Google for showing the bug in dev. tools!
At the request of commentators I created a jsfiddle BUT it does not reproduce the problem, even if you use Chrome Dev. Tools to simulate mobile. It only happens in a native browser (tested with Chrome) on or simulating mobile. In any case, here's the jsfiddle: https://jsfiddle.net/Methodician/fLvjum5b/
And why not. Here's the test site on a server (will be updated or removed as time passes): https://aid2assist-dev.firebaseapp.com/home
Scroll down to the green needs section and go to mobile on dev tools (or open on your phone) and the bug appears...
Thanks for your help!!!