Group directory challenge

Question: Have a challenging question for you. Have a linux box. Need to create directory where users would be able to create files, but remove/modify only files created by them. Simple enough to have sticky bit set and thats it.
But then we want particular admin user to be able to remove files from this directory and not being root user. How to do that? NFS4_ACLs are possible there. But I'm sure they won't help.
Ideas?
Users:
user1:uploaders
user2:uploaders
admin1:admins <--- should be able to manage files in group dir
sgid on dir makes it possible to protect files from being edited by other users, but nothing stops user from deleting other users' files. Thats the problem
UPDATE 1:
The question was for FS permissions and nfs4_acls just because the users would be working with files over sftp. So that sudo and other scripted ways are not possible. Possible is to use LD_PRELOAD for sftp-server and override the unlink syscall or something like that. So it falls in to openssh and sftp-server.
UPDATE 2:
The users are chrooted to the directory in question by openssh and the directory should be root:root owned for it to work. All the files are put in this directory without any structure (app specific). The admin is actually not the only user to manage uploaded files but rather a group of admin users.
Comment: You mention NFS4_ACLs, is this directory intended to be created in a NFS share?
Comment: @dawud the directory is stored on NFS4 share which is good because it allows me to use NFS4_ACLs which are quite powerful
Comment: Sorry that I haven't been answering there for a long time
Comment: On a linux nfs server nfs4 acls are basically transposed onto posix acls on the local filesystem. For which the setuid bit takes precendence over the posix ACL, using ACL's looks like a non-starter.
Comment: The best way I can think of to acheive this is with a fuse program to perform a custom management layer. If you wanted that it would be for money not points!

Alternatively you can possibly come up with a way by using pubkeys for the 'managers' to be able to login as any allowed user through the 'SSHAuthorizedKeys' command to call a special script. But that might become difficult to manage for many users and admins.
Comment: Yeah, I wanted to keep it as simple as possible. BTW it is easily achievable on solaris zfs which the same nfs4 acls :(
Comment: POSIX acl is a way to go.
Answer: I'd be inclined to solve with with sudo rather than with ACLs. (There's no explicit mention of NFS in the question so I'm going to assume that root_squash isn't an issue.)
Start with your directory having permissions 1777 (sticky plus all read/write) as you suggested.
Create this script with a filename such as /usr/local/bin/rmd. Amend the definition of TARGET so that it is the absolute path to the target directory
#!/bin/bash
#
# Remove files from $TARGET. Some care is taken to avoid escaping from
# the path root
#
########################################################################
#
TARGET='/tmp'

ERROR=
for ITEM in "$@"
do
    LINK=$(readlink -f "$ITEM")
    if test -n "$LINK" && echo "$LINK" | grep -vq "^$TARGET/"
    then
        echo "Suspicious path: $ITEM" >&2
        ERROR=yes
    fi
done
test yes = "$ERROR" && exit 1

exec rm "$@"

Add the following entry to the sudoers file (use visudo to edit this file). Change the admin to be the user with administrative privileges to delete files in the target directory.
admin ALL = NOPASSWD: /usr/local/bin/rmd

Since we know that rmd is in /usr/local/bin it would be possible to re-exec the script if it didn't have sufficient privileges, and so avoid the administrative user having to remember to use sudo, but I've omitted that for now. Let me know if you want this adjustment to the script.
Usage example
$ ls -l /tmp
lrwxrwxrwx 1 roaima roaima 4 Mar 31 00:17 etc -> /etc
-rw-r--r-- 1 roaima roaima 0 Mar 31 00:29 one
lrwxrwxrwx 1 roaima roaima 2 Mar 31 00:20 root -> ..
-rw-r--r-- 1 roaima roaima 0 Mar 31 00:29 two

$ sudo rmd /tmp/etc/hosts /tmp/root/etc/motd /tmp/one
Suspicious path: /tmp/etc/hosts
Suspicious path: /tmp/root/etc/motd

$ ls /tmp
etc  one  root  two

$ sudo rmd /tmp/one /tmp/root
$ ls /tmp
etc  two

Comment: This can't be solution because it won't work over SFTP while regular FS permission would. Its more like a workaround which is fine in some cases but not in this case
Comment: @Dmytro Why won't the `sudo rmd` approach work in the general case? Subsequent to your updates, ignore the directory permissions I originally suggested and reapply the proposed solution. I still think it has merit and I will quite happily work on its detail, but I need to understand why you think it's a non-starter, please.
Comment: How do ine use sudo script from sftp/scp client?
Comment: @Dmytro, your admin users also access this share via sftp? Where in your Question does it say that?
Comment: all users are accessing the server using sftp/scp
Comment: @Dmytro your question definitely didn't make it clear that "users" also includes the "admins". You use "users" as a term that is different to "admins".
Answer: Bindfs is one possible solution. I named my power admin user nradmin and here is the example:
mkdir /uploads
chmod 1777 /uploads

mkdir /home/nradmin/manage-uploads
bindfs -u nradmin -p ud+rwx /uploads /home/nradmin/manage-uploads

Every file and directory in the mounted target is owned by nradmin. The -p ud+rwx makes every directory to be with permissions "rwx" for the directory owner. Since nradmin is the owner of all directories and it has full owner permissions in them, it can successfully delete any file in them, even recursively.

The alternative approach would be that you code a limited chroot() implementation of /bin/rm and execute it as root. A chroot() can be escaped by a process ran by root but only if you give this process the freedom to execute whatever it wants. A simple C binary which first makes chdir() & chroot() to the /uploads directory, and then only calls unlink() or rmdir() should be secure. But this requires lots of coding like recursive delete of directories, a command-line option like -f to ignore non-existing files, etc.
Comment: I need a group of users to be able to remove files. Not only one adnin
Comment: If you don't have dozens of admin users, you can do a `bindfs` mount in each of their home directory and manage it via `sftp`.
Comment: admin users are chrooted as well, but one layer higher than uploaders. All of this falls within DocumentRoot of webserver. They are more like a media managers who manage not only these files.
Answer: One simple solution appears to be this. Consider the administrative user to be admin, and that our special directory is to be /tmp/special.
mkdir /tmp/special
chmod 1777 /tmp/special
chown admin:admin /tmp/special
ls -ld /tmp/special
drwxrwxrwt 2 admin admin 4096 Apr  3 21:34 /tmp/special

Any user can create/edit/delete their own files in /tmp/special. The user admin can delete any file (albeit with warnings from rm).
NB If a user creates a directory in /tmp/special, the administrative user cannot remove it. That may be a showstopper for this solution, but as your question only mentioned files and not directories I felt it was worth offering.
Comment: Your answer could have been a solution actually but I'm stick with root:root on directory because this dir is used as chroot for sftp user thus has to have root:root ownership. There are only files to be uploaded, but....
Answer: The full scope of this problem is unclear as we do not know what's the usecase. However using SELinux labels one get achieve what you ask for. SELinux gives you some fine-grained controls over who does what and where. If number of users is "limited" and "known" - having specific contexts/labels associated with each one of them is not a big issue, then it is a matter of writing a bit of policy to code-in your requirements.
Comment: It is to be done on Ubuntu box mounting remote NFS4 FS. On the back is OpenIndiana server.
Answer: Hmm... how about chrooting to /special_folders_root/special_folder/./ to avoid problems with root-owned chrooted directories? See vsftpd's documentation (for example) for explanation about extraneous dot in the path.
Unsure, if following will be useful, but:
We have samba share with subdirs. Network MFUs putting the scanned documents inside specific subdirs (MFU01 --> /share/001/, MFU15--> /share/015/ etc).
Users (from windows) may alter or remove the files in any of these subdirs, but can not remove the subdirs. I made that using windows-style ACLs, but I know nothing about NFS ACLs
NB! Not for bounty, but for assistance.
Comment: there is no FTP at all. it is sftp.
Comment: The difference is that using sftp-server user can only be chrooted in root owned directory
Comment: It's OK. Root can be owner, but the trick with extra dot allows non-anonymous user to do what he need. This dot designates chroot point, and if there's something after it, like blablabla/./abyrwalg, then user's root will be root-owned blablabla, but his starting position will be abyrwalg directory, which is not required to be root-owned.
Comment: did you try this with sftp-server?
Answer: How about this approach:
Keep original uploaded files in a separate directory, per user.  This covers governance and delete permissions.
In $share, everything is a link to the original files, and owner/admin ACLs are in place.
In the end, every item in $share is a link back.  Anything that isn't a link gets moved to the (uploader) owner's folder.
Comment: See update2:  All the files are put in this directory without any structure (app specific).
Comment: What user does is only upload file and thats all.

Group directory challenge


What is $UU^*$ if $U$ is a linear isometry?

