text:
Q: The bigger the domain, the smaller the first eigenvalue - $\lambda(M_2) \leq \lambda(M_1)$ on the Laplacian I know it is probably a silly question, but is there anyone could help me to complete of the corollary $3.1$ of that document? I pass a lot of time to try understanding the problem, but I can't advance on the subject.

Corollary $3.1$. If $M_1 \subset M_2$, then $$\lambda(M_2) \leq
 \lambda(M_1),$$ i.e. the bigger the domain, the smaller the first
  eigenvalue.
Proof.  $$\lambda_1(M_1)=\min \{E(u), u \in C^{\infty}(M_1) \}$$
But then, $u \in C^{\infty}(M_1)$, $u=0$ on $M_2$, and
  $$\lambda_1(M_2)=\min \{E(u), u \in C^{\infty}(M_2) \}$$

A: I think it's a bit confusing what they wrote, bordering on incorrect. I'm sure you can find a better reference for these things.
The idea is to use the theorem that $ \lambda_1(M) \leq E(u) / \langle u,  u \rangle = \| \nabla u \|^2 / \| u \|^2 $ for any sufficiently nice $ u $ (it does not have to be $ C^\infty $).
Let $ \varphi_1 \in C^\infty(M_1) $ be the eigenvector corresponding  to $ \lambda_1(M_1) $. By extending by $ 0 $, $\varphi_1 $ defines a piecewise differentiable function $ \widetilde \varphi_1 $ on $ M_2 $. It is not $ C^\infty $.  Now use the theorem:
$$
\lambda_1(M_2) \leq \| \nabla \widetilde \varphi_1 \|^2_{M_2} / \| \widetilde \varphi_1 \|^2_{M_2} = \| \nabla \varphi_1 \|^2_{M_1} / \|  \varphi_1 \|^2_{M_1}= \lambda_1(M_1)
$$
I put subscripts on the norms $ \| \cdot \|_{M_i} $ to indicate in which space it is taken.
The equality $ \| \nabla \widetilde \varphi_1 \|^2_{M_2} / \| \widetilde \varphi_1 \|^2_{M_2} = \| \nabla \varphi_1 \|^2_{M_1} / \|  \varphi_1 \|^2_{M_1} $ is because $ \widetilde \varphi_1 $ has support in $ M_1 $ and will be obvious if you write out each side in terms of integrals.
EDIT: Fixed a bunch of typos.


text:
Q: Server/client program doesn't work when I add a function in C I'm making a program that copies a file from client to server. I have to send the length of the file to the server before copying. Both of the programs work fine, until I add int sizeFile = getSizeFile(originalFile); in the client part of my program. All of a sudden (after I add the function) the  while() loop in my server gets stuck on recv(). And the while() in my client just loops once and then breaks.
Why does my program work fine until I add the getSizeFile() function and how can I solve it?
function:
int getSizeFile(FILE* file)
{
    // get file size
    FILE *f = file;
    fseek(f, 0L, SEEK_END);
    int sizeFile = ftell(f);
    return sizeFile;
}

server:
char ch[70];
printf("where do you want to save it(full path + name): ");
scanf_s("%s", ch, 70);

char c[70];
printf("which file you want to copy(full path + name): ");
scanf_s("%s", c, 70);

r = send(s, c, 70, 0); // B
if (r == SOCKET_ERROR)
{
    printf("2 error: %d\n", WSAGetLastError);
}

FILE* copyFile;
fopen_s(&copyFile, ch, "wb");
if (copyFile == NULL)
{
    printf("Error opening file\n");
}

char buf[BUFSIZE];
size_t size = BUFSIZE;
int counter = 0;

while (1)
    {
        int res = recv(s, buf, BUFSIZE, 0);
        if (res == SOCKET_ERROR)
    {
        printf("3 error %d\n", WSAGetLastError);
        break;
    }
    size = fwrite(buf, 1, res, copyFile);
    printf("size: %d\n", size);
    printf("res: %d\n", res);
    counter++;
    printf("counter: %d\n", counter);
}
fclose(copyFile);

client:
    char c[70];
    res = recv(ClientSocket, c, 70, 0); // B
    if (res == SOCKET_ERROR)
    {
        printf("Server disconeccted\n");
        break;
    }

    FILE* originalFile;
    fopen_s(&originalFile, c, "rb");
    if (originalFile == NULL)
    {
        printf("Error opening file\n");
    }

    char buf[BUFSIZE];
    size_t size = BUFSIZE;
    int counter = 0;

    int sizeFile = getSizeFile(originalFile); // <-- this one

    while (size == BUFSIZE)
    {
    size = fread(buf, 1, BUFSIZE, originalFile);
    int r = send(ClientSocket, buf, size, 0);
    if (r == SOCKET_ERROR)
    {
        printf("1 error: %d\n", WSAGetLastError);
        break;
    }
    printf("size: %d\n", size);
    printf("r: %d\n", r);
    counter++;
    printf("counter: %d\n", counter);
}
fclose(originalFile);

A: Would make this a comment since it just riffs off what Alex F said, but not enough reputation. In any case, if you add rewind(f); after int sizeFile = ftell(f); in getSizeFile(FILE* file), that should solve the issue of not being able to read the file properly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: No such file or directory: couldn't create child process: /opt/suphp/sbin/suphp This don't seems like a php memory_limit error to me, I have set CloudLinux configuration to unlimited for this website in CloudLinux LVE Manager. Any suggestion what might be causing the website 500 internal server error.
[Sat Sep 19 09:24:46.857537 2015] [:error] [pid 68390] (2)No such file or directory: [client 73.173.61.86:51181] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php
[Sat Sep 19 09:25:33.430357 2015] [:error] [pid 67875] (2)No such file or directory: [client 73.173.61.86:51191] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php
[Sat Sep 19 09:26:15.970405 2015] [:error] [pid 67877] (2)No such file or directory: [client 73.173.61.86:51217] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php
[Sat Sep 19 09:26:17.710636 2015] [:error] [pid 68390] (2)No such file or directory: [client 73.173.61.86:51218] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php
[Sat Sep 19 09:26:45.729530 2015] [:error] [pid 67873] (2)No such file or directory: [client 73.173.61.86:51223] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php
[Sat Sep 19 09:26:47.654225 2015] [:error] [pid 67874] (2)No such file or directory: [client 73.173.61.86:51224] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php
[Sat Sep 19 09:32:54.666577 2015] [:error] [pid 68390] (2)No such file or directory: [client 104.236.82.54:47798] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php
[Sat Sep 19 09:34:06.616071 2015] [:error] [pid 67874] (2)No such file or directory: [client 73.173.61.86:51328] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php
[Sat Sep 19 09:34:08.672377 2015] [:error] [pid 67875] (2)No such file or directory: [client 73.173.61.86:51329] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php
[Sat Sep 19 09:37:15.997949 2015] [:error] [pid 67875] (2)No such file or directory: [client 208.80.194.27:25675] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php
[Sat Sep 19 09:43:16.645956 2015] [:error] [pid 67876] (2)No such file or directory: [client 94.23.134.250:46019] couldn't create child process: /opt/suphp/sbin/suphp for /home/mywebsite/public_html/index.php

A: I recently found the sticky bit on the /opt/suphp/sbin/suphp file to be unset.
Adding chmod +t /opt/suphp/sbin/suphp will set the sticky bit back.
Alternatively chmod 5755 /opt/suphp/sbin/suphp will set both the sticky bit and the UID bit.


text:
Q: Cloud FireStore: Retrieve 1 document with query I'm trying to retrieve a single document from a collection. I'm now using the code below that returns a collections of items, but I know that there is only one item. So it ain't that clean.
Setup:
private db: AngularFirestore
private itemSubs: Subscription[] = [];
itemAd= new Subject<Item>();

fetchItemFromDatabase(itemId: string) {
    this.itemSubs.push(
      this.db.collection('items', id => id.where('itemId', '==', itemId)).valueChanges().subscribe((items: Item[]) => {
        this.itemAd.next(items);
      }));
  }

I tried to do it with this.db.collection('items').doc(itemId).get() , but I'm getting an error on get() that it's not found/supported. I also didn't got autocompletion when trying to call this methode (methode found in the official cloud firestore documents).
I looked at around at some other solutions and then tried it with this.db.collection('items').doc(itemId).ref.get().then(...) , but here I got an empty doc back.
So I'm a bit stuck at the moment and I don't want to use that whole collections logic when I know there is only 1 item in it.

A: There may be multiple documents with itemId equal to a given value. While you may know that there is only one in your app, the database and API cannot know nor enforce that. For that reason the query you run will always return a query snapshot that potentially contains multiple documents.
this.db.collection('items', id => id.where('itemId', '==', itemId))

If you want to enforce that there is only one document with the given item ID, consider using that item ID as the document name instead of storing it as a field in the document.
There can be only one document with a given name, so that means the ID is guaranteed to be unique. And you can then retrieve that document with:
this.db.collection('items').doc(itemId)


text:
Q: Splitting a string in to multiple value BufferedReader br = new BufferedReader(new FileReader(file));
        String delimiter = "\\s\\d\\.\\s";
        String cl;

        while ((cl = br.readLine()) != null) {
            String split[] = cl.split(" ", 2);
            String name = split[0];
            //System.out.println( name);
            String description = split[1];

            String s[] = description.split(delimiter);

        }

        br.close();

trying to read in something like this in and split by the delimiter above
(
.WKS 1. Lotus Worksheet (filename extension). 2. Microsoft Works document (filename extension)). )
However, I get back an empty space and it doesn't put anything in Arr[1] just array[0].
My end goal is to store them with .WKS as key and store the rest of them into a hash table under that key with chaining.

A: By making a change to "\\d\\.\\s" to the delimiter, this code:
String delimiter = "\\d\\.\\s";
String cl =  ".WKS 1. Lotus Worksheet (filename extension). 2. Microsoft Works document (filename extension).";
String split[] = cl.split(" ", 2);

String name = split[0];

String description = split[1];

String splitted[] = description.split(delimiter);

System.out.println("name=" + name);
System.out.println("description" + description);

for (String s : splitted) {
    System.out.println(s);
}

prints
name=.WKS
description=1. Lotus Worksheet (filename extension). 2. Microsoft Works document (filename extension)).

Lotus Worksheet (filename extension).
Microsoft Works document (filename extension).

Notice the empty line, this means that splitted[0] is empty.
Is this what you want?


text:
Q: entity framework 5 transaction doesn't commit I don't understand what is wrong with this transction
In case of error the rollback is ok
but the commit never happens
as the transaction was already interrupted...
What is wrong here?
Thanks!
  try
           {

               using (TransactionScope scope = new TransactionScope())
               {

                   //insert dati swap nella tabella PAPER_OPERATION
                   context.PAPER_OPERATION.Add(op_paper);

                   context.SaveChanges();
                   //si richiama la sp incaricata di effettuare un post processing sui dati dello swap
                   context.SP_PAPER_OPERATION_RUN(op_paper.ID_OPERAZIONE);

                   //per quanto riguarda la prezzatura la prima volta in cui lo swap viene inserito si tratta di un inserimento ex novo di righe nella tabella PRICING_PERIOD
                   //e a seguire nella tabella R_PAPER_OPERATION_PRICING_PERIOD
                   foreach (var pp_buy_to_insert in list_pp_buy)
                   {
                       context.PRICING_PERIOD.Add(pp_buy_to_insert);
                       context.SaveChanges();
                       R_PAPER_OPERATION_PRICING_PERIOD r_oppaper_pp_buy = new R_PAPER_OPERATION_PRICING_PERIOD();
                       r_oppaper_pp_buy.ID_PRICING_PERIOD = pp_buy_to_insert.ID_PRICING_PERIOD;
                       r_oppaper_pp_buy.ID_PREZZATURA_PAPER = Convert.ToString(op_paper.ID_OPERAZIONE) + 'B';
                       context.R_PAPER_OPERATION_PRICING_PERIOD.Add(r_oppaper_pp_buy);
                       context.SaveChanges();
                   }
               id_inserted = op_paper.ID_OPERAZIONE;

                scope.Complete();
               }

                var parameter = new
                {
                    INSERTED_ID = id_inserted
                };

                return Json(parameter, JsonRequestBehavior.AllowGet);

            }
            catch (Exception e)
            {
                                }


text:
Q: SQL Server transaction, where is uncommitted data held? My question relates to how are transactions dealt with in SQL Server.
Lets say I have a user defined transaction that contains a lot of data, where does that data get stored during that process? Its only committed to the database file if the transaction is successful but where does it reside beforehand.

*

*Does that stay in memory of the program creating the transaction

*to the SQL server memory process

*is it written to the transaction log of the database?

*temporary files or some other disk location?

A: Uncommitted data is written into the table(s) in question, it is simply not marked as committed until the transaction commits.  If the transaction is rolled back the data will be overwritten the next time a write occurs that needs the affected page.  Once the transaction commits, the data is in the table is committed and cannot be overwritten.  The log contains an ongoing record of what is happening in the database so that transactions can be rolled backwards or forwards after a system crash, or if a transaction is rolled back.

A: SQL Server uses ARIES write-ahead logging. Details are described in How It Works: Bob Dorr's SQL Server I/O Presentation. Write-ahead logging requires every change made tot he data to eb described by a log record so that crash recovery can reconstruct the database. To rollback a transaction all that one has to do is to walk the log backward and generate a compensating action for every record generated by the transaction. This will in effect undo everything done by the transaction. Two phase locking will ensure that the compensating operation is always free to proceed.
See also Inside the SQL Server Transaction Log and, of course, ARIES: A Transaction Recovery Method Supporting Fine-Granularity Locking and Partial Rollbacks Using Write-Ahead Logging.


text:
Q: Can't install python selenium on Ubuntu 14.10/15.04(pre-release) I'm trying to install selenium library for python on my Ubuntu machine using pip installer.
I receive the following error:

pip install selenium
Exception: Traceback (most recent call last):   File
  "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in
  main
      status = self.run(options, args)   File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 304,
  in run
      requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)   File
  "/usr/lib/python2.7/dist-packages/pip/req.py", line 1230, in
  prepare_files
      req_to_install.run_egg_info()   File "/usr/lib/python2.7/dist-packages/pip/req.py", line 293, in
  run_egg_info
      logger.notify('Running setup.py (path:%s) egg_info for package %s' % (self.setup_py, self.name))   File
  "/usr/lib/python2.7/dist-packages/pip/req.py", line 285, in setup_py
      if six.PY2 and isinstance(setup_py, six.text_type): AttributeError: 'module' object has no attribute 'PY2'

I am currently using Python 2.7.9

python --version
Python 2.7.9

A: Solved upgrading six

pip install --upgrade six


text:
Q: Pass C# code using mvc razor view engine to angular page I have this below c# code which gets me the username.Now, i want to pass this username details to the frontend for display. I am using mvc with razor view engine and front end is using angularjs
how can i pass this C# to html page. ? any idea ?
String UserName = Request.LogonUserIdentity.Name;

Can someone please share an example.

A: Yes, you can use that data binding syntax to bind a property from the object you are passing in to the web form. But that's if you are using webforms. If you are using Mvc with razor view engine, the binding syntax is different. However, as you tagged your question using Angular too, if you are using that, you might want to just return your data from your C# controller in a json format and bind that to the Html view using Angular data binding. You can get more help by giving some more details about your app.


text:
Q: Using command prompt batch files to move and automatically rename duplicate files So, here's what I have: I created a small batch file to record the results of a ping test to a text file.  What I want to do is run the batch file and move the results log to a specific folder on the Desktop automatically.  Then, if the target filename exists, automatically rename accordingly.  Meaning, if File1 exists, create File2, File3, so on and so forth.  Here's what I have so far:
@echo off
color A
title Ping Test
:A
echo.
cls
ping google.com -n 4 > C:\Users\%username%\Desktop\pingresults.txt
cls
:Question
echo.
echo You can find the results in C:\Users\%username%\Desktop\pingresults.txt
echo Would you like to run this test again? (Y/N)
Set /p Choice=
if %choice% equ y goto :A
if %choice% equ n goto :Results
if %choice% neq y goto :Question
if %choice% neq n goto :Question
:Results
cls
echo Would you like to view the results of the test? (Y/N)
Set /p Choice=
if %choice% equ y goto :OpenResults
if %choice% equ n goto :Close
if %choice% neq y goto :Results
if %choice% neq n goto :Results
:Close
exit
:OpenResults
start C:\Users\%username%\Desktop\pingresults.txt

And the move batch file looks like this:
@echo off
echo.
cd C:\Users\Diesel\Desktop
move pingresults.txt PingResults\
if exist pingresults.txt ren pingresults.txt=+1
Exit.

I don't want to overwrite the existing file, but rename it in succession.  I can't find any helpful articles anywhere using only batch files, they all say to use vbs or php, a language I'm not familiar with

A: To rename files to file1 [file2][...] and move it in a desktop folder:
@ECHO Off &SETLOCAL
FOR %%a IN (*.txt) DO CALL:processFile "%%~a"
goto:eof

:processFile
SETLOCAL
:loop
SET /a fileCounter+=1
SET "fileName=%~n1%filecounter%%~x1"
IF EXIST "C:\Users\%username%\Desktop\%fileName%" GOTO:loop
ECHO MOVE "%~1" "C:\Users\%username%\Desktop\%fileName%"
ENDLOCAL
goto:eof

Look at the output and remove the word echo before move  if it looks good.

A: I have a pair of utility files that do this, so I can call from either command line, or another batch file.  This manages several versions of the file in the same folder, and I would call it before moving your new file in.
Usage is:
archivefile 5 "c:\temp\songs" .txt [move]

Where 5 is the number of versions to keep.
The base file name in this example is "c:\temp\songs.txt"
and it creates (in c:\temp) 5 files: songs_1.txt songs_2.txt songs_3.txt songs_4.txt songs_5.txt
If you specify move it will move the original songs.txt otherwise it copies it.
Note, if you're using it from another batch file (which you'll probably want to), you need to use call or it won't return to your original batch file (both batch files will exit instead, which isn't what you want):
call archivefile 5 "c:\temp\songs" .txt

You need the pair of batch files to be either in the current directory, or on the windows path.  Now I think about it, archivefile_b.bat could probably be a sub-routine within the main file instead, but it ain't broke, so I'm not going to fix it.
This is archivefile.bat:
@Echo off
rem archivefile.bat - keep a number of archives of a file
rem paramters:  n rootfile extension [move|copy]
rem n = number of files to keep.
rem move|copy optional indicator to rename (move) the original file instead of copying it
rem archivefile 5 "c:\temp\songs" .txt [move]
rem

if "%3"=="" goto usage

set _af_n=%1
set _af_root=%2
set _af_ext=%3

set _af_move=copy
set _af_moveX=%4
if "%_af_moveX%"=="move" set _af_move=move

set _af_i=
set _af_j=

rem make sure that the first parameter (n) is numeric
set /A _af_n=%_af_n%
if "%_af_n%"=="0" echo Error: number of copies must be numeric (%1) & goto usage

if not exist %_af_root%%_af_ext% echo Error: cannot locate main file: %_af_root%%_af_ext% & goto error

rem remove the oldest file
if exist %_af_root%_%_af_n%%_af_ext% del %_af_root%_%_af_n%%_af_ext%

rem move up the remainder
for /L %%i in (%_af_n%, -1, 1) do call archivefile_b %%i %_af_root% %_af_ext%

rem copy the original

if "%_af_move%"=="move" goto moveIt
rem move not specified - make a copy
copy %_af_root%%_af_ext% %_af_root%_1%_af_ext%

goto moveCopyDone

:moveIt

rem need filename only for a rename
set _af_destfile=%_af_root%_1%_af_ext%
set _af_destfile=%_af_destfile:"=%
for %%i in (%_af_destfile%) do set _af_destfile=%%~ni%%~xi

ren %_af_root%%_af_ext% %_af_destfile%

:moveCopyDone

dir %_af_root%*%_af_ext%

goto done

:usage
echo usage: archivefile n rootfile extension
echo   - n = number of archives to keep
echo   - rootfile = the root filename
echo   - extension = file extension
echo.
echo example:
echo archivefile 5 "c:\Documents and Settings\gregh\My Documents\Rescued document" .txt
goto done

:error
rem could maybe do something here? naa.
goto done

:done

This is archivefile_b.bat, which manages just one of the files:
rem @Echo off
rem archivefile_b.bat - helper for the archivefile routine
rem  -- juggles ONE of the archive files.

rem paramters:  n rootfile extension
rem n = the index to move from n to n+1
rem archivefile 5 "c:\temp\songs" .txt
rem therefore renames c:\temp\songs_5.txt to c:\temp\songs_6.txt

set _afb_n=%1
set _afb_root=%2
set _afb_ext=%3

rem make sure that the first parameter (n) is numeric
set /A _afb_n=%_afb_n%
if "%_afb_n%"=="0" echo Error: (archivefile_b) number of copies must be numeric (%1) & goto done