Question: Let $U: \mathbb{R}^n \rightarrow \mathbb{R}^{d}$ be a linear isometry and $d>n$,does the matrix $UU^*$ have any particular structure then? For example if $d=n$ then the result will be the identity matrix, but this cannot be the answer now, due to rank violations. What can I hope for? I am pretty sure that it is a matrix of rank $n$. Can we say more?
I suspect that it is the projection onto $ran(U^*)$ but I am not sure.
Answer: We can just check whether $UU^*$ is a projection or not.
We have $(UU^*)^* = (U^*)^*U^* =U U^*$ and $(UU^*)^2 = UU^*UU^*=U1U^*=UU^*$.
So $UU^*$ is a projection.
Furthermore, for $x \in U(\mathbb{R}^n)$ we have $x=Uy$ and thus $UU^*x=UU^*Uy=Uy =x$, thus $U(\mathbb{R}^n)$ stays invariant under $UU^*$.
For $x \perp U(\mathbb{R}^n)$ we have for all $y \in \mathbb{R}^n$ that $0 = \langle Uy , x \rangle = \langle y , U^*x \rangle$, which is only possible if $U^*x = 0$, and thus $UU^*x=0$.
So $UU^*$ is the projection onto $U(\mathbb{R}^n)$.
Comment: I would even say [*orthogonal* projection](https://en.wikipedia.org/wiki/Projection_(linear_algebra)#Orthogonal_projections) as it is self-adjoint.


como filtrar valores repetidos no php o resultado de uma busca no banco de dados

Question: Ola estou criando um sistema que me retorna do banco de dados varias datas, mas gostaria de apenas uma de cada sem as repetições, eu ja tentei com array_unique, mas sem sucesso, acho que deve ser pelo fato de minha pesquisa retornar em associação OBJ, se alguem puder me dar uma sugestão eu ficaria agradecido.
$sql_historico = "SELECT * FROM historico WHERE id_condominio = " .$id_condominio;
       $historico = $PDO->prepare( $sql_historico);
<code>   $historico->execute();
   if($historico->rowCount()>0){
    while($valor_historico = $historico->fetch(PDO::FETCH_OBJ)){
     $historico_data = $valor_historico->data;
</code>
}
}
Comment: distinct não resolveria?
Answer: Gostaria de informa que consegui uma solução mais simples, eu utilizei um recurso do SQL que filtra e agrupa o resultado eliminado valores repetidos (GROUP BY +nome do campo da tabela que se deseja eliminar valores iguais.
Comment: Um `SELECT DISTINCT` também funciona: https://www.w3schools.com/sql/sql_distinct.asp


How does Assembly.LoadFrom resolve unmanaged dependencies?

Question: I'm confused by the behavior of Assembly.LoadFrom. In my application I call Assembly.LoadFrom to a .NET .exe and start it using EntryPoint.Invoke (this odd approach is useful for building a launcher app on non-Windows platforms).
I had assumed that since the assemblyFile was in a different folder, that it would fail to find some managed .dll dependencies that are located in the same folder as it. But it worked; it didn't fail...
It would appear that when I called Assembly.LoadFrom(assemblyFile), it checked the folder containing assemblyFile for managed dependencies of assemblyFile. I didn't expect this. What would happen if that assembly had unmanaged dependencies (such as a DllImport), would it still search that same directory? And is this behavior framework specific?
Comment: Nothing strange and behavior is same in Mono. For unamanaged dependencies...normal rules of Platform apply (see LoadLibrary() for Windows). Honestly I'm not sure but I think this is Platform specific so with Mono, let's say, on Linux normal Linux rules will be applied for search.
Comment: @Adriano But the JIT lazily resolves the `DllImport`. When `DllImport("MySweetLibrary.dylib")` is finally resolved, will it know it came from `assemblyFile` in a far off directory, and search that directory? My guess is that it won't.
Answer: The Assembly has nothing to do with loading unmanagged libraries. What does the loading for unmanaged libraries is the DllImport call which is lazy (does not load till the first call).
DllImport in turn (in .NET, I don't know what Mono does on other platforms) calls LoadLibary on windows. LoadLibary has a known set of rules for how it resolves it's dependencies:

If a DLL with the same module name is already loaded in memory, the system uses the loaded DLL, no matter which directory it is in. The system does not search for the DLL.
If the DLL is on the list of known DLLs for the version of Windows on which the application is running, the system uses its copy of the known DLL (and the known DLL's dependent DLLs, if any). The system does not search for the DLL. For a list of known DLLs on the current system, see the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs.

If those two points are not met and SafeDllSearchMode is enabled (it is by default for for XP SP2 and newer) it uses the following order

The directory from which the application loaded.
The system directory. Use the GetSystemDirectory function to get the path of this directory.
The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The current directory.
The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.

So to answer your question, no the directory your managed assembly is located in is not searched when looking for unmanaged assemblies, only the directory of the application that loaded your managed assembly.
However all hope is not lost, you can call SetDLLDirectory and add the folder of your managed assembly and it will include it in the search when looking for the unmanaged DLL, it will change the search order to

The directory from which the application loaded.
The directory specified by the lpPathName parameter (in the SetDLLDirectory call).
The system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is System32.
The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The directories that are listed in the PATH environment variable.

If you need to add more than one folder for searching see the MSDN for documenation on AddDllDirectory for the steps required to allow for multiple search directories.
Answer: None of the .NET specific configuration affects the way unmanaged DLLs are located.  Normal operating system search rules are in effect, regardless of how the CLR finds managed assemblies.  The underlying OS call on Windows is LoadLibrary(), a winapi function that has no support for altering search rules itself.  You can specify a full path name to avoid searching but that's almost never practical in pinvoke.
If this is a problem then you'll have to write explicit code to help the OS locate the file.  Common techniques are pinvoking SetDllDirectory(), altering the PATH environment variable with Environment.SetEnvironmentVariable() and changing the default directory by assigning Environment.CurrentDirectory


Solo Cello Composition: Double Stops Question

Question: Can the G or D strings be muted by Cellist so that a double stop can be played on the G and A, or C and D strings? Would greatly appreciate a response.
Answer: No, this doesn't work, at least not for sustained notes. There's no way to "bridge over" the D string when bowing the G and A string; in fact the only way to bow both G and A string simultaneously is to put a lot of pressure on the D-string so the bridge arcing is "surpressed". If you bow a muted D-string this way, it creates a very ugly scraping noise.
What is possible is to arpeggiate a chord from the G to the A-string, immediately lifting the bow, but mute the D string. This works much the same way as on guitar except the bow is used for "plucking" the strings. The muted D will still cause a bit of a rasp, but it's so short that it may be musically acceptable.
For properly doing wide double-stops, you should make sure they are on neighbouring strings. If the lower note is on an empty string, this is no problem. Using thumb position, it is also possible to play any octaves or even ninths on neighbouring strings, but it can be tricky to get the intonation right.
Alternatively, find a note that can be played on the D-string and add it to the chord. Triple stops or even four-note chords are found all across the literature. Again it's usually understood that not all the notes are sustained – often, only the top two notes are held. For triple stops it is actually possible to bow all three strings at the same time, but the required pressure still makes it sound pretty violent, like in this example from the Henze Cello solo Serenade:
<code>X:1
L:1/16
M:
K:
T:V
Q: "Vivace"
%%score B
V:B            clef=bass
% 1
[V:B]  ._B,,.F,.B,.G,.^f,2 ._B,,.F,.B,.G,.^f,2 | ._B,,.F,.B,.G,.^f,2 | .^c2.D2.A,2 _A,,6 | .[E,C_E]2.[E,C_E]2.[E,C_E]2 .[E,C_E]2.[E,C_E]2.[E,C_E]2
</code>
Comment: Thank you for your answer it  was  and is extremely helpful, S


Hyperledger fabric Endorsement policy in fabric nodesdk

Question: I have implemented fabric sdk to install and instantiate the chaincode. Everything is working fine, but not able to figure out the correct to implement endorsement in fabric nodesdk
Here is the endorsement policy which i have used while using command:
peer chaincode ${CHAINCODE_ACTION} -o orderer.google.com:7050 \
    --tls --cafile ${ORDERER_CA} -C $CHANNEL_NAME \
    -n ${CHAINCODE_NAME} -l ${LANG} -v "$CHAINCODE_VERSION" \
    -c '{"Args":[]}' \
    -P "AND (OR('Org1MSP.peer', 'Org1MSP.client','Org1MSP.member','Org1MSP.admin'),
    OR ('Org2MSP.peer', 'Org2MSP.client', 'Org2MSP.member', 'Org2MSP.admin'))"

If I want to implement the same in nodesdk, below is the reference I got it from balance transfer example:
const request = {
      targets: [peer],
      chaincodeId: 'cc1',
      chaincodeType: 'java',
      chaincodeVersion: '7.0',
      txId: tx_id,

      // Use this to demonstrate the following policy:
      // The policy can be fulfilled when members from both orgs signed.
      'endorsement-policy': {
        identities: [
          {role: {name: 'member', mspId: 'Org1MSP'}},
          {role: {name: 'member', mspId: 'Org2MSP'}}
        ],
        policy: {'2-of': [{'signed-by': 0}, {'signed-by': 1}]}
      }
    };

I understand that 2-of in nothing but AND condition between the orgs. signed by 0 and 1 are the indexes of identities. But how can we add OR condition with in Org member, client, admin, peer?
I dont find any documentation to dig more into this. Any help will be much appreciated.
Answer: Your understanding of the endorsement-policy in node-sdk is absolutely correct. A "signaturePolicy" has the following object structure.
type -- SIGNATURE
rule
    Type -- n_out_of
    n_out_of
        N -- {int}
        rules -- {array}
            Type -- signed_by
            signed_by -- {int}
    identities -- {array}
        principal_classification -- {int}
        msp_identifier -- {string}
        Role -- MEMBER | ADMIN

You can read more about it here. You can also refer to examples in the section ChaincodeInstantiateUpgradeRequest.
Now, coming onto the question that you asked which is, how can we add OR condition within Org member, client, admin, peer. Check the below example, which is originally from the node SDK documentation.
Endorsement policy: "Signed by admin of the ordererOrg and any member from one of the peer organizations"
{
  identities: [
    { role: { name: "member", mspId: "peerOrg1" }},
    { role: { name: "member", mspId: "peerOrg2" }},
    { role: { name: "admin", mspId: "ordererOrg" }}
  ],
  policy: {
    "2-of": [
      { "signed-by": 2},
      { "1-of": [{ "signed-by": 0 }, { "signed-by": 1 }]}
    ]
  }
}

As you can see the only identities can be either admin or member that you can specify in your endorsement-policies. A member here can be any member apart from the admin. It can be a peer, client, user. If you want it to be signed by an admin, you'll have to specify explicitly in role object with value admin for the property name.
For your case, I think the following structure will be apt.
{
  identities: [
    { role: { name: "member", mspId: "peerOrg1" }},
    { role: { name: "admin", mspId: "peerOrg1" }},
    { role: { name: "member", mspId: "peerOrg2" }},
    { role: { name: "admin", mspId: "peerOrg2" }}
  ],
  policy: {
    "2-of": [
      { "1-of": [{ "signed-by": 0 }, { "signed-by": 1 }]}
      { "1-of": [{ "signed-by": 2 }, { "signed-by": 3 }]}
    ]
  }
}

Sadly, I couldn't find more examples of endorsement-policies in node-sdk but I think above examples would do the job in explaining its working.
Also, I think this will help you in a better understanding of what members and admins are in an endorsement policy.


How do I set a custom input format for a field?

Question: After using Drupal 7 for years, I am now handed a Drupal 8 site to do some editing. I have created a custom input format (Plain HTML), and I want to print this field with this input format in a custom template. How can I achieve this?
With {{ content.field_mapka_markery }}, it prints plain text. There is no choice to select my newly created input format in the Manage display settings. Why is that? In Drupal 7 there is always a new formatter,  but not so in Drupal 8.
I also tried {{ content.field_mapka_markery|raw }} or .value. |raw doesn't  work at all, and .value does the same as without it.
Answer: Managed to create a new field with "Text - Formatted - Long" as default, which allowed me to set up my custom text format. Why is that not possible for plain text field I am not sure.
Answer: The plain text format filters the text before storing, as far as I know. You need to store it as a formatted string. Then you can apply any filters you like.
Comment: No, input formats are used for rendering the field, not to alter the field value before storing it in the database.
Comment: It's not different from what done for the body field of nodes.


Integration of first kind zero order bessel function J(x)

Question: What is the integration of first kind zero order Bessel function  $J(kx)$, where
$k$ is constant and the
limits of $x$ are from $0$ to $a$.
i.e., $$\int_0^{a} J_0(kx) dx = ?$$
Answer: If you look here, you wil find that
$$\int J_0(t)\,dt =\frac{\pi  t}{2}  \pmb{H}_0(t) J_1(t)+\frac{t}{2} (2 -\pi  \pmb{H}_1(t)) J_0(t)$$ where appears the Struve function.
This makes
$$\int_0^a J_0(kx)\,dx =\frac{a}{2}  (\pi  \pmb{H}_0(a k) J_1(a k)+(2-\pi  \pmb{H}_1(a k)) J_0(a k))$$
Comment: Do you know how to obtain this relation?
Comment: I wish there was a derivation for this formula lol
Answer: Honestly speaking, for the limit $0$ to $a$, I have no idea how to solve, but if it is $0 $ to $\infty$, then you can follow this way $:$
We have $$L\{J_0(x):p\}=\frac{1}{\sqrt{1+p^2}} \qquad \text{and} \qquad L\{J_0(kx)\}=\frac{1}{\sqrt{k^2+p^2}}. . . . . (1)$$ ( from Laplace transformation and using the scaling property )
By the definition of Laplace transformation, $$L\{J_0(x):p\}=\int_0^{\infty} J_0(x) e^{-px} dx$$
So from $(1)$, $$\int_0^{\infty} J_0(kx) e^{-px} dx=\frac{1}{\sqrt{k^2+p^2}}$$
Putting $p=0$ we have, $$\int_0^{\infty} J_0(kx)  dx=\frac{1}{\sqrt{k^2+0}}=\frac{1}{k}$$


Usando Codeigniter dentro do Wordpress

Question: Estou trabalhando em um blog no qual dentro de uma página específica ele tem um iframe que aponta para dentro do próprio servidor, chamando uma pasta que contém o CodeIgniter rodando.
Até alguns dias tudo funcionava, isso no servidor antigo.
Tive que trocar de servidor e no servidor atual ele não funciona.
A única página que ele abre é a página configurada no codeigniter para ser a inicial, quando necessito acessar um controller recebo um erro 404.
O Wordpress tenta acessar uma pasta, e realmente essa pasta não existe, por exemplo eu informo a seguinte url:
servidor.com.br/codeigniter/controller/action/
Ao invés de entrar no controller e procurar a ação ele procura por pastas e obviamente estas pastas não existe, eu criei pastas com esses caminhos e ele conseguiu a index que coloquei dentro da pasta "action", mas isso não é o que necessito. Eu preciso que ele se comporte como um framework.
Eu preciso de uma forma de que quando eu apontar para servidor.com.br/codeigniter/ ele entenda que não é mais para se comportar como se fosse do blog, e começar a se comportar como um framework.
Eu não entendo nada de .htaccess é um dos meus piores pontos como programador, tentei boa parte do dia arrumar uma solução com o htaccess, porém, como podem ver não tive nenhum sucesso, não tenho certeza se a maneira correta de resolver esse problema seria com htaccess, mas foi a única possível saída que encontrei.
Segue htaccess do wordpress:
\# BEGIN WordPress

< IfModule mod_rewrite.c>

RewriteEngine On

RewriteBase /

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /index.php [L]

< /IfModule>

\# END WordPress

E também htaccess do codeigniter
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /index.php?$1 [L]

Se eu entrar no codeigniter direto por um subdomínio o programa roda perfeitamente, porém, eu não posso acessar o iframe com um subdomínio, pois preciso recuperar dados/variáveis de dentro do iframe com jQuery/Ajax, se eu utilizar um subdomínio isso não é possível, necessito de uma forma que faça o blog entender que quando for servidor.com.br/codeigniter ele comece a utilizar o htaccess do codeigniter, ou então, ele entre nos controllers ao invez de procurar por pastas, (creio que essa seja a solução.)
Answer: Consegui resolver meu problema, precisei descobrir algumas novas funções do .htaccess que eu não conhecia, o problema é que estou com muitas dúvidas em mente e não consigo matar as dúvidas no Google, fazer o que...
Segue a minha resolução, talvez ajude alguém.
O .htaccess do framework ficou dessa forma:
Options +SymLinksIfOwnerMatch
RewriteEngine on

RewriteBase /online/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?/$1 [L]

Precisei adicionar o RewriteBase para ele redirecionar a pasta raiz do framework.
Aparentemente no RewriteRule eu passei o index do framework e os parametros de controller/action.
A primeira linha não sei para que serve.

Usando Codeigniter dentro do Wordpress


Proving a sheaf is not locally free

Question: Let $X$ be an affine variety defined by $xy=z^2$ in $\mathbb{A}^3$ and $D,E$ be Weil divisors of $X$ defined by $x,z=0$ and $y,z=0$ respectively.
I want to prove that the sheaf $\mathcal{O}_X(D)$ is not locally free of rank 1.
Let $U=X-E$. If $\mathcal{O}_X(D)$ is locally free of rank 1, then there is a generator $h$ of $\Gamma(U, \mathcal{O}_X(D))$. Since $\frac{1}{x}, \frac{1}{z} \in \Gamma(U, \mathcal{O}_X(D))$, I tried to show that $h$ cannot generate both $\frac{1}{x}, \frac{1}{z}$ but I've got stuck here. Can anyone help me how to proceed?
Answer: Consider $D = \{x = z = 0\}$. It is not hard to find a locally free resolution
$$
\mathcal{O}_X^{\oplus 2}
\stackrel{\left(\begin{smallmatrix}z & -y\\-x & z\end{smallmatrix}\right)}\to
\mathcal{O}_X^{\oplus 2} \stackrel{(x,z)}\to
\mathcal{O}_X(-D) \to 0.
$$
Tensoring it by $\mathcal{O}_P$, where $P$ is the vertex of $X$, one obtains
$$
\mathcal{O}_P^{\oplus 2}
\stackrel{\left(\begin{smallmatrix}0 & 0\\0 & 0\end{smallmatrix}\right)}\to
\mathcal{O}_P^{\oplus 2} \to
\mathcal{O}_X(-D) \otimes \mathcal{O}_P \to 0,
$$
which implies that
$$
\mathcal{O}_X(-D) \otimes \mathcal{O}_P \cong \mathcal{O}_P^{\oplus 2},
$$
hence $\mathcal{O}_X(-D)$ cannot be locally free of rank 1. On the other hand, $2D$ is a Cartier divisor, so if $\mathcal{O}_X(D)$ would be locally free, the same would be true for $\mathcal{O}_X(-D)$.

Proving a sheaf is not locally free


Remove labels in printer friendly version of books

Question: Is there any way to remove labels or apply a CSS file to the printer-friendly version of books?
Answer: Here is how I approached the problem:
Copied
<code>/modules/book/book-node-export-html.tpl.php
/modules/book/book-export-html.tpl.php
</code>
to my theme directory and modified the $contents variable via str_replace.
This works fine as a temporary fix, but I guess performance-wise this is not the best solution, would would be still nice to find a way to apply CSS.


What happened to the arguments part of views 3?

Question: Am I just blind?
(I'm trying to pass the current page's nid into a block where I'm theming a view and want to filter the view by the nid.)
Answer: They have been renamed "Contextual filters," and they have been moved in the third column that is collapsed by default.

In Drupal 6 (Views 6.x-3.x-dev) the URL arguments are still called "Arguments."
Comment: @João was first and correct, so I gave him the check, but bonus point for the screenshot!
Answer: Arguments are now called Contextual Filters.


What are proper classes good for in mathematics (Applications)

Question: Pardon me if the following question is somewhat naive or stupid. I am not an expert in formal logic!
I have a question about the notion of "proper classes" coming from the realm of formal logic, see here: https://en.wikipedia.org/wiki/Class_(set_theory)
It is said that each set is also a class, but not any class need to be a set. Such classes are then called "proper classes". I am wondering if there are any applications of this notion in other areas of mathematics. For example, is there an interesting mathematical object (e.g. in Analysis, Algebra,...) which is a "proper class"? Or is it enough for other areas of mathematics to use the notion of sets given by the Zermelo–Fraenkel set theory? If so, why is it important at all to introduce the notion of "proper classes" in logic?
Best wishes
Comment: Why introduce the notion? Because proper classes are mathematical objects, and one goal of mathematical logic is to better understand mathematical objects.
Answer: Let's start with the beginning. Set theory.
Russell's paradox—and many other paradoxes of naive set theory—show us that there are collections of mathematical objects that we can define, but they do not form sets.
This is a bit of a thorn in the side of set theory, since the whole point of sets is to have a mathematical object which is itself a collection of mathematical objects (or rather, at least model this idea). So in an ideal world, every collection of mathematical objects that we can define would be a set. But alas, we do not live in a perfect world.
Proper classes solve this problem by allowing us to have a notion of collection which is formal, but does not correspond to a set. The collection of all sets, the collection of all partial orders, etc. are all collections which we can describe, but do not form sets.
In modern set theory this is used in full power when talking about the ordinals, inner models, ultrapowers of the universe, and many many other collections of sets which themselves make a proper class.

So, what happens outside of set theory? Well. The basic theorems of model theory show us that if there is one infinite group, then there is one of every cardinality, and therefore there is a proper class of groups none of which is isomorphic to any other; and there is a proper class of topological spaces, no two of them are homoemorphic; and so on and so forth.
The collection of most things satisfying a certain property which is not bound to a specific set will usually end up being a proper class. And while sometimes we can sort of remedy that (e.g. the collection of all singletons is a proper class, but usually it is enough to talk about $\{\varnothing\}$), in many cases we really do need to talk about a proper class of objects.
Many people would argue that this is a hindrance rather than an important notion. This makes category theory cumbersome. This makes things like "define the algebraic closure of a field" cumbersome. This causes a lot of problems when you want to be more formal, correct, and maintain clarity without getting into set theoretic issues (which is arguably irrelevant in an algebra course).
But, I argue that the fact that proper classes are there, stuck like a bone in the throat of everyone, is a good thing. If utilized properly, they promote thinking with care, they promote attention to details, and once you understand how proper classes actually work, and what does it mean for you as a mathematician, you can see that this is mostly a large shadow cast by a small mouse.

So where can you find proper classes to be prominent?
Category theory. That's an easy one. Most "obvious categories" are in fact proper classes, since the collection of objects is a proper class, and sometimes the morphisms between objects make a proper class as well. So the categories $\bf Set, Grp, Ab, Ring, Mod_{\it R}, Vec, Top$ and many others are in fact a pair of proper classes: a class of objects, and a class of morphisms between these objects.


gcc49 on Fedora 27: /usr/bin/ld: cannot find -lgcc_s

Question: I am using the davidva/gcc49 copr, on Fedora 27.
When I try to compile after running source /usr/bin/gcc49 as the copr webpage describes, I get this error:
/usr/bin/ld: cannot find -lgcc_s

After learning about how the flag -l works for gcc, I learned it is looking for library gcc_s. I found it in /opt/gcc-4.9.3/lib64/gcc/x86_64-fedoraunited-linux-gnu/lib64, which sounds like the right spot for it to be. Why is it not linking? Do I need to add a directory to a library path? If it's LDFLAGS, it's already there because of the file I sourced:
export LDFLAGS="-L/opt/gcc-$gver/$lib/gcc/$gcc_target_platform/$lib/"

What do I need to do to get gcc 4.9 on Fedora 27 to find its library file which is clearly in the LDFLAGS directory?
Answer: The problem is that the libgcc_s.so file is in the wrong directory! Just symlink to it in the 4.9.3 directory:
pushd /opt/gcc-4.9.3/lib64/gcc/x86_64-fedoraunited-linux-gnu/4.9.3
sudo cp -p ../lib64/libgcc_s.so.1 .
sudo ln -s libgcc_s.so.1 libgcc_s.so
popd

I guess the /opt/gcc-4.9.3/lib64/gcc/x86_64-fedoraunited-linux-gnu/lib64 directory was supposed to be included in any LDFLAGS parameter, and that might be a weakness of the build process I was using and not the gcc 4.9 package.
Putting this file and appropriately-named symlink in the 4.9.3 directory allows my build process to complete successfully.
Reference: https://bgstack15.wordpress.com/2018/02/01/gcc-4-9-for-fedora-27/


nmb: unrecognized service when installing Samba

Question: I've followed these steps to install Samba on my CentOS package. However, when I try to run chkconfig --level 345 nmb on, I get a nmb: unrecognized service error.
I tried service nmb status and service nmb restart with the same error message returning.
There doesn't seem to be anything regarding this, what's wrong? Why do I not have nmb installed, and how can I get it installed?
Comment: Did the yum install samba complete correctly ?
Comment: @Iain I unistalled Samba and now re-installed. Same error, no nmb, and it looks like Samba installed correctly. Here's the full text of the install: http://pastebin.com/raw.php?i=M08SJSZ4
Answer: On a CentOS 5.8 system I have (like the one you are using), it appears that the smb and nmb services are managed together through the /etc/init.d/smb file
service smb start
Starting SMB services:                                     [  OK  ]
Starting NMB services:                                     [  OK  ]

Whereas on a CentOS 6.3 system they are managed as separate services. So your
chkconfig --level 345 smb

will also have configured nmb.
I don't know why the page you reference says to use the separate services. The RHEL 5 deployment guide(21.2.1) says nmb is controlled by smb whereas the the RHEL 6 deployment guide (184.108.40.206) says they are separate services.


Find k , if k = $\lim \limits_{n \to \infty} n[(n^3+3n^2+2n+1)^{1/3}+(n^2-2n+3)^{1/2}-2n]$

Question: Find k , if k = $\lim \limits_{n \to \infty} n[(n^3+3n^2+2n+1)^{1/3}+(n^2-2n+3)^{1/2}-2n]$
I converted it to $\lim \limits_{t \to 0}$ and tried using L'Hospital's rule and I got it after differentiating twice. It looks pretty bad. Please give an elegant solution. Thank you.
Answer: Setting $1/n=h,$
 $F=\lim \limits_{n \to \infty} n[(n^3+3n^2+2n+1)^{1/3}+(n^2-2n+3)^{1/2}-2n]$
$=\lim_{h\to0^+}\dfrac{(1+3h+2h^2+h^3)^{1/3}+(1-2h+3h^2)^{1/2}-2}{h^2}$
Using Binomial series,
$(1+3h+2h^2+h^3)^{1/3}=\{1+h(3+2h+h^2)\}^{1/3}$
$=1+1/3h(3+2h+h^2)+1/3(1/3-1)\dfrac{\{h(3+2h+h^2)\}^2}{2!}+O(h^3)$
$=1+h+h^2\left(\dfrac23-\dfrac29\cdot\dfrac92\right)+O(h^3)=1+h-h^2/3+O(h^3)$
$(1-2h+3h^2)^{1/2}=\{1+h(3h-2)\}^{1/2}$
$=1+1/2h(3h-2)+1/2(1/2-1)\dfrac{\{h(3h-2)\}^2}{2!}+O(h^3)$
$=1-h+h^2\left(\dfrac32-\dfrac14\cdot\dfrac92\right)+O(h^3)$
$=1-h-3h^2/8+O(h^3)$
Can you take it from here?
Answer: Observe that $(n+1)^3=n^3+3n^2+3n+1$, $(n-1)^2=n^2-2n+1$, $2n=(n+1)+(n-1)$
$$\lim \limits_{n \to \infty}n((n+1)^3-n)^{1/3}-(n+1))\\= \lim \limits_{n \to \infty}\frac{-n^2}{((n+1)^3-n)^{2/3}+(n+1)((n+1)^3-n)^{1/3}+(n+1)^2}\\=\frac{-1}{3}$$
$$\lim \limits_{n \to \infty}n((n-1)^2+2)^{1/2}-(n-1))=\lim \limits_{n \to \infty}\frac{2n}{((n-1)^2+2)^{1/2}+(n-1)}=1$$
so $k=1-\frac{1}{3}=\frac{2}{3}$
Comment: $a^3-b^3=(a-b)(a^2+ab+b^2)$, $a^2-b^2=(a-b)(a+b)$
Answer: Start with $$\lim \limits_{n \to \infty} n[(n^3+3n^2+2n+1)^{1/3}+(n^2-2n+3)^{1/2}-2n] = \lim \limits_{n \to \infty} n^2\left(\left(1+\frac 3n+\frac 2{n^2}+\frac 1{n^3}\right)^{1/3}+\left(1- \frac 2n+ \frac 3{n^2}\right)^{1/2}-2\right), $$
then use the expansion $(1+x)^a = 1 + a x + \frac{a(a-1)}2 x^2 + o(x^2)$ to expand the two remaining terms
Comment: Please explain it clearly. What should I take as x ?
Comment: In the first bracket $\frac 3n + \frac 2{n^2} + \frac 1{n^3}$ in the second $-\frac 2n + \frac 3{n^2}$
Comment: The answer comes out to be $2/3 + 3/2$ which is $13/6$ which is wrong.


How to highlight active teaser in Views?

Question: Using Views and Panels, I have an unordered list of node teasers that appears on every page. When viewing a node, I would like to highlight that node's teaser in the list.
Class .active gets applied to the teaser link, but I'd like to apply it to the whole list item. Is this possible?
Answer: The following does the work for me:
<code>function YOUR_THEME_preprocess_views_view_unformatted(&$vars) {

  if (arg(0) != 'node') return; // no active node

  $index = 0;
  foreach($vars['view']->result as $node) {
    if (arg(1) == $node->nid) {
      $vars['classes_array'][$index] .= ' active';
    }
    $index++;
  }

}
</code>
Comment: is that method only works for unformatted style? because I am getting error Notice: Undefined offset: 2 for table style (where 2 is the $index value) but working fine with unformatted style.
Comment: ok got it. for YOUR_THEME_preprocess_views_view_table $vars['row_classes'][$index][] should be used instead of $vars['classes_array'][$index]


Topology in a proper class

Question: Topological spaces are usually modelled over sets. What happens if I try to topologize a proper class? Say, the class of all maps from naturals to cardinals or similar. Suppose I specify a topology on such a class by defining convergence for a net. What usual properties or facts may I lose? I would like to go on to take quotient spaces and continuous parametric families of elements etc. What could potentially go wrong? Thank you.
Comment: Example from [Wikipedia](https://en.wikipedia.org/wiki/Order_topology#Topology_and_ordinals): "Note that if we are willing to accept a proper class as a topological space, then the class of all ordinals is also a topological space for the order topology."
Answer: I'll just put here some ideas.
• Topology is usually defined by means of open sets. We should decide if we consider only subsets of the proper class or subclasses as well. More generally, often we shall decide which objects we allow to be large and which have to be small.
• Look at the category theory. A category is actually an ordinary structure like group. It is a partial monoid. But it is used in the setting when you allow large objects. So there lie many examples of this problem of dealing with size.
Comment: Good remarks, especially the first one. Thanks.

Topology in a proper class


What Does This Pushing Technique Do?

Question: I have watched a number of guitarists do a certain technique before where they push on the upper body of the guitar near where they strum.  I have seen it done on both on acoustic and on electric guitars, but have yet to figure out exactly what they are doing.  I have attached a video clip (first two seconds) where this is being done.  Can anyone tell me what this technique is called, and what it accomplishes outside of just bending the strings or using the whammy bar [if anything]?
I looked and could not find a similar question, but I am not a guitar player, so I might be missing the correct terminology.
Comment: Achieves no more than using the whammy bar. Except weakens the guitar possibly. Not having a whammy bar means this is a method of lowering the strings' pitch. But maybe they think it looks cool.
Comment: Michael Schenker uses a similar tech on his flying V by bracing the V between his legs and cranking on the head stock.  He has broken guitars with this tech.  I would never do this, and wouldn't recommend it to a fellow guitarist.
Comment: @Tim Thanks -- this guitar does have a whammy bar; the guitarist uses it maybe 10 seconds later.  Hence the confusion :)
Answer: I don't know of it having a name, per se, but the guitarist is essentially flexing the body relative to the neck by holding the neck firm and taking advantage of whatever play there is in the neck joint. This raises and lowers the pitch like a whammy bar but is much more subtle, like a very subtle all-strings vibrato. The player typically grasps the body close to the neck to get less torque and therefore reducing the potential for such movement as to damage the joint permanently.
One use of the technique is to compensate for less-than-perfect intonation on higher frets. If you play an A-shape barre chord on the 12th fret, for example, and find that the G-string is a little sharp, flexing the neck like this "blurs" the pitches and creates the illusion that the chord is in tune.

What Does This Pushing Technique Do?


How to get a target's property value inside a control template

Question: Suppose I have the following:
<ControlTemplate x:Key="MyButtonTemplate" TargetType="{x:Type Button}">
   <Grid>
      <Rectangle Width="100" Height="20" />
   </Grid>
</ControlTemplate>

<Button Template="MyButtonTemplate" Width="25" />
<Button Template="MyButtonTemplate" Width="50" />
<Button Template="MyButtonTemplate" Width="75" />

What do I need to do to the control template to have the rectangle be the width of the button instead of a hard-coded 100 each time? Is there a way for me to access the property value of my target type from inside of my control template?
Thanks.
Answer: How about this:
 <Rectangle Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" />

Answer: Don't specify Width or Height for Rectangle at all and let it stretch to the size of the Button:
<ControlTemplate TargetType="{x:Type Button}">
   <Grid>
      <Rectangle/>
   </Grid>
</ControlTemplate>


jQuery Ajax sending data to php with one button click but two different actions

Question: What I'm trying to achieve is a user to follow another user without having to refresh the page. So far I've played around and had no problem inserting and deleting the rows in mysql table, but now when I'm trying with AJAX I can't get it to work.
jquery
$(document).ready(function(){
$("#followbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();

$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#followbutton').hide();
$('#unfollowbutton').show();

// $("#unfollowbutton").hover(function(){
// $(this).text("Unfollow");
// }, function(){
// $(this).text("Unfollow");
// });

}
});
});
});