set /A _afb_j=%_afb_n%+1

rem define the file names
set _afb_fn=%_afb_root%_%_afb_n%%_afb_ext%
set _afb_fj=%_afb_root%_%_afb_j%%_afb_ext%

rem remove the quotes
set _afb_fn=%_afb_fn:"=%
set _afb_fj=%_afb_fj:"=%

rem can only supply a filename to the ren command (not path)
for %%i in (%_afb_fj%) do set _afb_fj=%%~ni%%~xi

rem do the rename now
if exist "%_afb_fn%" ren "%_afb_fn%" "%_afb_fj%"

:done


text:
Q: Hadoop server connection for copying files from HDFS to AWS S3 Requirement is to copy hdfs files from Hadoop cluster(non-aws) to AWS S3 bucket with standalone java application scheduled with daily CRON.
Would be using AmazonS3.copyObject() method for copying.
How to specify the kerberized server connection details for the source Hadoop cluster so that S3client can access the files from source hdfs folder.
The below command was used earlier but its not the secure way of transferring files.
hadoop distcp -Dfs.s3a.access.key=<<>> -Dfs.s3a.secret.key=<<>> hdfs://nameservice1/test/test1/folder s3a://<>/test/test1/folder

A: S3 doesn't go near kerberos; your cronjob will have to use kinit off a keytab to authenticate for the HDFS access.
The most secure way to pass secrets to distcp is to keep them in a JCEKS file in the cluster FS, such as one in the home dir of the user running the job, with permissions only for reading by that person (max paranoia: set a password for encrypting and pass that in with the job). See Protecting S3 Credentials with Credential Providers
One more trick to try: create session credentials using the CLI assume role command, and pass the temporary credentials to distcp for s3a to pick up. That way, yes, the secrets are visible for .ps, but they aren't the longer lived secrets. You can also ask for a specific role there with restricted access compared to the user's full account (e.g: r/w access to one bucket only)


text:
Q: how to fetch data from database? how we can fetch the data from the database through Silver light? I want the basics only. because i am a fresher in silver light.

A: Expose your data through a WCF service.
Have a look at this tutorial: Displaying SQL Database Data in a DataGrid using LINQ and WCF.
Also:

*

*Service-Driven Apps With Silverlight 2 And WCF

*Brad Abrams's Business Apps Example for Silverlight 3 RTM and .NET RIA Services

*.NET RIA Services / WCF Services

A: It depends a little on the version of Silverlight that you are using. In any case, there are some very good and comprehensive tutorials out there on the web. Here are a few that will be of interest:
http://silverlight.net/learn/tutorials/sqldatagrid.aspx
http://www.simple-talk.com/dotnet/.net-framework/data-and-silverlight-2-data-binding/


text:
Q: What are the consequences of joining / leaving factions? I read somewhere that you get really cool gear by joining some factions, but are there any downsides to it, such as, increased hostility from others, or any lost missions?
How do I join individual factions, and when?
Is it always by talking to their chief, or if not, what missions do I need to complete?
And, can I leave at will? Can they throw me out?
What happens when you leave a faction? Change of hostility?

A: You can join the Stalkers right after you help the Stalkers drive the military out of the Cordon.  You can join Duty, Freedom, and the Bandits after you flood the tunnels under the Agroprom Research Institute.  To join a faction, you talk to the leader.
When you join a faction, you typically become an enemy of at least one other faction.

*

*If you join Freedom, Duty becomes
hostile.

*If you join Stalkers,
Bandits become Hostile.

*If you join
Duty, Bandits and Freedom become
hostile.

*If you join Bandits,
Stalkers and Duty become hostile,
Renegades become neutral.

You can switch factions that are still neutral or friendly to you after you join a faction.  For example, if you initially joined the Bandits, you can leave and join Freedom. However, once a faction becomes hostile, you can't get them to become friendly with you again, even if you switch to another faction.
You can't get 'thrown out' of a faction, however, if you kill enough of your fellow faction members, your own faction will become hostile to you.
You lose some side-quests when joining a faction because some side-quests are from factions that become hostile.


text:
Q: Django autocomplete fields do NOT work when using a horizontal filter on a many to many field I am using django's auto complete light to make a custom form. In this model there is another field which I would like to apply a horizontal filter to. However whenever I apply the filter, the autocomplete forms do not work anymore.
@admin.register(model)
class modelAdmin(VersionAdmin):
   form = autoCompleteForm

   filter_horizontal = ('many_to_many_field',)

Open to any solutions, I have searched around and cannot seem to find any other similar problem.

A: For anyone who has the same problem as me. How I got around this problem was I made my own custom widget using autocomplete-light for the many to many field. This still allows to select multiple but allows for a smaller field, its the same size as a charField.
from dal import autocomplete

class many_to_many_field_Autocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        qs = *custom query if needed*

        #search option
        if self.q:
            qs = qs.filter(name__icontains=self.q)

        return qs

Then add the widget to the urls.py file,
urlpatterns = [
    url(
        r'^model-autocomplete/$',
        many_to_many_field_Autocomplete.as_view(),
        name='model-autocomplete',
    ),
]

Then add the custom widget to that field inside of the form class
class VersionForm(forms.ModelForm):
    class Meta:
        model = model_name
        fields = '__all__'
        widgets = {
            'many_to_many_field_name': autocomplete.ModelSelect2Multiple(url='model-autocomplete'),
        }


text:
Q: CLIPS asserting facts with OR condition in RHS is there a way in CLIPS to handle rules like:
(defrule temperature
    (IT-IS-COLD-INSIDE TRUE)
    =>
    (assert
        (IT-IS-COLD-OUTSIDE TRUE)
    )
    (or
        (assert (WINDOW-IS-OPEN TRUE))
        (assert (DOOR-IS-OPEN TRUE))
    )
)

What I am curious about is that, for example, another rule fires and let's say the result of that rule is that the DOOR-IS-OPEN gets asserted to FALSE, then can CLIPS conclude that this means that the WINDOW-IS-OPEN must be TRUE (if of course IT-IS-COLD-INSIDE is TRUE already)?
or I should just write it in the other way around like:
(defrule temperature
    (or
        (WINDOW-IS-OPEN TRUE)
        (DOOR-IS-OPEN TRUE)
    )
    (IT-IS-COLD-OUTSIDE TRUE)
    =>
    (assert (IT-IS-COLD-INSIDE TRUE))
)

The problem with this one is that it is not always true in my use case (the first example always covers the truth though). Let's say maybe there is very strong heating inside. I could just add this also to the picture, but it is not always possible. I am trying to develop a system that can work on data that are partially defined.
When I run my original example, it asserts the first fact (WINDOW-IS-OPEN TRUE) but never the second.
The syntax is probably wrong, but I guess you have the idea of what I am trying to achieve.

A: First define two deftemplates: one for representing known attribute values and another for representing deducible attribute values. Groupings of deducible attribute values will be grouped together using the link slot.
         CLIPS (6.31 6/12/19)
CLIPS>
(deftemplate av
   (slot attribute)
   (slot value))
CLIPS>
(deftemplate dav
   (slot attribute)
   (slot value)
   (slot link))
CLIPS>
(deffacts initial
   (av (attribute it-is-cold-inside)
       (value TRUE)))
CLIPS>

Your temperature rule can then be implemented with the following code.
CLIPS>
(defrule temperature
   (av (attribute it-is-cold-inside)
       (value TRUE))
   =>
   (assert (av (attribute it-is-cold-outside)
               (value TRUE))
           (dav (attribute window-is-open)
                (value TRUE)
                (link temperature))
           (dav (attribute door-is-open)
                (value TRUE)
                (link temperature))))
CLIPS>

Next create rules for managing the deducible attribute values. The remove-dav rule will remove any dav fact when there is a known av fact that conflicts with it. The one-remaining-dav rule will convert a dav fact into an av fact when it is the last remaining dav fact for a specific link.
CLIPS>
(defrule remove-dav
   (declare (salience 10))
   ?dav <- (dav (attribute ?a)
                (value ?v))
   (av (attribute ?a)
       (value ~?v))
   =>
   (retract ?dav))
CLIPS>
(defrule one-remaining-dav
   ?dav <- (dav (attribute ?a)
                (value ?v)
                (link ?l))
   (not (and (dav (attribute ?a2)
                  (value ?v2)
                  (link ?l))
             (test (or (neq ?a ?a2)
                       (neq ?v ?v2)))))
   =>
   (retract ?dav)
   (assert (av (attribute ?a)
               (value ?v))))
CLIPS>

So when the temperature rule initially creates the deductible attribute values:
CLIPS> (reset)
CLIPS> (watch rules)
CLIPS> (watch facts)
CLIPS> (run)
FIRE    1 temperature: f-1
==> f-2     (av (attribute it-is-cold-outside) (value TRUE))
==> f-3     (dav (attribute window-is-open) (value TRUE) (link temperature))
==> f-4     (dav (attribute door-is-open) (value TRUE) (link temperature))
CLIPS>

The appropriate deductions can be made when new information is later added:
CLIPS> (assert (av (attribute door-is-open) (value FALSE)))
==> f-5     (av (attribute door-is-open) (value FALSE))
<Fact-5>
CLIPS> (run)
FIRE    1 remove-dav: f-4,f-5
<== f-4     (dav (attribute door-is-open) (value TRUE) (link temperature))
FIRE    2 one-remaining-dav: f-3,*
<== f-3     (dav (attribute window-is-open) (value TRUE) (link temperature))
==> f-6     (av (attribute window-is-open) (value TRUE))
CLIPS>

A: Thanks Gary! I think this is what I was looking for.
I modified the code a little bit to be a little bit more understandable:
(defrule temperature
   (av (attribute it-is-cold-inside)
       (value TRUE))
   =>
   (assert (av (attribute it-is-cold-outside)
               (value TRUE))
           (dav (attribute window-is-open)
                (value MAYBE)
                (link temperature))
           (dav (attribute door-is-open)
                (value MAYBE)
                (link temperature))))
(defrule one-remaining-dav
   ?dav <- (dav (attribute ?a)
                (value ?v)
                (link ?l))
   (not (and (dav (attribute ?a2)
                  (value ?v2)
                  (link ?l))
             (test (or (neq ?a ?a2)
                       (neq ?v ?v2)))))
   =>
   (retract ?dav)
   (assert (av (attribute ?a)
               (value TRUE))))


text:
Q: Почему apache + nginx при обработке изображений отдает 500 ошибку? Есть php скрипт, который выполняет обработку большого количества изображений (ресайз, наложение вотермарков и тд.). Проблема в том, что скрипт по истечению 40 минут работы отдает 500 ошибку, а затем, с каждым последующим запуском отваливается еще раньше, хотя таймаут на выполнение запроса стоит около часа. В логи пишет upstream prematurely closed connection while reading response header from upstream
У Apache