$(document).ready(function(){
$("#unfollowbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();

$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitUnfollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#unfollowbutton').hide();
$('#followbutton').show();

//I want the button to change its text to Following and when hovering it should say unfollow if user is followed

}
});
});
});

followuser.inc.php
<?php
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
if (isset($_POST["submitFollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('INSERT INTO userfollow (thefollower, theuserid, followstatus) VALUES (?,?,?)');
$followstatus = 1;
$stmt->bind_param('sss', $userthatisfollowed, $theuserid, $followstatus);
$stmt->execute();
echo $response = "Followed!";
$stmt->close();

} else if(isset($_POST["submitUnfollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('DELETE userfollow FROM userfollow WHERE thefollower = ? AND theuserid = ?');

$stmt->bind_param('ss', $userthatisfollowed, $theuserid);
$stmt->execute();
echo $response = "Unfollowed!";
$stmt->close();
} else {
    echo "DID NOT WORK";
}

profile.php
if(isset($_SESSION["userid"]) && $_SESSION["userid"] != $userthatisfollowed) {
?>
<form action="<?php echo htmlspecialchars("includes/followuser.inc.php");?>" id="followform" method="post">
<?php

if ($resulted->num_rows > 0){
$subscribe_status = "Unfollow";
$subscribe_text = "Following";

} else {
$subscribe_status = "Follow";
$subscribe_text = "Follow";
}

echo "<button name='submit".$subscribe_status."' id ='unfollowbutton' type='submit' style='display:none'>";
echo "".$subscribe_text."";
echo "</button>";

echo "<button name='submit".$subscribe_status."' id ='followbutton' type='submit'>";
echo "".$subscribe_text."";
echo "</button>";

// echo "<button name='submit".$subscribe_status."' id ='notificationbell' type='submit' style='display:none'>";
// echo "";
// echo "</button>";

echo "

";
?>
<input type="hidden" name="theuserid" id="theuserid" value="<?php echo $_SESSION["userid"] ?>">
<input type="hidden" name="thefollower" id="thefollower" value="<?php echo $userthatisfollowed; ?>">
</form>
<?php
}

What's worth noting is that I'm getting the response DID NOT WORK which tells me that if(isset($_POST["submitUnfollow"])) is not set. However, If I try with if(isset($_POST["theuserid"]) && (isset($_POST["thefollower"])) then it actually works for the insert query but not for the delete query.
Comment: You're not sending `submitFollow` in the `data:` argument, so `if (isset($_POST['submitFollow']))` won't succeed.
Comment: @Barmar How would I do it considering that there is a clickevent on that exact button? you mean like this var thebutton = $('#followbutton').val(); and have that in the data:argument as well?
Answer: You're missing the submitFollow parameter in the data: object. Instead, you have followbutton: true, which isn't used by the PHP code. So change that to:
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFolow': 'true'},

And for the unfollow button, use submitUnfollow instead.
Comment: thank you, did not know you could do it that way.
Comment: It is currently working, however I still need to refresh the page in order for the button texts to change. If the user Follows another user, the button/click event should be changed to Unfollow. This only happens whenever I refresh the page
Comment: Create both a follow button and unfollow button. When the user clicks on button, hide that button and show the other. I don't see any way for the user to choose who they're following, since you have that in a hidden input, it's not something they select.
Comment: and both of the buttons should be outside of the if statement that is checking the subscribe status? @Barmar
Comment: Yes, they're just in the static HTML.
Comment: The problem I'm having is that everytime I refresh the page the value of subscribe_status becomes Follow so the user can be followed again even tho there already is a record in the table, which is wrong. However, with ajax it works as intended
Comment: And if i put in the buttons inside of the if statements I cannot use for example $('#unfollowbutton').hide();
$('#followbutton').show();
Comment: I've updated the post so you can see the code jquery and html
Comment: Don't put the buttons inside the `if`. The `if` statement should just specify whether the button is hidden or shown.
Comment: This should be a new question, I already answered the original question.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/250485/discussion-between-votum-and-barmar).


Verify is tautology by using logical equivalence

Question: Verify is tautology by using logical equivalence:
$$((p ∨ q) ∧ (p → r) ∧ (∼ r)) → q$$
by showing what laws are using, step by step explanation needed.
Logical equivalence: de morgan's laws, commutativity, associativity, double negative, distribution, idempotent, absorption, identity, universal bound, negation
Rules of inference: modus ponens, modus tollens, generalisation, specialisation, conjunction, ellimination, transivity, proof by division into cases, contradiction
What I got so far:
I need to prove
$$((p ∨ q) ∧ (p → r) ∧ (∼ r)) → q ≡ \text{tautology}$$
Since $p → r$ same as $∼ p ∨ r$:
$$((p ∨ q) ∧ (p → r) ∧ (∼ r)) → q ≡ ((p ∨ q) ∧ (∼ p ∨ r ) ∧ (∼ r)) → q$$
I am stuck here
Comment: Please include your work or at the very least what does one have to do to verify something is a tautology? For instance, I can tell that the premise tautologically implies $q$ without making use of the equivalences.
Comment: @AlvinLepik please check my solution I got so far.
Answer: Proceed by
$$(p\lor q) \land (\neg p\lor r)\land\neg r \rightarrow q \equiv \neg (p\lor q) \lor \neg (\neg p\lor r)\lor r \lor q\\ \equiv (\neg p\land\neg q) \lor (p\land\neg r)\lor r\lor q $$
View the latter formula grouped as follows
$$\left [(\neg p\land \neg q) \lor q\right ] \lor \left [(p\land\neg r)\lor r\right ]\equiv $$
Use distributivity
$$\equiv \left [(\neg p\lor q) \land (\neg q\lor q)\right ] \lor \left [(p\lor r)\land (\neg r\lor r)\right ] \equiv \neg p\lor q \lor p\lor r \equiv t  $$
Answer: Next use absorption, since $~ (\neg p\vee r)\land \lnot r \equiv \neg p$


what's 10's complement

Question: Design a combinational circuit that generates the 10's complement of a BCD (Binary Coded Decimal) digit.
(i)Built the truth table of your circuit
my understanding is that, the 9's complement of 0 is 9,the 9's complement of 1 is 8.....and 10's complement equals to 9's complement plus 1. but someone told me " 10's compliment is similar to 2's compliment in binary system.we can find 2's compliment by adding 1 to 1's compliment.1's compliment of 0001=1110...add 1 to 1110 to get 2's compliment.1110+1=1111 " so...what is the correct answer
truth table
Comment: In base 10, ten's complement works like two's complement in base 2, and nines' complement works like ones' complement in base 2.
Comment: You should post here: http://electronics.stackexchange.com/ or here: http://cs.stackexchange.com/
Answer: Your understanding is correct: 10's complement is done by taking 9's complement and adding 1.
On better reading of your question, I see that the explanation given of how to do 10's complement by the other person is wrong.  However, there is a similarity: in both cases you subtract each digit from the largest digit in the number base and then add 1.
The other similarity in behavior is that they can both be used to add signed numbers using the exact same algorithm as addition of unsigned numbers.
In binary: decimal 3 is 0011; to get -3 in 2's complement, subtract each digit from 1 to make the 1's complement (1100) then add 1 to get the 2's complement (1101).  Non-negative numbers are unchanged in these complements, so decimal 2 is 0010 in binary 2's complement.  Adding 1101 to 0010 gives 1111, which you can show is the 2's complement of -1.
Likewise, in decimal one can get the 10's complement for -12, by subtracting each digit from 9 (9987) then adding 1 (9988).  As in binary, non-negative numbers are unchanged in 10's complement so the 10's complement of 15 is 15.  Adding 9988 to 15, gives (1)0003 [you drop the carry out] giving 3, which is the answer to -12+15.
The Wikipedia article on 2's complement, gives more details about why 2's complement is used in computers.  10's complement in decimal has analogous properties to 2's complement in binary.

what's 10's complement


Selecionar modelo de acordo com a marca

Question: Tenho a função que retorna todas as marcas cadastradas: (Com os campos ID e MARCA)
public function lista(){

        $lista = array();

        $n = 0;
        $db = new mysql();
        $exec = $db->executar("SELECT * FROM automovel_marca order by marca asc");
        while($data = $exec->fetch_object()){

            $lista[$n]['id'] = $data->id;
            $lista[$n]['marca'] = $data->marca;

            $n++;
        }
        return $lista;
}

E a função que retorna os modelos: (Com os campos ID, IDMARCA e MODELO)
public function lista(){

        $lista = array();

        $n = 0;
        $db = new mysql();
        $exec = $db->executar("SELECT * FROM automovel_modelo order by modelo asc");
        while($data = $exec->fetch_object()){

            $lista[$n]['id'] = $data->id;
            $lista[$n]['idmarca'] = $data->idmarca;
            $lista[$n]['modelo'] = $data->modelo;

            $n++;
        }
        return $lista;
}

Eu consegui puxar elas individualmente nos FORMS, o problema é que queria que o campo MODELO do FORM fosse relacionado ao campo MARCA, quando a pessoa selecionar a marca ele exiba todos os modelos referentes aquela marca.
A estrutura do DB está assim:
automovel_marca (id,marca)
automovel_modelo (id,idmarca,modelo) - neste caso o idmarca segue a relação do ID do automovel_marca
Answer: Eu desconheço a estrutura das suas tabelas, mas vamos la basicamente alterariamos os dois locais abaixo no metodo lista do automovel_modelo:
public function lista($idmarca){

        $exec = $db->executar("SELECT * FROM automovel_modelo where idmarca = ".$idmarca." order by modelo asc");

Ai quando chamar o listar do automovel_modelo você passaria o parametro $idmarca.

Selecionar modelo de acordo com a marca


Codeigniter/Angular2 Session persistence

Question: so I am developing an API first application, Backend with codeigniter-restserver (https://github.com/chriskacerguis/codeigniter-restserver) and front end with Angular2.
I have finished the backend and tested all endpoints with Postman including image upload and delete endpoints, all work fine.
however in addition to authorization http header, some endpoints are guarded by user login session checks. in postman session persist so if I try to upload an image to an endpoint it check if there is anyone logged in, if not it return a status code indicating "not logged in", then I go to the login endpoint login and then return to the image upload endpoint then it works (on Postman).
however from my Angular2 client application even when I call the login endpoint, its still returns the user not loggen in status code. when I then call the image upload endpoint, like it kills the session immediately it recieve response from the REST server.
my question is, what do you think Postman do differently from my Angular2 client App (I am using Angular http and observables).
The Codeigniter restserver is on localhost:80 and Angular2 client App on localhost:4200 in dev mode.
Thanks
Answer: I don't know if this is direct answer for your question, but i hope it will help you understand your problem and how to continuo with your project...
I would not depend on Codeigniter's session, since you are working on Single page application and the "rest server" should be stateless.
This also means that you should not look for the sessions in Codeigniter...
Your client application should contain session data. So you should use JsonWebToken (JWS), which can be stored in local storage or cookie on client. For each request you can also send this JWT token to server, where you decode it with some helper function (i'm using JWT helper) and if verification is true, then you make further actions, else return Not authorised or some response
Comment: It is not possible to create a small app with angular inside a codeigniter view?
There is many possibilities of this combo and the question still seems valid.
Comment: yeaa its possible and also you can use codeigniters session if you wan't.. I just think that restfull application should be statless and there for you should hold session on you client not on your server... What about if you decide that you will connect another client on this application?


A question about Cartesian Products of Families

Question: I am reading Halmos' Naive Set Theory, and am quite puzzled with the way he defines a Cartesian Product of a Family. He says: "the Cartesian Product of the family is, by definition, the set of all families {xi} with xi ∈ Xi for each i in I." Now, by this definition then, if I define some family {Ai} with i belonging to the index set 2. So that {Ai} is the set A0 and A1. Then the Cartesian Product of this family is, by definition, the set containing all the functions x from the index set 2 to the set {Ai} for every i in 2. Now, let A0 be the set {a,b} and A1 the set {c,d}. First then, the set containing all the functions from 2 to A0 is the set {{(0,a),(1,a)},{(0,a),(1,b)},{(0,b),(1,a)},{(0,b),(1,b)}}. And secondly, the set containing all the functions from 2 to A1 is the set {{(0,c),(1,c)},{(0,c),(1,d)},{(0,d),(1,c)},{(0,d),(1,d)}}. So that the Cartesian Product of whole  {Ai} is the union of those two sets which is: {{(0,a),(1,a)},{(0,a),(1,b)},{(0,b),(1,a)},{(0,b),(1,b)},{(0,c),(1,c)},{(0,c),(1,d)},{(0,d),(1,c)},{(0,d),(1,d)}}. BUT, Halmos later in the same section defines the Cartesian Product of a {Ai} with i ∈ 2 to be the same as A0 × A1 which is the set {(a,c),(a,d),(b,c),(b,d)}, WHICH IS definitely not the set we found earlier. Where is my logic flawed? It would be most helpful if someone explained this to me explicitly. Thank you in advance.
Answer: First, let me use your example to show what Halmos's definition means. So $I=2$, $A_0=\{a,b\}$, and $A_1=\{c,d\}$. According to Halmos, the cartesian product of this family is the set of families $\langle x_i\rangle_{i\in I}$, with the same index set $I=2$, that satisfy $x_i\in A_i$ for each $i\in I$. (Note that $x$ and $A$ here both have the subscript $i$.  Note also that I'm using the angle-bracket notation $\langle\cdots\rangle$  for families.)
So an element of this family would be a family $\langle x_0,x_1\rangle$  consisting of $x_0\in A_0$ and $x_1\in A_1$. That means $x_0$ can be $a$ or $b$ while $x_1$ can be $c$ or $d$. The elements of the cartesian product are therefore the four families $\langle a,c\rangle,\langle b,c\rangle,\langle a,d\rangle,\langle b,d\rangle$.
That looks pretty good, in that those four families look like the four elements you were expecting in $A_0\times A_1$, but there's one detail that deserves to be straightened out. Most authors (I haven't checked Halmos) define $I$-indexed families to be certain functions. In particular, a $2$-indexed family, like $\langle a,c\rangle$, is not strictly speaking the same thing as an ordered pair, like $(a,c)$. So the cartesian product of a $2$-indexed family $\langle A_0,A_1\rangle$ is not the same set as $A_0\times A_1$. (And I hope Halmos doesn't say it is, unless he has a different notion of "family" than what I've described.) But there's an obvious one-to-one correspondence between the two, namely to change angle-brackets to parentheses.
Comment: Much thanks! Only for some reason Halmos didn't use angle brackets when denoting the set of all families ⟨xi⟩i∈I, he wrote {xi}i∈I. Also, Halmos does define cartesian products of families as certain sets of functions. And thank you again for answering!
Answer: I agree with you that Halmos's discussion is not so easy...
Consider a simple example with set $A= \{ a,b \}$ and $B= \{ l,m \}$.
The cartesian product $A \times B = \{ (x,y) \mid x \in A \text { and } y \in B \}$ will have four pairs.
Consider now a function $x : A \to B$; e.g. $x= \{ (a,l), (b,m) \}$ which has two elements.
If $x' = \{ (a,l), (b,l) \}$ is another such function, we have that $x \cup x' = \{ (a,l), (b,m), (b,l) \}$ (which is not a function); thus, collecting together all such functions, the result will contain all pairs, and thus will be exactly the set $A \times B$.

Let start again from Halmos' definition (page 34): $x$ is a function from the domain $I$, the index set to $X$ (the range of the function is the indexed set).
The function itself is called a family and the value of function $x$ is at index $i$, called a term, is denoted by $x_i$.
Thus, for a family we have: $\{ A_i \}_{i \in I} = \{ (i, A(i)) \mid i \in I \}$.
Now we can to move to page 37 and consider "the family of sets $\{ X_i \}_{(i \in I)}$".
If $I= \{ a,b,c \}$, we want that the "generalized" cartesian product of $\{ X_i \}_{(i \in I)}$ will be made of "uples" $\{x_a,x_b,x_c \}$ where $x_i \in X_i$.
But such an uple is a function $x : I= \{ a,b,c \} \to \bigcup X_i$ with the condition that $x(i)=x_i \in X_i$.
Thus, de corresponding definition will be:

$\Pi_{i \in I} \{ X_i \} = \{ x \mid (x: I \to \bigcup_{i \in I} X_i \text { and } (x(i) \in X_i) \}$.

Using the $x_i$ notation: $\Pi_{i \in I} \{ X_i \} = \{ x_i \mid \forall i(i \in I \to x_i \in X_i) \}$.
Using the index set $I$ and the three sets: $X_a= \{ l,m \}, X_b= \{ l, n \}, X_c= \{ l \}$, we can compute all elements of $\Pi \{X_i \}$:

$\{ \{ (a,l), (b,l), (c,l) \}, \{ (a,l), (b, n), (c,l) \}, \{ (a,m), (b,l), (c,l) \}, \{ (a,m), (b,n), (c,l) \} \}.$

As we can see, due to the fact that the index set $I$ has three elements, all elements of the cartesian product are "three-uples".
If we apply the definition to a couple of sets $X_0= \{ a,b \}$ and $X_1 = \{ l,m \}$, i.e. to the family $\{ X_i \}$ indexed by $I = \{ 0,1 \}$, what we get is:

$\Pi \{ X_i \} = \{ (0,a), (1,l) \}, \{ (0,a), (1,m) \}, \{ (0,b), (1,l) \}, \{ (0,b), (1,m) \}.$

Now, if you compare it with the corresponding example $A \times B$ above, you can see that the two sets are not equal (but they are "structurally" so).
The link between the two definitions is given by Halmos in the first lines of page 36 with the "natural one-to-one correspondence between the cartesian product of two sets and a certain set of families."


Update com duas tabelas ao mesmo tempo

Question: Estou fazendo um update para janela de edição e não está dando erro, mas está funcionando somente a parte de endereço, a parte das informações do apicultor não está atualizando
Tabela apicultor
<?php
session_start();
require_once "conexao.php";

$nome_apicultor = $_POST['nome_apicultor'];
$sobrenome_apicultor = $_POST['sobrenome_apicultor'];
$email_apicultor = $_POST['email_apicultor'];
$cpf_apicultor = $_POST['cpf_apicultor'];
$rua_apicultor = $_POST['rua_apicultor'];
$numero_apicultor = $_POST['numero_apicultor'];
$bairro_apicultor = $_POST['bairro_apicultor'];
$cidade_apicultor = $_POST['cidade_apicultor'];
$complemento_apicultor = $_POST['complemento_apicultor'];
$telefone_apicultor = $_POST['telefone_apicultor'];
$estado_apicultor = $_POST['estado_apicultor'];
$codEndereco = $_POST['codEndereco'];
$codApicultor = $_SESSION["token"];

try {
    $prepared = $conexao_pdo->prepare("UPDATE `endereco` SET `endereco` = :rua_apicultor, `bairro` = :bairro_apicultor, `numero` = :numero_apicultor, `complemento` = :complemento_apicultor, `cidade` = :cidade_apicultor, `estado` = :estado_apicultor  where `cod` = :codEndereco;");
    $prepared->bindParam(":rua_apicultor", $rua_apicultor);
    $prepared->bindParam(":bairro_apicultor", $bairro_apicultor);
    $prepared->bindParam(":numero_apicultor", $numero_apicultor);
    $prepared->bindParam(":complemento_apicultor", $complemento_apicultor);
    $prepared->bindParam(":cidade_apicultor", $cidade_apicultor);
    $prepared->bindParam(":estado_apicultor", $estado_apicultor);
    $prepared->bindParam(":codEndereco", $codEndereco);
    $prepared->execute();
    $id_end = $conexao_pdo->lastInsertId();

    if($prepared->rowCount() > 0) {
        $prepared = $conexao_pdo->prepare("UPDATE `apicultor` SET `nome` = :nome_apicultor, `sobrenome` = :sobrenome_apicultor, `email` = :email_apicultor, `cpf` = :cpf_apicultor, `telefone` = :telefone_apicultor, `endereco_cod` = :endereco_cod  where `cod` = :codApicultor;");
        $prepared->bindParam(":nome_apicultor", $nome_apicultor);
        $prepared->bindParam(":sobrenome_apicultor", $sobrenome_apicultor);
        $prepared->bindParam(":email_apicultor", $email_apicultor);
        $prepared->bindParam(":cpf_apicultor", $cpf_apicultor);
        $prepared->bindParam(":telefone_apicultor", $telefone_apicultor);
        $prepared->bindParam(":codApicultor", $codApicultor);
        $prepared->bindParam(":endereco_cod", $id_end);
        $prepared->execute();

        if($prepared->rowCount() > 0) {
            header("Location: ../Perfil.php");
        }
        else {
            header("Location: ../Perfil.php");
        }
    }
    else {
        header("Location: ../Perfil.php");
    }

} catch(PDOException $e) {
    print $e->getMessages();
    die();
}
?>

Comment: Defina uma transação com os dois comandos UPDATE, um para cada tabela, que eles serão executados de forma atômica, isto é, ou os dois UPDATES serão executados ou nenhum deles será.
Answer: Para podermos ajudar melhor coloque essas duas tabelas do seu banco de dados na pergunta. E se o endereco_cod que você passou for chave primária coloque ele na cláusula where em vez de editá-lo. Algo assim:
UPDATE `apicultor` SET `nome` = :nome_apicultor, `sobrenome` = :sobrenome_apicultor, `email` = :email_apicultor, `cpf` = :cpf_apicultor, `telefone` = :telefone_apicultor
where `endereco_cod` = :endereco_cod and `cod_Apicultor` = :codApicultor;

E algo que eu notei também é que na sua claúsula where nos dois updates está escrito cod = :codEndereco; e no outro cod = :codEndereco;, o cod então seria o mesmo em endereço e apicultor?
Comment: Coloquei as duas tabelas na pergunta
Comment: Se você estiver usando POO da uma olhada na documentação para deixa-la mais simples que você irá entender melhor: https://www.php.net/manual/pt_BR/book.pdo.php  Por que do jeito que você colocou o código eu não sei se você pode usar funções que era o que eu recomendaria. Proucura algo melhor sobre o padrão MVC se você não entender.

Update com duas tabelas ao mesmo tempo


Add value to every "other" field ((i+j)%2==0) of numpy array

Question: I have an m-by-n numpy array, and I'd like to add 1.0 to all entries [i, j] when (i + j) % 2 == 0, i.e., "to every other square".
I could of course simply iterate over the fields
import numpy as np

a = np.random.rand(5, 4)

for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        if (i + j) % 2 == 0:
            a[i, j] += 1.0

but needless to say this is really slow.
Any idea of how to improve on this?
Answer: You can easily do the operation in two steps, like
import numpy as np

a = np.zeros((5, 14))

# Even rows, odd columns
a[::2, 1::2] += 1
# Odd rows, even columns
a[1::2, ::2] += 1

print a

Answer: Here's one way using NumPy broadcasting -
a[(np.arange(a.shape[0])[:,None] + np.arange(a.shape[1]))%2==0] += 1

Explanation : We basically create two arrays that are equivalent of the i-th and j-th iterators. Let's call them I and J.
I = np.arange(a.shape[0])
J = np.arange(a.shape[1])

Now, to perform an operation between all possible i and j, we create extend I to 2D by pushing its elements into the first axis and thus creating singleton dimension along its second axis.
Figuratively, the effect of  broadcasting could be put like this :
    I[:,None] : M , 1
            J : 1 , N
I[:,None] + J : M,  N

Thus, the final setting would be -
a[(I[:,None] + J)%2==0] += 1

To put it other way with the intention to avoid comparing with 0 and directly use mod-2 which would be essentially 0 or 1 -
a += (np.arange(a.shape[0])[:,None]-1 + np.arange(a.shape[1]))%2

One can also use np.ix_ to process odd and then even rows for setting, like so -
a[np.ix_(np.arange(0,a.shape[0],2),np.arange(0,a.shape[1],2))] += 1
a[np.ix_(np.arange(1,a.shape[0],2),np.arange(1,a.shape[1],2))] += 1

Comment: could please add some explanation? Would surely help newbies to understand it in a better way.
Comment: I think the `np.xi_` solution should get more emphasis; it's about twice as fast.
Comment: @NicoSchlömer Well the broadcasting strike me first, so that came up at the top :)
Answer: One can build a mask for "every other" element, and apply the addition on the mask.
# Create mask
m00 = np.zeros(a.shape[0], dtype=bool)
m00[0::2] = True
m01 = np.zeros(a.shape[1], dtype=bool)
m01[0::2] = True
m0 = np.logical_and.outer(m00, m01)

m10 = np.zeros(a.shape[0], dtype=bool)
m10[1::2] = True
m11 = np.zeros(a.shape[1], dtype=bool)
m11[1::2] = True
m1 = np.logical_and.outer(m10, m11)

m = np.logical_or(m0, m1)
a[m] += 1


How to visualise open cones of infinite spaces?

Question: By open cone I mean the usual definition
$\mathcal{O}X = \frac{X \times [0, 1)}{X \times \{0\}}$.
I can view what an open cone will look like if $X = [0, 1]$, for example. Is there anyway of viewing what an open cone will be for larger spaces, such as $\mathbb{R}$ or $\mathbb{Z}$?
Are there any theorems which give us information about the open cone of $X$, given properties of $X$?
Answer: $\mathbb{R}$ is homeomorphic to the open interval $(-1;1)$ and $\mathbb{Z}$ can be 'squashed into' that interval via a function like:
$ f(0) = 0 $
$ f(n) = 1 - \frac{1}{n} $ if $n > 0$
$ f(n) = -1 - \frac{1}{n}$ if $n< 0$
The open cones of the images of $\mathbb{R}$ and $\mathbb{Z}$ are simpler to visualize, in my opinion.
I don't think all the properties carry over, though - I think there might be a problem with local connectedness in the example for $\mathbb{Z}$, for example... What properties are you interested in?
Comment: I'm not interested in anything in particular, just interested to see if we can immediately deduce anything about the cone of $X$ just based on $X$. I'm fairly new to this, are you saying about that if there is a homeomorphism from $X$ to $Y$, then there is also a homeomorphism from $\mathcal{O}X$ to $\mathcal{O}Y$?


divisibility remains by scaling multiplicative order

Question: I want to show that if  p | $a^{e}-1$ then also p | $a^{ek}-1$ where k is any integer.
Def. of order in terms of divisibility: Let $m ≥ 2$ and a be any integer coprime to $m$. The order of $a$ mod $m$ is the smallest $e > 0$ so that $m$ divides $a^{e}-1$.
In terms of congruence I can see why this is the case: e.g. let $a = 2, e = 4, m = 5$. Then
$2^{4} ≡ 1 $ (mod $5$), lets scale $e$ with $k=2$, then $2^{4^2} ≡ 1 $ (mod $5$) = $2^{4}2^{4} ≡ 1 $ (mod $5$). So it does not matter what $k$ is, the congruence is still valid.
I don't know exactly how to show why the scaling of $e$ with any $k$ does not change the fact that $p$ divides  $a^{e}-1$.
Comment: $\,p\mid a^e-1\mid a^{ek}-1\,$ by the first linked dupe with $\, a \to a^e,\ b = 1,\ n = k.\ $ Or use $\bmod p\!:\ a^e\equiv 1\Rightarrow (a^e)^k\equiv 1^k\equiv 1\,$ by the [Congruence Power Rule](https://math.stackexchange.com/a/879262/242), or if $\ell := {\rm ord}_p \,a\,$ then $\,\ell \mid e\Rightarrow \ell\mid ek\Rightarrow a^{ek}\equiv 1\,$ by the [Order Theorem](https://math.stackexchange.com/a/2033681/242).
Answer: If $p|a^e-1$, then $pc=a^e-1$ for some $c$, and so $pc+1=a^e$.
Then $(pc+1)^k=a^{ek}$, and the left hand side is $pb+1$ for some $b$, hence $pb=a^{ek}-1$, or $p|a^{ek}-1$.
Answer: Observe,
$$a^{ek}-1=(a^e)^k-1^k=(a^e-1)\cdot q$$
for some integer $q$.
Since $p$ divides $a^e-1$, it must divide $a^{ek}-1$.
Comment: [Factorize $a^n-b^n$](https://math.stackexchange.com/questions/712758/derivation-of-factorization-of-an-bn)
Comment: We know for a fact that $p\;|\;a^e-1$. In the first step, we show that $a^e-1\;|\;a^{ek}-1$. Therefore $p\;|\;a^e-1\;|\;a^{ek}-1.$ The term ' $q$ ' is the quotient when $a^{ek}-1$ is divided by $a^e-1$. Hope it helps :)
Comment: I think I understood your explanation, but the .q is a bit unclear for me. Let me try to summarize your point in my own words: $a^{ek}-1=(a^e)^k-1^k$. This is clear. The next step is $p | (a^e-1)^k$. And since $ p | a^e - 1$, $p$ also divides $(a^e - 1)^k$
Comment: Think about it this way. In the equation, $$a^{ek}-1=(a^e-1)\cdot q$$ $p$ appears in the prime factorization of $a^e-1$ on the right hand side. Hence, it also appears on the left side. Therefore, $p$ divides $a^{ek}-1$.


Cricket Ruling - Run out after a short run

Question: I am looking for assistance on a scenario where

The 1st run was successfully compeleted by the batsman on non-striking end
2nd run was short by the non-striking batsman
When the non-striking batsman ran for the 3rd run, the striking batsman got run out on the other end
The non-striking batsman who took short run, came back to his crease after the other batsman got run out on the opposite end.

Question: Will the 2nd run be considered as the player took short run initially but came back to crease when the other batsman got run out?
Answer: If I understand your explanation correctly:

The first run was properly completed
The second run was run short by the non-striker
The striker was run out going for the third run.

If it hadn't been for the short run, this would result in two runs scored and the striker being run out; however, due to the short run, only one run is scored - Law 18:

18.3.2 Although a short run shortens the succeeding one, the latter if completed shall not be regarded as short.
[...]
18.4.1 if either batsman runs a short run, the umpire concerned shall, unless a boundary is scored, call and signal Short run as soon as the ball becomes dead and that run shall not be scored.

Therefore one run is scored, and the striker is out.
Comment: Will it be the same ruling even if the batsmen did not cross each other when they started running for the 3rd run?
Comment: If the batsmen haven't crossed for the 3rd run, the striker cannot be out at the non-striker's end, but ignoring that: yes. The batsmen have correctly completed one run so that's always going to be given, they've incorrectly completed one run so that's not going to be given, and someone is out.


Bootstrap subtheme move main navigation

Question: I have a sub theme based off Bootstrap and my current nav bar look like this

My goal is to move the menu (Home ... contact) to appear underneath the slogan when the page is larger than 768px as it is the breakpoint when it turns into a burger button and appears on the right. I was trying to play around with the css and the page.tpl.php, but no results there. This is the first time I've used Bootstrap with Drupal.
Answer: To move things around like that you will either need to use the CSS top property within your CSS or SASS file(s), or move it around with Javascript.
Answer: You can add a breakpoint in your LESS/CSS (ideally you're using LESS or SASS with bootstrap, but anyway) and I'd probably make the slogan absolute position and use the top property as suggested by @Darvanen like this:
    /* Small devices (tablets, 768px and up) */
    @media (min-width: @screen-sm-min) {
        div.slogan {
            position: absolute;
            top: 0;
        }
        div#main-menu {
            margin-top: 30px; // Depends on the size of the slogan div
        }
    }

You might need to experiment with the positioning of the menu div, like make it position: relative;.
For more see the excellent bootstrap docs: http://getbootstrap.com/css/#grid-media-queries
Answer: I successfully modified page.tpl.php file and completely replaced the header section with -

      <a class="logo" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
        <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          Toggle navigation

        </button>

              <?php if (!empty($primary_nav)): ?>
                <?php print render($primary_nav); ?>
              <?php endif; ?>
              <?php if (!empty($secondary_nav)): ?>
                <?php print render($secondary_nav); ?>
              <?php endif; ?>

Bootstrap subtheme move main navigation


Notify.JS : Notify on a speficic element not working when page is scrolled

Question: I a have probleme in my MVC .NET application when i use notify.js.
I use this library to display some informations in all my website, but I just realized that in every pages when I scroll the position of my notify is not working !
I try to notify on a specific element like that :
<code>  $('#idOfMyElement').notify("Notify text", { position: "top center", className: "success", autoHideDelay: 1500 });
</code>
It's working unless i scroll ...  When I scroll the notify is displaying in the same position as if i didn't scroll ! Like the notify is fixed on the previous element's position on the screen...

My libraries are up to date, like bootstrap / jquery / notify.js

Please help, i can't reproduce this in a jsfiddle ...
Comment: According to the website: https://notifyjs.com/ the notification is displayed on an element or on a fixed part of the page that does not change when you scroll: `$.notify("I'm over here !");` I'm not sure you want fixed or global but the code you posted is a fixed notification so the element should scroll up and down with the element.
Comment: Global fixed element is displayed very well. I want to display informations on a element of my webpage. It's working until i scroll, and i think that the notifications doesn't update the current position of my element and is displayed in it's initial position, not it's new position.
Comment: Looking at the examples on the notify.js site I can see the notification is nested in the element it is attached to so when you scroll the notification sticks to the whatever element you attached it to unless you have some overriding styles to the notification that make it's position fixed.
Comment: I don't have any override style .. That's why i'm stuck. I'll keep searching.
Comment: Same comportment when i remove all the css in my view ...
Answer: I had the exact same problem.
I couldn't understand why on notify.js web worked fine, and not on mine.
So I just changed the jquery version and it started working fine.
I used jquery 3.0.0 on my website and it gave this problem, and on notify.js website it uses 1.11.
I have tested that it works fine with jquery 1.11, 2.2.4, and 3.5.1 (which is the one I have now)


How do I tell the difference between a borrowed chord and a key change?

Question: Having muddled through for a few years, I'm finally learning the basics of harmony. I'm having a bit of trouble, though understanding exactly what goes on when chords occur from outside the key. Is the key changing? Or are these 'borrowed' chords, and in which case, how are they decided on?
For example, see the classic "I Can't Forget" by Leonard Cohen.

Here is an apparently accurate transcription of the chords in the verse:
http://www.maartenmassa.be/CohenChords/09iym/i_cant_forget.htm
<code>    F#
I stumbled out of bed
       D#m
I got ready for the struggle
F#
I smoked a cigarette
     D#m               C#
And I tightened up my gut
   B         Bm       G#m
I said this can't be me
 A#          E    D#m
Must be my double
F#              B
And I can't forget... (etc)
</code>
OK, so I see I-vi-I-vi-V of F# major, taking us to the line "I said this can't be me". This makes sense to me. But what happens then?
It seems to modulate to B minor - fine, I think we're heading for a scale with B minor in it, ie A major, D major(/B minor),  or G major. But this is followed immediately by G#m, though, so it's not any of those (maybe we're back in F#?), but then we get A#!? E?
I am totally confused at this point as to what key we're in.
It's particularly galling as the change to A# is my favourite chord change in the song, and the whole run from B to D#m, and then back to F#, is weirdly satisfying.
Can anyone explain what's going on here?
Comment: Are you primarily interested in this one song, or is this a more general question? Do you have other examples?
Comment: Generally, it's about how one might include such an exotic chord change as as A# -> E in a song that's apparently in the key of F# major.
Answer: Mmmmm, a flat-VII cadence!  One of my favorite sounds, too.  See, backdoor progression aka backdoor cadence.  Also called a mixolydian cadence.
Comment: I don't see where you are finding a bVII-I cadence.
Comment: Could it be the E major heading back to F# via D#m?
Answer: Without hearing the song this is what is likely happening:

F# I stumbled out of bed
D#m I got ready for the struggle
F# I smoked a cigarette
D#m - C# And I tightened up my gut

This is fairly straight-forward, moving along in the key of F#: I-vi-I-vi-V
From there, it is a deceptively cadences to "B" (IV) instead of the expected return to "F#":

B - Bm - G#m I said this can't be me
A# - E - D#m
  Must be my double
F# - B And I can't forget... (etc)

In this passage, he is using "B" as a local tonicization by treating as a pivot chord and implying a move to B major.  Using the first be as a pivot, we'd analyze the chords in the key of B major: I-i-vi-VII-IV-iii-V-I.
Obviously, with a VII, something odd is happening. It can't be a borrowed chord from the subdominant (if we were thinking of the entire passage in F#) because as a leading tone chord, it would be fully-diminished. So how does the A# chord function?
My answer is that the chord in of itself is inherently non-functional in terms of harmonic progression, but is function in creating some very nuanced inner-lines.  In order to understand what's really happening here we need to look at the text along with the chords.

In order to understand the second part, we must first look at the top stanza highlighted above.  Notice how an association is developed between the personal pronoun "I" and the chordal motion from I-vi. Each line begins with "I" and the chord is either I or vi.
Now, looking at the second stanza, notice how the first line also contains the personal pronoun "I" along with a motion of I-vi (now in B major).  This is where things get interesting.  The straight-forward harmonic motion of the first stanza mirrors the confident, concrete observations and descriptions of actions detailed in the text.  It is only when the character begins questioning themselves that the harmonic motion begins to get wonky, which brings us back to the second stanza...
Notice how the chord quality changes from B to Bm with the phrase "I said this can't be me" - already the author is blurring the lines of functional tonality here in the same way the character in the song is confused. This fact is further supported by chromatic noodling of the inner-lines which I will outline below.  First, let us take a pitch inventory of the chords used:

B = B, D#, F#
Bm = B, D, F#
G#m = G#, B, D#
A# = A#, C##, E#
E = E, G#, B
D#m = D#, F#, A#
F# = F#, A#, C#

Now I will arrange them to have smooth voice-leading to better illustrate the chromatic noodling in the inner lines:

B = B, D#, F#
Bm = B, D, F#
G#m = B, D#, G#
A# = A#, C##(D), E#(F)
E = B, G#, E
D#m = A#, F#, D#
F# = A#, F#, C#

I have italicized all of the notes that move chromatically by step from the previous chord. As you can see by the numerous chromatic half-step motion between chords, Cohen is using the tried and true technique of word painting to emphasize the text's meaning.  In this case, the text suggests a blurring of identity through duality. Thus, Cohen uses chromatic half-step motion and local tonicization to the subdominant in F# major to suggest tonal implications of duality.
In the last line of the second stanza, we see a V-I in B major (an Authentic Cadence) that supports the text "And I can't forget...".  Such harmonic reinforcement (an Authentic Cadence is a strong cadence) suggests a "snapping" back to reality as the narrator of the song realizes that he cannot forget.  This harmonic motion provides stability to the wandering harmony of the previous lines, as if resuming where it had left off when beginning the section.  From here, Cohen could easily use the "B" as a pivot chord to move back into F# major and continue on.  (I don't know what happens as I have not heard the piece.)
Comment: Thank you very much for this detailed analysis and the introduction to 'tonicization', which seems to be the crucial idea here. So would it be fair to say he's exploiting the fact that B and F# have the G#m chord in common, and then using the alarming A# => E to drive home that temporary tonic change (E being a nice strong V over B), before gracefully heading back to F#?
Comment: B and F# share a few chords: D#m, B, G#m, and of course F#. E is actually the subdominant (IV) of B, so the A# chord suggests a leading tone chord more than anything else, even though it isn't actually a leading tone chord.
Answer: This seems to be just an unusual chord sequence  (ie, one that we're not used to hearing) within some otherwise fairly natural sounding chords.
I's say this isn't a key change. The next verse starts on the same chord (F#) and does the same thing so the context of the chord sequence doens't change.
At least until the end of second verse (I haven't listened further), the song is in the key F#.. major ? Only because that';s how the first line is sung (ish, he'sa bit wobbly lol).
F#major and Dm scales don't share a heck of a lot of notes, and the sequence does this kind of thing elsewhere so it seems he's going for a notion of breaking some rules and having it sound like it all fits together.
I think he's succeeded !
Comment: Once you get rid of the mistaken idea that all chords somehow "should" fit one particular scale, you won't find nearly so much need for concepts such as temporary tonics and borrowed chords.
Comment: Hi, thanks for your answer. Could you explain what E major and A# major are, then, in this context? Would you call them 'borrowed' chords? If so, why do they work? Technically they both seem to clash with the key signature.
Comment: Hmm - This : http://en.wikipedia.org/wiki/Borrowed_chord explains what a "borrowed Chord" is and as E and A# aren't in "Parallel keys" (as on wiki page) with F# then according to that definition they're not borrowed chords. I can't answer what they are though. Sometimes weirdness that shouldn't fit .. does  ! :-) It sounds like the A# is a kind of 'step' chord from G#m to E, allowing the ear to follow a few close-interval differences between G#m and A#, then E . .eg 3rd of G#m = B, A# root = A#, then 5th of E = B again. All semitone differences which the ear is tempted to follow.
Comment: @LaurencePayne I agree. I had to google "borrowed chord" as I hadn't heard the expression before in 30 years of playing - bet i've been accidentally using/writing them without knowing there was a name.
Comment: I'm not sure if it's the current wave of mainstream music pedagogy,  or something from the special breed of "theory for guitarists who want improvising tricks" that we see so much of on Internet forums.
Answer: The only "difference" between a key change and sequence of borrowed chords is where a chord progression ends up going.  For example, the chorus of "Hotel California", in the key of B minor, uses the chord sequence G D F# Bm G D Em F#.  Nothing about the first two chords, nor the melody over them, indicates whether the piece is still in Bm or has changed to D.  Indeed, if the the third and fourth chords were changed to A D while keeping the melody the same, everything would make sense but the piece would be established in D major.  Applying the same chord change to the seventh and eighth chords, and changing the last note of the melody from an F# to a D would mean the chorus was in D major rather than B minor.


Prove that $2^{4n}+1$ cannot be a prime if $3|n$

Question: $2^{4n}+1$ cannot be a prime if $3|n$ and $n>0$
My Try:
$$2^{12k}+1\equiv (-1)^{3k}+1 \equiv0\pmod{17}$$
So it divisible by $17$ for odd $k$. But how to complete the proof?
Answer: Hint: $$ 16^{3k} +1 = (16^k+1)(16^{2k}-16^k+1).$$