*

*max_execution_time 3600

*max_input_time 3600

*upload_max_filesize 512M

*post_max_size 512M

*memory_limit 512M

У nginx

*

*proxy_connect_timeout 3600s

*proxy_send_timeout 3600s

*proxy_read_timeout 3600s

*proxy_buffer_size          512k

*proxy_buffers              512   4096k

*proxy_busy_buffers_size 4096k

*proxy_temp_file_write_size 4096k

*client_max_body_size 30m

*client_body_buffer_size      4096k

*large_client_header_buffers 8 32k

В самом скрипте после обработки каждого каталога очищается дисковый кэш.
Как можно решить данную проблему, не прибегая к крону и/или запуску скрипта непосредственно на сервере?

A: Оказалось что apache съедал всю оперативку, но в лог ничего не писал, а писал nginx. gc_collect_cycles() исправил ситуацию.

A: Смотрите логи выполнения PHP. Вы не те логи смотрите. У вас скорее всего скрипт спотыкается на обработке одного и того же изображения.
А вообще лучше используйте консольные скрипты и ставьте большие лимиты на все:
set_time_limit(0); // бесконечное выполнение скрипта, либо очень большой таймаут ставьте
ini_set('memory_limit', '1G') // укажите лимит на память побольше
ini_set('display_errors', E_ALL); // включайте вывод всех ошибок

При запуске в консоле переводите STDOUT и STDERR в файл для логирования:
$ php /var/www/myhost/my_script.php >> /var/log/my_script.log 2>&1

При необходимости запускайте через CRON и flock для проверки запуска только 1 скрипта одновременно:
* * * * * /usr/bin/flock -xn /var/lock/my_lock_name -c '/usr/bin/php -q /var/www/myhost/my_script.php' >> /var/log/my_script.log 2>&1

Данное событие будет запускаться каждую минуту, и если lock файла нет, то php скрипт запускается. При таком подходе в самом скрипте можно просто проверять необходимость обработки. То есть создать в БД некую очередь.

хотя таймаут на выполнение запроса стоит около часа

Около часа? Как вы поставили "около часа"?


text:
Q: how to properly handle a file upload in wicket I have a file upload page that takes a file and parses it.
Order of Events

*

*user uploads file

*uploaded file gets copied

*copied file gets it's encoding checked, with CPDetector

*determined encoding from the copied file is used to parse the original uploaded file

*

*FileNotFoundException on Solaris Test Server during BufferedReader creation.

*copied file is deleted

*uploaded file is parsed/verified

*parsed data is saved to a database

*uploaded file is deleted (I can't remember if I'm doing this or Tomcat is.)

The Whole process works on my Windows 7 workstation. As noted above it does not work on my Solaris Test Server. Something(I Suspect Tomcat) is deleting the uploaded file before I can finish parsing it.
I've watched the directory during the process and an uploaded file does indeed get created, but it lasts less than a second before being deleted.  Also It's supposed to go into /opt/tomcat/ but seems be getting created in the /var/opt/csw/tomcat6/temp/ directory instead.
Thanks for any help

A: I realize it's probably bad form to answer my own question like this but I wanted to leave this here in-case it helps someone else.
The Problem turned out to be How I was accessing the files.
I had hard-coded file paths, for windows, and Database loaded ones for the test server.
I switched those to using System.getProperty("catalina.home")+"/temp/" + filename
I'm also copying the temp file a second time so I end up with:
Order of Events (changes are in bold)

*

*user uploads file

*uploaded file gets copied

*copied file gets it's encoding checked, with CPDetector

*uploaded file gets copied again to ensure a copy survives to be parsed

*determined encoding from the copied file is used to parse the original uploaded file

*copy used for encoding detection is deleted

*copy for parse is parsed/verified

*parsed data is saved to a database

*parsed file is deleted.

*uploaded file is deleted (I'm not sure if I'm doing this or Tomcat is.)


text:
Q: Mutation of numpy array input to a function A function I wrote mutated my input variable, a numpy array, and I do not understand why. Let me explain with the following code:
def f(array):
    array = array/2
    return array

def g(array):
    array[array > 2] = 2
    return array

test_array = numpy.array([[1,2], [3,4]])

f(test_array)

print(test_array) # Returns [[1,2], [3,4]], so test_array is not mutated

g(test_array)

print(test_array) # Returns [[1,2], [2,2]], so test_array is mutated

Function f does not mutate test_array, i.e., test_array is unchanged after running f. However function does g mutate test_array.
Does anyone know why this happens?


text:
Q: Website written in C# and ASP.NET MVC is compiling ASCX pages with Visual Basic I am developing a website in ASP.NET MVC using C#. It works fine on my machine, however when I load it to the production server it generates an error trying to present the home page.
The error is caused by the fact that the ASP system is compiling the .ascx pages using Visual Basic, which, of course, does not work since all of the code is in C#.
How do I fix this?

A: Does your production app have the following stuff in it's app config?
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <providerOption name="CompilerVersion" value="v3.5"/>
    <providerOption name="WarnAsError" value="false"/>
</compiler>

Also, have you verified that your Master Page / Views contain
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<YourType>" %>

and
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<LoginPageView>" %>

The Language specification?

A: I found that the default compiler language needs to be specified in the web.config file.
For some reason this is not specified in my project (which was built by a Visual Studio template). It appears that when running locally the ASP system correctly infers the default language, but when running on a remote server it defaults to Visual Basic.
The default compiler language setting is set as follows:
<compilation
   defaultLanguage="c#"
/>

where the compilation tag is in the system.web tag which is in the configuration tag. Note that there is a capital L in defaultLanguages. Also note that normally this tag will already be present with lots of other information in it, you need to just add the defaultLanguage attribute.

A: I had this problem yesterday, as a matter of fact...
In your .ascx files, you need to include the control directive with the appropriate language attribute at the top of the page:
<%@ Control Language="C#" ... %>


text:
Q: UiAutomator cannot find UiObject that on a screen I trying to click on a button with UiAutomator, but receive error "androidx.test.uiautomator.UiObjectNotFoundException"
I tried to locate object in two ways.

*

*UiObject cartButton = uiDevice.findObject(new Selector().resourceId("R.id.group_cart_add_button"));

*UiObject2 cartButton = uiDevice.findObject(By.res(InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageName(), "R.id.group_cart_add_button"));
Then I use cartButton.click() but both times I receive an error.
In hierarchy this object is exist
And when I try to find it in Evaluate tool, I can do it:
But if I try to click, I receive an error:
Why?

A: You can do the following:
String packageName = "your-app-package-name"
String fullCartButtonResourceId = packageName + ":id/group_cart_add_button";
UiObject2 cartButton = mDevice.findObject(By.res(uk));

or
UiObject cartButton = findObject(new UiObject(new UiSelector().resourceId(fullCartButtonResourceId));


text:
Q: State Preservation and Restoration UIImageView added from button event I am adding UIImageView on a button click. I want to restore it using UIKit.
I am getting restoration identifier in:
 - (void)decodeRestorableStateWithCoder:(NSCoder *)coder;

How can I decode this UIImageView?

A: To make the state preservation and restoration work there are two steps that are always required:

*

*The App delegate must opt-in

*Each view controller or view to be
preserved/restored must have a restoration identifier assigned.

You should also implement encodeRestorableStateWithCoder: and decodeRestorableStateWithCoder: for views and view controllers that require state to be saved and restored.
Add the following methods to the view controller of your UIImageView.
-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
    [coder encodeObject:UIImagePNGRepresentation(_imageView.image)
                 forKey:@"YourImageKey"];

    [super decodeRestorableStateWithCoder:coder];
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    _imageView.image = [UIImage imageWithData:[coder decodeObjectForKey:@"YourImageKey"]];

    [super encodeRestorableStateWithCoder:coder];
}

State preservation and restoration is an optional feature so you need to have the application delegate opt-in by implementing two methods:
- (BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder
{
    return YES;
}

- (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder
{
    return YES;
}

Useful article about state preservation:
http://useyourloaf.com/blog/2013/05/21/state-preservation-and-restoration.html

A: i have used this code in one of my app.
here is the encoding & decoding process
-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{

NSData *imageData=UIImagePNGRepresentation(self.imgViewProfilePicture.image);
[coder encodeObject:imageData forKey:@"PROFILE_PICTURE"];
[super encodeRestorableStateWithCoder:coder];
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{

self.imgViewProfilePicture.image=[UIImage imageWithData:[coder decodeObjectForKey:@"PROFILE_PICTURE"]];
[super decodeRestorableStateWithCoder:coder];

}


text:
Q: GhostScipt - Can resize output image file I'm converting pdf to html with help GS 9.04.
But in result i'm getting big file and it's ok for printing purpose.
But for monitor screen i would like to have the same quality but smaller size.
Is it possible to make resize by GS and do not loose the quality ?
now i have the next code
gs \
 -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT \
 -r300 \
 -sDEVICE=pngmono \
 -dTextAlphaBits=4 \
 -dFirstPage={$page} \
 -dLastPage={$page} \
 -sOutputFile={$filename} \
  {$pdf}

and output file is good for printing. When i'm using -g option it makes crop.
If i'm adjusting -r value it makes smaller and ugly at the same moment.
What i want to get is smaller image suitable and readable to looking on it via screen.

A: You can use a lower resolution which will generate a smaller output file. The fact that you prefer the high resolution image suggest that there is some kind of anti-aliasing or other image manipulation being performed on the image, Ghostscript can do this, by using 'interpolation' but its not really what its good at.
Ideally you would do this with an image manipulation package, but you can try the tiffscaled devices (on gs 9.04) to get an idea of what can be done. Personally I would suggest you use something like imagemagick to do the resolution reduction.


text:
Q: Next-auth credential signup page So I am trying to integrate Next-Auth into my project to create a members area plus staff portal for our site.
I have noticed that I can do a credential that would allow me to use the username and passwords already in the database - however I can't seem to find the documentation on a signup page for credentials logins as we want to accept new members/staff to register.
What I have found is the following:
import CredentialsProvider from `next-auth/providers/credentials`
...
providers: [
  CredentialsProvider({
    // The name to display on the sign in form (e.g. 'Sign in with...')
    name: 'Credentials',
    // The credentials is used to generate a suitable form on the sign in page.
    // You can specify whatever fields you are expecting to be submitted.
    // e.g. domain, username, password, 2FA token, etc.
    // You can pass any HTML attribute to the <input> tag through the object.
    credentials: {
      username: { label: "Username", type: "text", placeholder: "jsmith" },
      password: {  label: "Password", type: "password" }
    },
    async authorize(credentials, req) {
      // You need to provide your own logic here that takes the credentials
      // submitted and returns either a object representing a user or value
      // that is false/null if the credentials are invalid.
      // e.g. return { id: 1, name: 'J Smith', email: 'jsmith@example.com' }
      // You can also use the `req` object to obtain additional parameters
      // (i.e., the request IP address)
      const res = await fetch("/your/endpoint", {
        method: 'POST',
        body: JSON.stringify(credentials),
        headers: { "Content-Type": "application/json" }
      })
      const user = await res.json()

      // If no error and we have user data, return it
      if (res.ok && user) {
        return user
      }
      // Return null if user data could not be retrieved
      return null
    }
  })
]
...

However I don't see how this will allow signup feature.

A: It is easy man after the user signup then call login function with email and password which created in advance.
const email = "abs@gmail.com";
const pass = "123456"
axios.post('http:yoursignupURL',{email , pass});
// after user registered in database
login('credential',{
email : email,
password : password
})


text:
Q: center align three divs side by side with CSS I've got three divs side by side in a container that sets itself to the width of the user's window.
I want them to stay nested next to each other, and centered as a unit in the dynamic container.
I'd like to do this without putting them into another div (mostly because I have a lot of them in this page as it is).
HTML:

COLLECTIONS

blahblah

COLLECTIONS

blahblah

COLLECTIONS

blahblah

CSS:
#nav_one {
    width: 208px;
    float: left;
    padding: 20px 10px 20px 10px;
    text-align: center;
}

#nav_two {
    width: 208px;
    margin: 0 auto;
    padding: 20px 10px 20px 10px;
    text-align: center;
}

#nav_three {
    width: 208px;
    float: right;
    padding: 20px 10px;
    text-align: center;
}

A: Ok, after the comment below, I have a better idea what you are looking for, with the caveat of the container div's requiring 208px. I don't think that margin: auto will here to center all three in a group, so I propose float: left and use jQuery to calculate #content div, subtract .container widths, and divide by two to get left margin for the left-most .container div.
.container {
    width:208px;
    float:left;
    padding:0;
    margin: 0 auto;
    text-align:center;
    background-color: #cccccc;
}
.container p {
    text-align:justify;
    padding: 20px 10px 20px 10px;
}

$(document).ready(function(){
    var w = $('#content').width();
    var calw = (parseInt(w) - (208*3))/2;
    $('#left').css('margin-left',calw+'px');
});

COLLECTIONS

blahblah

COLLECTIONS

blahblah

COLLECTIONS

blahblah

EDIT
To take into account the fixed-width 208px div containers, I think the easiest way to do this would be to use a little bit of jQuery:
$(document).ready(function(){
    var w = $('#content').width();
    var calw = (parseInt(w) - (208*3))/2;
    $('#left').css('margin-left',calw+'px');
});

Here's a jsfiddle to demonstrate the effect (updated with the above).
Of course, at this point, you might very well be better off using a container div with a margin auto applied to it, and a width of the 3 contianer div's you have with it. Of course, this approach causes problems in IE due to a bug in the way margin: auto is handled.
.container2 {
    width:208px;
    float:left;
    padding:0;
    margin: 0 auto;
    text-align:center;
    background-color: #cccccc;
}
.container2 p {
    text-align:justify;
    padding: 20px 10px 20px 10px;
}
#content2 {
    width: 624px;
    background-color: #ccccaa;
    margin: 0 auto;
}

COLLECTIONS

blahblah

COLLECTIONS

blahblah

COLLECTIONS

blahblah

Showing both.

A: If I understand correctly you are trying to center the 3 divs class container inside the div id content. Width of your container div determines the spacing of your 3 nesting divs, if you want them closer together simply adjust the width of the container div. If your container div happens to be a fixed width use padding to push content around inside.

A: use this:
#content {
    width: 684px;
    margin:0 auto;
}

#nav_one, #nav_two, #nav_three {
    width: 208px;
    float: right;
    padding: 20px 10px;
    text-align: center;
}

A: Its generally a bad idea to use fixed width measurements in your css. Set your width measurements using a percentage and then restrict them using px measurements with min-width and max-width. This will allow the most portability to various screen sizes.
Basically what you are doing is micro-managing. By using percentages instead you allow the browser to render your content more easily.

A: Recent comment from @gollum18, so here's a better answer than all of the above.
HTML

CSS
section {
    text-align: center;
}
    .third {
        width: 33.333%;
        width: -webkit-calc(100% / 3);
        width: -moz-calc(100% / 3);
        width: calc(100% / 3);
    }
    .center-align {
        display: inline-block;
        text-align: left;
    }


text:
Q: What is the equivalent of the Oracle "Dual" table in MS SqlServer? What is the equivalent of the Oracle "Dual" table in MS SqlServer?
This is my Select:
SELECT pCliente,
       'xxx.x.xxx.xx' AS Servidor,
       xxxx AS Extension,
       xxxx AS Grupo,
       xxxx AS Puerto
FROM DUAL;

A: In sql-server, there is no dual you can simply do
SELECT pCliente,
       'xxx.x.xxx.xx' AS Servidor,
        xxxx AS Extension,
        xxxx AS Grupo,
        xxxx AS Puerto

However, if your problem is because you transfered some code from Oracle which reference to dual you can re-create the table :
CREATE TABLE DUAL
(
DUMMY VARCHAR(1)
)
GO
INSERT INTO DUAL (DUMMY)
VALUES ('X')
GO

A: While you usually don't need a DUAL table in SQL Server as explained by Jean-François Savard, I have needed to emulate DUAL for syntactic reasons in the past. Here are three options:
Create a DUAL table or view
-- A table
SELECT 'X' AS DUMMY INTO DUAL;

-- A view
CREATE VIEW DUAL AS SELECT 'X' AS DUMMY;

Once created, you can use it just as in Oracle.
Use a common table expression or a derived table
If you just need DUAL for the scope of a single query, this might do as well:
-- Common table expression
WITH DUAL(DUMMY) AS (SELECT 'X')
SELECT * FROM DUAL

-- Derived table
SELECT *
FROM (
  SELECT 'X'
) DUAL(DUMMY)

A: You don't need DUAL in MSSQLserver
in oracle
select 'sample' from dual

is equal to
SELECT 'sample'

in sql server

A: In SQL Server there is no dual table. If you want to put a WHERE clause, you can simple put it directly like this:
SELECT 123 WHERE 1<2
I think in MySQL and Oracle they need a FROM clause to use a WHERE clause.
SELECT 123 FROM DUAL WHERE 1<2

A: This could be of some help I guess, when you need to join some tables based on local variables and get the information from those tables:
Note: Local variables must have been
Select  @XCode     as 'XCode '
       ,@XID       as 'XID   '
       ,x.XName    as 'XName '
       ,@YCode     as 'YCode '
       ,@YID       as 'YID   '
       ,y.YName    as 'YName '
From (Select 1 as tst) t
Inner join Xtab x on x.XID = @XID
Inner join Ytab y on y.YID = @YID

A: It's much simpler than that.
Use literal values to establish data types.
Put quotes around column names if they need special characters.
Skip the WHERE clause if you need 1 row of data:
SELECT  'XCode' AS XCode
       ,1 AS XID
       ,'XName' AS "X Name"
       ,'YCode' AS YCode
       ,getDate() AS YID
       ,'YName' AS "Your Name"
 WHERE 1 = 0


text:
Q: Why can I push to a remote under a different user.name and user.email without logging in? I first deleted all credentials related to git in the credential manager in Windows, changed my user.name and user.email to another user in a repo and then push to a remote. Git then asked me to login via browser. I clicked the login button and the browser tab that showed up told me the authentication succeeded right away without asking me to enter the password of the new user. And when I check the commits history on Github, it showed the commit was made by the new user(the user that I changed my user.name to), but that user has never logged in on my computer. How is this possible? Is it related to ssh? But I push and pull using only https. And why can the new user push to my repo? I didn't add him as my collaborator.

A: user.name and user.email are not related to authentication at all. These are just fields written to commits made locally. Anyone can write anything for these fields and anyone can push commits declared as made by anyone.
You can think of those fields like an email signature: you write it when creating the email/commit and people can read it but it's just a part of the email/commit and anyone can write anything in the emails/commits they send/make.


text:
Q: "Boy, was that class boring!" Why is "was" at the beginning when the sentence is not a question?
A: Boy, was that class boring!
B: Sure was.

As you can see sentence 'a' is not a question. So why 'was' is the first word in the sentence?

A: I guess this could be considered a class of exclamatory question. In particular, there's a common construction that takes the structure of a question but uses it as an exclamation, with an assumed meaning of "yes" to the question.
A common stand-up-comedy joke is "I just flew in from [some other city], and boy, are my arms tired!" It doesn't really mean to ask a question at all—it's not asking "are my arms tired?"; in fact, this construction emphasizes that the statement is certain.
It's related to some other exclamatory-question structures, like "Isn't she lovely!", but a little different: Isn't she lovely means "Is she not lovely"; many exclamatory questions include a negative like that. "Won't it be great?" "Haven't you heard?" But the construction in this example uses a positive question; it also often includes an intensifying word or phrase like "Boy!," "Man!," "Oh my," etc.
Other examples:

*

*Did I enjoy it? Man, did I ever!

*When my dad hears about this, will he be mad or what!"

A: This particular word order is idiomatic/natural in English. All you need to know is learn what it means:
Boy, was that class boring! = Boy, what a boring class it was!
Here's another example:
Boy, was the movie interesting! = Boy, what an interesting movie it was!


text:
Q: java.lang.NoClassDefFoundError when using class from another module I added dependency of a custom jar(say some-jar.jar) in a module's pom.xml where I need to write my code inside say CustomClass.java. Now, some-jar.jar contains AnotherClass.class which I need to use in my code.
After I finish my code, build succeeds and I am able to successfully deploy the application.
But when the execution reaches my code, it throws an ERROR(not an exception) saying
java.lang.NoClassDefFoundError: com/some/package/AnotherClass
. . . and the usual stack trace.

I understand this is happening because JVM is not able to locate this file at Runtime even though at compile time it was located, but what is the solution here? What do I need to do to make it available at Runtime.
Unfortunately, due to some restrictions I cannot disclose any more information than this issue. Lets see, if it is even required.

A: You can either specify your dependencies in classpath like this or make a fat jar (google it)


text:
Q: Unable to Generate Ad Banner With Firebase. I keep getting error "no resource identifier found for Attribute for adUnitID" I have followed the sample google video as well as 5 other relevant "How to make a banner" videos and no one is running into my problem. When I add the following code to my xml (within relative layout)
 com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        ads:adSize="BANNER"
        ads:adUnitID="ca-app-pub-9079489398627366/3701601134">
    </com.google.android.gms.ads.AdView>

It asks me to add xmlns:ads="http://schemas.android.com/apk/res-auto
I do then everything looks fine. Once I compile I get the error:

Error:(72) No resource identifier found for attribute 'adUnitID' in package 'mypackage'

Here is what I have done with other necessary files:
MANIFEST
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-           permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
    <activity
    android:name="com.google.android.gms.ads.AdActivity"
      android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
      android:theme="@android:style/Theme.Translucent"></activity>

My java code:
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);

My gradle:
    android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
    applicationId "willvanbuskirk.com.trumpfactsandquotes"
    minSdkVersion 14
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {

        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
   }

   dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.firebase:firebase-core:9.6.0'
    compile 'com.google.firebase:firebase-ads:9.6.0'

   }
   apply plugin: 'com.google.gms.google-services'

A: did you forgot initialization by using your app_id, not ad_unit_id
 MobileAds.initialize(getApplicationContext(),getString(R.string.adMob_app_id));


text:
Q: iOS: didSelectRowAt Index Path only works on second click I am struggling with an issue on my xcode project. I'm displaying custom cells in a table view and using didSelectRowAt indexPath: to show a detail view. It works the way I want to, but weirdly only on the second click.
I am fairly new to programming and would appreciate your help with this. Thank you so much!
I checked that I'm not using didDeselectRow at by accident. I also went through stackoverflow to try and find a solution, and that was the closest I could find to my issue. But I am using didSelectRow at.
// Here is my code for when the user taps a cell:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    // Pop Up Variables

    var id:String = tasks[indexPath.row].task_id!
    var title:String = tasks[indexPath.row].task_title!
    var type:String = tasks[indexPath.row].task!
    var desc:String = tasks[indexPath.row].task_desc!
    var action:String = "Dismiss"

    present(detailVC!, animated: true, completion: {
        self.detailVC!.setPopup(withTaskId: id, withTitle: title, withType: type, withDesc: desc, withAction: action)
         })

}

// Just a note here,I am setting up the switch to the other view controller at the top of the document.
// Display the popup
    var detailVC:TaskDetailViewController?
override func viewDidLoad() {
    super.viewDidLoad()

    // Set up the task detail view controller
    detailVC = storyboard?.instantiateViewController(withIdentifier: "TaskDetailVC") as! TaskDetailViewController?
    detailVC?.delegate = self
    detailVC?.modalPresentationStyle = .overCurrentContext

    // Conform to the table view protocols
    tableView.dataSource = self
    tableView.delegate = self

    // Set Self as delegate for model and call getTasks

    // Get the Tasks from the Task Model
    model.delegate = self
    model.getTasks()

}

The detail view only appears after I tap a row the second time. Not the first time?

A: I had this issue a few years back, didn't know that it still persist today.
I solved it by encapsulating all logic within didSelectRowAt in the main thread using GCD. You can check these out:
https://stackoverflow.com/a/27907119/6642629
https://stackoverflow.com/a/26183438/6642629
You can try the following:
Swift 4
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    DispatchQueue.main.async {

        var id:String = tasks[indexPath.row].task_id!
        var title:String = tasks[indexPath.row].task_title!
        var type:String = tasks[indexPath.row].task!
        var desc:String = tasks[indexPath.row].task_desc!
        var action:String = "Dismiss"

        present(detailVC!, animated: true, completion: {
            self.detailVC!.setPopup(withTaskId: id, withTitle: title, withType: type, withDesc: desc, withAction: action)
        })
    }
}

A: Just change Selection of your UITableView in InterfaceBuilder from Multiple Selection to Single Selection and it will works as you wish.
Then you should handle selected state of each row on your own (using a field in model or set color for background or etc)


text: Q: How do I find the version for a Dynamic Library (.dylib file) in MACOS I have a Dynamic library (abc.dylib) with version say 6.0.1.104 in my local file system. I can go ahead and right click the file > Get Info and find it's version. But I want a way by which I can do it programmatically in java or from any terminal command. Is there any way to do this?


text:
Q: How to convert VisualStudio project to Eclipse CDT The question is already in the title. I have a Visual Studio project which builds a .dll. Now I need the same library for MacOS X and linux, so I would like to convert the VS project to Eclipse and compile it for both platforms.
I will be very thankful for any tips, hints or guidance!

A: First of all, you need to know which compiler you have to use, then
 1. you can convert the project in a MakeFile and create a Makefile project in Eclipse
 2. or you can try to convert the project in a compiler-specific project.


text:
Q: Drawing the phase portrait of two differential equations I am trying to make a phase portrait of two differential equations (second order) and the vector field of ODE. The equations are(I took the example from the following article):
x'=x-4x^2+2y^2+10xy
y'=y+4y^2+4xy

and the vector field is F(x,y)=(x-4x^2+2y^2+10xy,y+4y^2+4xy).
I would like the result to be something like this. I have found many variants to model a phase diagram but none help me in this case (for example here I found this example, but I can't replicate it in latex). I would really appreciate your help because I have been trying to do something that works well regardless of the field I put in and nothing works for me.

Whereas the vector field should look something like this(I made this graph here):

A: A solution I often use to draw phase diagrams is this one from How to draw slope fields with all the possible solution curves in latex, which I added my version with two functions in quiver={ u={f(x,y)}, v={g(x,y)} ...}.
It lets me generate local quivers from functions f(x,y) and g(x,y) while keeping a predefined style. I may add new curves with \addplot such as \addplot +[blue] {-4*x};, which seems to be one of the the lines, the one with \addplot +[violet] {+x} I could visually find.
Improvements needed to achieve final result:

*

*Draw arrows correctly where I used \addplot to draw added functions.

*Draw arrows in quiver with curves.

*Automatically find equations for \addplot, as it is, one must do the math and then insert results.

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}

\usepackage{amsmath}
\usepackage{derivative}

\pgfplotsset{ % Define a common style, so we don't repeat ourselves
  MyQuiver2D/.style={
    width=0.6\textwidth, % Overall width of the plot
    axis equal image, % Unit vectors for both axes have the same length
    view={0}{90}, % We need to use "3D" plots, but we set the view so we look at them from straight up
    xmin=-2.1, xmax=2.1, % Axis limits
    ymin=-2.1, ymax=2.1,
    domain=-2:2, y domain=-2:2, % Domain over which to evaluate the functions
    xtick={-2,-1.5,...,2}, ytick={-2,-1.5,...,2}, % Tick marks %
    samples=21, % How many arrows?
    cycle list={    % Plot styles
      gray,
      quiver={
        u={f(x,y)}, v={g(x,y)}, % End points of the arrows
        scale arrows=0.015,
        every arrow/.append style={
          -latex % Arrow tip
        },
      }\\
      red, samples=31, smooth, very thick, no markers, domain=-2:2\\ % The plot style for the function
    }
  }
}

\begin{document}

\begin{tikzpicture}[
  declare function={f(\x,\y) = \x - 4*\x*\x + 2*\y*\y + 10*\x*\y;},
  declare function={g(\x,\y) = \y + 4*\y*\y + 4*\x*\y;}
  ]
  \begin{axis}[
      MyQuiver2D,
      title={$\displaystyle \odv{x}{t}=x-4x^2+2y^2+10xy; \odv{y}{t}=y+4y^2+4xy$},
      width=\textwidth
    ]
    \addplot3 (x,y,0);
    \addplot +[] {0};
    \addplot3 (x,y,0);
    \addplot +[magenta] {-4*x};
    \addplot3 (x,y,0);
    \addplot +[violet] {+x};
  \end{axis}
\end{tikzpicture}
\end{document}

Edit and Update
This solution improves:

*

*All vector are normalized and colored quiver, where colors represent the "strength" or "real size".

*Each plot has decorations with arrows.

*Better organization of styles to reuse and default settings.

The solution is based on:

*

*PGFPlots Parametric Plot, Arrow Spacing by Constant Time.

*Plot Vector Field in LaTeX TikZ.

While editing your graph, I realized it could be interesting show the fixed points of your EDO, despite they are not shown in the original paper. In this process, I noted I created the first solution with domain=-2:2, and I could not really see the vector field close to some fixed points. Therefore I added them with coordinates. I checked the fixed points with WolframAlpha:

*

*https://www.wolframalpha.com/input?i2d=true&i=%7B%7Bx-4Power%5Bx%2C2%5D%2B2Power%5By%2C2%5D%2B10xy%7D%2C%7By%2B4Power%5By%2C2%5D%2B4xy%7D%7D%3D%7B%7B0%7D%2C%7B0%7D%7D.

So I edited styles in order to better handles local defined domains and then I created a second figure with domain=-0.4:0.4.
A MWE follows:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}
\usetikzlibrary{decorations.markings}

\usepackage{amsmath}
\usepackage{derivative}

% Define style to the axis
\pgfplotsset{MyQuiverAxis/.style={
    width=\textwidth, % Overall width of the plot
    xlabel={$x$}, ylabel={$y$},
    xmin=-2.1, xmax=2.1, % Axis limits
    ymin=-2.1, ymax=2.1,
    domain=-2:2, y domain=-2:2, % Domain over which to evaluate the functions
    axis equal image, % Unit vectors for both axes have the same length
    view={0}{90}, % We need to use "3D" plots, but we set the view so we look at them from straight up
    % colormap/viridis,
    colormap/hot,
    colorbar,
    colorbar style = {
      ylabel = {Vector Length}
    }
  }
}

% Define a common style to quivers
\pgfplotsset{MyQuiver2Dnorm/.style={
    %cycle list={% Plot styles
    samples=15, % How many arrows?
    quiver={
      u={f(x,y)/sqrt((f(x,y)^2+(g(x,y))^2))}, v={g(x,y)/sqrt((f(x,y)^2+(g(x,y))^2))}, % End points of the arrows
      scale arrows=0.2,
    },
    -latex,
    %},
    % domain=-0.5:0.5, y domain=-0.5:0.5, % Change if domain not equal to axis functions
    quiver/colored = {mapped color},
    point meta = {sqrt((f(x,y))^2+(g(x,y))^2)},
  }
}

\pgfplotsset{MyArrowDecorationPlot/.style n args={3}{
    decoration={
      markings,
      mark=between positions #1 and #2 step 2em with {\arrow [scale=#3]{latex}}
    }, postaction=decorate
  },
  MyArrowDecorationPlot/.default={0.1}{0.99}{1.5}
}

\begin{document}
\begin{tikzpicture}[
  declare function={f(\x,\y) = \x - 4*(\x)^2 + 2*(\y)^2 + 10*\x*\y;},
  declare function={g(\x,\y) = \y + 4*(\y)^2 + 4*\x*\y;}
  ]
  \begin{axis}[
    MyQuiverAxis,
    title={$\displaystyle \odv{x}{t} = x-4x^2+2y^2+10xy; \odv{y}{t} = y+4y^2+4xy$},
    ]
    \addplot3 [MyQuiver2Dnorm] (x,y,0);
    \addplot [thick, red, domain=2:-2, MyArrowDecorationPlot] {0};
    \addplot [thick, magenta, domain=2:-2, MyArrowDecorationPlot] {-4*x};
    \addplot [thick, violet, MyArrowDecorationPlot] {+x};
    \addplot [very thick, fill=white, only marks] coordinates {(0,0) (-1/8,-1/8) (1/12,-1/3) (1/4,0)};
  \end{axis}
\end{tikzpicture}

\begin{tikzpicture}[
  declare function={f(\x,\y) = \x - 4*\x*\x + 2*\y*\y + 10*\x*\y;},
  declare function={g(\x,\y) = \y + 4*\y*\y + 4*\x*\y;}
  ]
  \begin{axis}[
    MyQuiverAxis,
    title={$\displaystyle \odv{x}{t} = x-4x^2+2y^2+10xy; \odv{y}{t} = y+4y^2+4xy$},
    xmin=-0.4, xmax=0.4, % Axis limits
    ymin=-0.4, ymax=0.4,
    domain=-0.4:0.4, y domain=-0.4:0.4
    ]
    \addplot3 [MyQuiver2Dnorm,
      domain=-0.35:0.35, y domain=-0.35:0.35,
      quiver={scale arrows=0.025}] (x,y,0);

    \addplot [thick, red, domain=0:-0.4, MyArrowDecorationPlot] {0};
    \addplot [thick, red, domain=0:1/4, MyArrowDecorationPlot] {0};
    \addplot [thick, red, domain=0.4:1/4, MyArrowDecorationPlot] {0};

    \addplot [thick, magenta, domain=0:-0.4,
      MyArrowDecorationPlot={0.05}{1}{1.25}] {-4*x};
    \addplot [thick, magenta, domain=0:1/12,
      MyArrowDecorationPlot={0.05}{1}{1.25}] {-4*x};
    \addplot [thick, magenta, domain=0.4:1/12,
      MyArrowDecorationPlot={0.05}{1}{1.25}] {-4*x};

    \addplot [thick, violet, domain=-0.4:-1/8, MyArrowDecorationPlot] {+x};
    \addplot [thick, violet, domain=0:-1/8, MyArrowDecorationPlot] {+x};
    \addplot [thick, violet, domain=0:0.4, MyArrowDecorationPlot] {+x};

    \addplot [very thick, fill=white, only marks] coordinates {(0,0) (-1/8,-1/8) (1/12,-1/3) (1/4,0)};
  \end{axis}
\end{tikzpicture}
\end{document}

Figures
First figure with domain=-2:2.

Second figure with domain=-0.4:0.4. This new solution shows how to change the domain of the vector field and also how to show the decorated plots in the same direction as the vector field.

A: I guess this could be made with pgfplots, using a variation of this code? (Note that it must be compiled with lualatex.)
\documentclass[border=0.2cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat = newest}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
   view = {0}{90},
   domain = -0.2:0.2,
   domain y = -0.2:0.2,
   xmin=-0.2,
   xmax=0.2,
   ymin=-0.2,
   ymax=0.2,
   ]
   \addplot3[
      -stealth,
      black!20,
      samples=20,% Controls the number of arrows
      quiver = {
         u = x-4*x^2+2*y^2+10*x*y,
         v = y+4*y^2+4*x*y,
         scale arrows = 0.2,
      }
      ] {0};
   \addplot3[contour lua={number=10, labels=false}] {x-4*x^2+2*y^2+10*x*y};% !!!!! NEEEDS lualatex for compilation
\end{axis}
\end{tikzpicture}

\end{document}


text:
Q: Pythonic way to handle arguments with values in Union In the code below, print_pos accepts one argument which can be of
three different types.
from typing import List, Tuple, Union

pos_t = Tuple[int, int]
anchor_t = Tuple[str, str]
anchor_pos_t = Tuple[anchor_t, pos_t]

def print_pos(
        pos: Union[
            pos_t,
            anchor_pos_t,
            List[Union[pos_t, anchor_pos_t]]
        ]
) -> None:
    if isinstance(pos, tuple) and isinstance(pos[0], int):
        print('xy =', pos)
    elif isinstance(pos, tuple) and isinstance(pos[0], tuple):
        print('anchor =', pos[0])
        print('xy =', pos[1])
    elif isinstance(pos, list):
        print('[')
        for p in pos:
            print_pos(p)
        print(']')
    else:
        raise ValueError('invalid pos')

print_pos((0, 100))
print_pos((('right', 'bottom'), (0, 100)))
print_pos([
    (0, 100),
    (('right', 'bottom'), (0, 100))
])

Right now, I use isinstance to check for the different possibilities
for the type of pos but I find the code rather clumsy.  Is there a
more convenient/elegant way to do that?  In particular is there a mean
to reuse types I defined (pos_t, anchor_t, anchor_pos_t) in my type check?

A: You can use the typeguard library to check variable types at runtime.
This library is mainly for runtime type validation, rather than conditional type checking, so an extra is_type function needs to be defined to fit your needs.
Extra type casts are also unfortunately necessary to prevent type checker errors.
from typing import Any, List, Tuple, Union, cast

from typeguard import check_type

pos_t = Tuple[int, int]
anchor_t = Tuple[str, str]
anchor_pos_t = Tuple[anchor_t, pos_t]

def is_type(value: Any, expected_type: Any) -> bool:
    """
    Return whether the given value is of the expected type or not.
    """
    try:
        check_type('<blank>', value, expected_type)
        return True
    except TypeError:
        return False

def print_pos(
    pos: Union[pos_t, anchor_pos_t, List[Union[pos_t, anchor_pos_t]]]
) -> None:
    if is_type(pos, pos_t):
        pos = cast(pos_t, pos)
        print('xy =', pos)
    elif is_type(pos, anchor_pos_t):
        pos = cast(anchor_pos_t, pos)
        print('anchor =', pos[0])
        print('xy =', pos[1])
    elif is_type(pos, List[Union[pos_t, anchor_pos_t]]):
        pos = cast(List[Union[pos_t, anchor_pos_t]], pos)
        print('[')
        for p in pos:
            print_pos(p)
        print(']')
    else:
        raise ValueError('invalid pos')

print_pos((0, 100))
print_pos((('right', 'bottom'), (0, 100)))
print_pos([(0, 100), (('right', 'bottom'), (0, 100))])

This isn't the cleanest solution, but it works.
I would recommend using a more object-oriented approach with classes if possible, to eliminate the need for union types.

A: This does not yet work with any current python version, but python 3.10 (planned to be released October 2021) will have structural pattern matching.
This allows something like this, which might be slightly more readable:
from typing import List, Tuple, Union

pos_t = Tuple[int, int]
anchor_t = Tuple[str, str]
anchor_pos_t = Tuple[anchor_t, pos_t]

def print_pos(
        pos: Union[
            pos_t,
            anchor_pos_t,
            List[Union[pos_t, anchor_pos_t]]
        ]
) -> None:
    match pos:
        # need to match this more specific case first, as tuple((x, y)) matches this as well
        case tuple(((a, b), (x, y))):
            print('anchor =', (a, b))
            print('xy =', (x, y))
        case tuple((x, y)):
            print('xy =', (x, y))
        case list(_):
            print('[')
            for p in pos:
                print_pos(p)
            print(']')
        case _:
            raise ValueError('invalid pos')

print_pos((0, 100))
print_pos((('right', 'bottom'), (0, 100)))
print_pos([
    (0, 100),
    (('right', 'bottom'), (0, 100))
])

This already works with the 3.10.0a7 pre-release, although the mypy support is not there yet.
Structural pattern matching is in a sense similar to sequence unpacking like
(a, b), (x, y) = pos

but more powerful.
The three PEPs describing structural pattern matching:

*

*PEP 634 -- Structural Pattern Matching: Specification

*PEP 635 -- Structural Pattern Matching: Motivation and Rationale

*PEP 636 -- Structural Pattern Matching: Tutorial


text:
Q: Cocoa Key event problem I'm trying to build my first cocoa application. done some iPhone developing before. I have a hard time understanding how to layout my project.
i making a Pong game and my current design is to allocate an NSWindowController from my appDelegate. I then use custom view to act as paddles and ball. My problem is that i can't get the window controller to capture key events. Am i thinking wrong here?
My idea is to have a controller class with all the logic, should i subclass another class for that?

A: Input events will be delivered to the views in the responder chain, so you should add all of your event-handling code to the custom view you mentioned, rather than the window controller.


text:
Q: Navigation similar to Gmail Android application
Note: I am using Xamarin - but will accept an answer in Java Android -

I have an android application in which I have similar navigation to the gmail android application.
I have a Left drawer navigation. With following Options

*

*Assets (Like gmail application Inbox fragment) -

When user launches the application they are shown this fragment by default - When a user is on this Activity and presses the back button the Application should close

*Geofences

When user is on this fragment and presses back it should go back to the Assets (Inbox) Fragment

*Notifications

When user is on this fragment and presses back it should go back to the Assets (Inbox) Fragment
This is how I launch the Default Fragment in my Activity
protected override void OnCreate(Bundle savedInstanceState)
{
 // Set the initial fragment i.e. AssetListFragment
 var fragment = new AssetListFragment();
 var ft = SupportFragmentManager.BeginTransaction()
                        .Replace(Resource.Id.content_frame, fragment);

  ft.Commit();

}

And then when an item from the Drawer navigation is clicked I launch the fragment like the following:
    private void NavigationDrawerItemSelected(object sender, NavigationView.NavigationItemSelectedEventArgs e)
    {
        Android.Support.V4.App.Fragment fragment = null;

        switch (e.MenuItem.ItemId)
        {
            case Resource.Id.nav_assets:
                fragment = new AssetListFragment();
                break;

            case Resource.Id.nav_geofences:
                fragment = new GeofenceFragment();
                break;

            case Resource.Id.nav_notifications:
                fragment = new NotificationsFragment();
                break;
        }

        if (fragment != null)
        {
            var fragmentName = fragment.GetType().Name;

            var fragmentPopped = SupportFragmentManager.PopBackStackImmediate(fragmentName, 0);

            if (!fragmentPopped)
            {
                var ft = SupportFragmentManager
                                .BeginTransaction()
                                .AddToBackStack(fragmentName)
                                .Replace(Resource.Id.content_frame, fragment);

                ft.Commit();
            }
        }

        // Close drawer
        _drawerLayout.CloseDrawers();
    }

When the user clicks the back button I have done the following:
    public override void OnBackPressed()
    {
        if (_drawerLayout != null && _drawerLayout.IsDrawerOpen(GravityCompat.Start))
            _drawerLayout.CloseDrawers();
        else
        {
            if (SupportFragmentManager.BackStackEntryCount > 0)
                SupportFragmentManager.PopBackStackImmediate();
            else
                base.OnBackPressed();

        }

    }

What I need to do is always go back to the First Screen (in my case the AssetListFragment) (in gmail android app the Inbox Fragment)
How can I do this? Currently all the fragments loaded from the Navigation Draw are added to the stack, when I click on the Back button it goes to the previous fragment not the first one.

A: You added the fragment to the stack, when you at the second or third fragment and press back button you should pop all the fragments out before the AssetListFragment
Android provide the API PopBackStackImmediate(id,flag) to navigate the target fragment.
In my example the FragmentOne is the first fragment like AssetListFragment :
if (FragmentManager.BackStackEntryCount > 0)
{
    FragmentManager.PopBackStackImmediate(new FragmentOne().Id, PopBackStackFlags.None);
}
else
{
    base.OnBackPressed();
}

Edit
For your requirement in the stack the fragment should be store as 1->2->3->1 and we when we find the current fragment is 1 and click back button should close app:
Android does not provide the API to detect the current fragment we can add a static Arraylist to store the fragments you added.
public static ArrayList myFragments = new ArrayList();
Add every fragment you replaced to the list :
 private void Bt1_Click(object sender, EventArgs e)
        {
            FragmentThree fThree = new FragmentThree();
            FragmentManager fm = FragmentManager;
            FragmentTransaction tx = fm.BeginTransaction();
            //tx.Hide(this);
            //tx.Add(Resource.Id.frameLayout1, fThree, "THREE");
            MainActivity.myFragments.Add(fThree);
            tx.Replace(Resource.Id.frameLayout1, fThree, "THREE");
            tx.AddToBackStack(null);
            tx.Commit();
        }

Check the current fragment if it is the FragmentOne :
Fragment lastFragment = (Fragment)(myFragments[myFragments.Count - 1]);

            if (lastFragment.Tag.Equals("ONE"))
            {
                myFragments.Clear();
                Finish();

            }
            else
            {
                if (FragmentManager.BackStackEntryCount > 0)
                {

                    FragmentManager.PopBackStackImmediate(new FragmentOne().Id, PopBackStackFlags.None);
                    myFragments.RemoveRange(1, myFragments.Count-1);
                }

                else
                {
                    base.OnBackPressed();
                }
            }

As another workaround, when you press back button just replace the current fragment with the AssetListFragment:
   public override void OnBackPressed()
    {
        if (_drawerLayout != null && _drawerLayout.IsDrawerOpen(GravityCompat.Start))
            _drawerLayout.CloseDrawers();
        else if(FragmentManager.BackStackEntryCount > 1)
        {
            Fragment fragment = new AssetListFragment();
            var ft = SupportFragmentManager
                        .BeginTransaction()
                        .AddToBackStack(null)
                        .Replace(Resource.Id.content_frame, fragment);
            ft.Commit();
        }
        else
        {
             base.OnBackPressed();
        }
    }


text:
Q: Changing ui language at runtime I'm trying to change the ui language of my UWP app dynamically.
Everything works fine except for the page containing the language combobox itself.
I have to pick a language from the combobox twice to see the page change to another language, why do i have to do this twice?
private void comboUILanguages_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
        ResourceController.ChangeUILanguage((string)((ComboBox)sender).SelectedItem);

        //for now, use a simple condition to determine wheter the page should be refreshed immediatly
        if (true)
        {
            MainPage.Current.RefreshMenu();
            Reload(currentGroup);
        }
}

private bool Reload(object param = null)
{
        var type = Frame.CurrentSourcePageType;

        try
        {
            return Frame.Navigate(type, param);
        }
        finally
        {
            Frame.BackStack.Remove(Frame.BackStack.Last());
        }
}

My ResourceController:
class ResourceController
{
    private static ResourceLoader resourceLoader = ResourceLoader.GetForViewIndependentUse();

    public static string GetTranslation(string resource)
    {
        return resourceLoader.GetString(resource);
    }

    public static void ChangeUILanguage(string language)
    {
        Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = language;
        Windows.ApplicationModel.Resources.Core.ResourceContext.GetForViewIndependentUse().Reset();
    }

    public static string GetCurrentUILanguage()
    {
        return CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
    }
}


text:
Q: For mailchimp can the Unsubscribe merge tag link to a custom form instead of the MailChimp hosted Unsubscribe form? Im required by law to have a link in all emails that allow an opt-out. It seems that link thats a |UNSUB| merge tag links directly to the MailChimp Hosted Unsubscribe Form. This isn't helpful as I want to be able to update my own external  database if someone unsubscribes. I was wondering if there is a way to host to own unsubscribe form. Or if thats not possible to have the Mailchimp Hosted Unsubscribe Form somehow update my external database.
Thanks./

A: I haven't found a way to customize the *|UNSUB|* tag to point to your own server. But MailChimp has an API, or rather webhooks, that can talk to your server everytime an unsubscribe (or other event occurs). Go to your list, click Settings and choose Webhooks and enter the URL to your server that will be receiving the data that is sent in a POST. Here is an example of what is POST'ed for the unsubscribe event/type:
array (
    'type' => 'unsubscribe',
    'fired_at' => '2016-11-29 17:25:47',
    'data' =>
    array (
        'action' => 'unsub',
        'reason' => 'manual',
        'id' => '1788964578',
        'email' => 'john.doe@sample.com',
        'email_type' => 'html',
        'ip_opt' => '166.136.10.51',
        'web_id' => '178654877',
        'merges' =>
        array (
            'EMAIL' => 'john.doe@sample.com',
            'FNAME' => 'John',
            'LNAME' => 'Doe',
            'INTERESTS' => '',
            'GROUPINGS' =>
            array (
                0 =>
                array (
                    'id' => '84611',
                    'name' => 'Public categories',
                    'groups' => '',
                ),
            ),
        ),
        'list_id' => 'f633681b5d',
    ),
)


text:
Q: stop github project page subpath redirecting to custom subdomain I have a GitHub pages set up with a custom domain.
I have some project pages which I would like to be available at project.domain.com, in addition to being available at domain.com/project.
Setting up the project repository with a CNAME file, and adding a CNAME record to the dns will make project.domain.com work, but redirects domain.com/project to project.domain.com.
Is there a way to have both URLs serve the same project page, without either redirecting to the other?
This question asks the opposite, how to automatically redirect from a subpath to a subdomain, but both options (A records or CNAME records) don't work for me.

A: You cannot have both.
You project repository is served as a folder of :

*

*username.github.io -> username.github.io/projectname

*or domain.com -> domain.com/project, if you add a CNAME for domain.com in username.github.io
If you add a CNAME in a project repository, an automatic redirection is applied in accordance with this CNAME content. In your case project.domain.com.


text:
Q: Setting cookies(where value contains =) in javascript not working i am trying to set a cookie in javascript. Cookies key-value pair are separated by "=". And, Unfortunately my value has a '=' in it. And it messes up with the key/value of the cookie.
document.cookie = "xuser=a=qJUmLNoHmkdfdfdf;Domain=test.com";

The cookie that is created finally is
Key: a
Value: qJUmLNoHmkdfdfdf
I have tried different formats like below using " and '. But didn't help.
document.cookie = "xuser='a=qJUmLNoHmkdfdfdf';Domain=test.com";
document.cookie = 'xuser="a=qJUmLNoHmkdfdfdf";Domain=test.com';

A: Instead of using an actual equal sign in the cookie, use a placeholder, such as the percent-encoding %3F or the HTML entity &61;, or whatever else you like.
Then the placeholder won't mess up the cookie, and you can replace the placeholder back to = whenever you need to use it in your code.


text:
Q: using a non-blocking socket connection in C I'm changing a socket connection in a script to a non-blocking connection. In a tutorial I found the lines:
x=fcntl(s,F_GETFL,0);              // Get socket flags
fcntl(s,F_SETFL,x | O_NONBLOCK);   // Add non-blocking flag

So I added them after I create my socket and before the connect statement. And it's no longer blocking :) but it also doesn't connect. I'm not getting any errors, the connect is just returning -1. If I comment these lines out it connects.
What else do I need to add to get a non-blocking connection to connect?

A: Check return value of connect(2) - you should be getting -1, and EINPROGRESS in errno(3). Then add socket file descriptor to a poll set, and wait on it with select(2) or poll(2).
This way you can have multiple connection attempts going on at the same time (that's how e.g. browsers do it) and be able to have tighter timeouts.

A: connect will probably immediately return a EINPROGRESS error.  Read up on use of select.
Note that you'll probably want to wrap your call to select in the TEMP_FAILURE_RETRY macro.


text:
Q: How do I draw a border on a canvas in Java, by using an object from the Dimension class? For an assignment I needed to draw a border around a 500x600 canvas on 20px from the sides, so I did it manually:
//upper line
myCanvas.drawLine(20, 20, 580, 20);

//bottom line
myCanvas.drawLine(20, 480, 580, 480);

//west line
myCanvas.drawLine(20, 20, 20, 480);

//east line
myCanvas.drawLine(580, 20, 580, 480);

But now I have to it using an object from the Dimension class, so that whenever the canvas size changes, the border changes too. So
myCanvas.drawLine(20, 20, (myCanvas.getHeight() - 20), 20)

But how do I do this? Everytime I get: cannot find symbol - method getHeight()

A: You could simply use a number of Borders (How to use Borders).
Something like...
myCanvas.setBorder(new CompoundBorder(new EmptyBorder(20, 20, 20, 20), new LineBorder(Color.BLACK));

Assuming that "canvas" extends from a JComponent of course...

A: As myCanvas is a custom class which contains a number of swing based objects, you draw using:
myCanvas.drawLine(20, 20, myCanvas.getSize().height - 20, 20);