let $S_4$ denote the group of permutations of $\{1,2,3,4\}$ and let $H$ be a sub group of $S_4$ of order $6$ .

Question: Let $S_4$ denote the group of permutations of $\{1,2,3,4\}$ and let $H$ be a sub group of $S_4$ of order $6$ . Show that $\exists~ i \in \{1,2,3,4\}$ which is fixed by each element of $H$.
Attempt:  As per the given question, $H$ is a sub group of $S_4$ of order $6$ .
We have to prove that $\exists~ i \in \{1,2,3,4\} ~ s.t. ~ \alpha(i) = i ~\forall ~\alpha \in H$ . So, If i prove that $ H \subseteq Stab_G (i)$ , then I can prove the same.
Now, by orbit stabilizer theorem, we have $|G| = |Stab_G (i)|~|Orb_G(i)|$ .
{ So, if $G$ is a group of permutation of a set $S$. For $\forall ~s \in S$,   $orb_G(s)= \{\phi(s)~ | ~~\phi \in G .$ The set $orb_G(s)$ is a subset of $S$ called the orbit of $s$ under $G$. }
We also know that $Stab_G(i)$ is a subgroup of $G$.
IF i show that $\exists ~orb_G(i)$ such that $| orb_G(i) |=4$ under $G$, then we are done because  $Stab_G (i)$ is already a subgroup of $G$.
So, my problem boils down to finding an $i$ such that $| orb_G(i) |=4$
EDIT : I also know that Since $S_4$ has no elements of order $6$, by Lagrange's theorem the elements of H must have orders $2$ or $3 $ which means they can be which are  $2$ cycled or $3$ cycled
How do I find such an $i$. Do i now write all the elements of $S_4$? Writing down everything seems tedious and impractical though ? Help will be really appreciated.
Thank you.
Answer: Since $S_4$ has no elements of order $6$, the elements of $H$ must have orders $2$ and $3$ (and of course $1$ for the neutral eleement).
Especially, $H$ has an element of order $3$, which must be a 3-cycle $(a\,b\,c)$. (It thenalso contains $(a\ c\,b)$).
Let $d$ be the one element that does not belong to this 3-cycle.
Also, $H$ has an element of order $2$, which can be either of the form $(x\,y)$ or $(x\,y)(u\,v)$. In the first case, if $d\notin \{x,y\}$, we are done.
Otherwise note that e.g. $(a\,b\,c)(a\,d)=(a\,d\,b\,c)$ is of order $4$ and cannot be $\in H$. For the other form, note that e.g. $(a\,b\,c)\cdot (a\,b)(c\,d)=(a\,c\,d)$ and $(a\,c\,b)\cdot (a\,b)(c\,d)=(b\,c\,d)$, whence we find at least $6$ elements of order $3$ in $H$, which is impossible.
Comment: @VHP: In this case, it's quite easy to show that if a subgroup's non-identity elements all have order 2, then the subgroup has order 2 or 4, not 6. Similarly, if all non-identity elements have order 3, then the subgroup has order 3.


Memcached is not launching

Question: I just installed memcached and the memcache pecl extension. Now randomly I cannot get it to start. When I run service memcached start I get this:
Starting memcached: chown: `memcached\r': invalid user
 to switch toe user memcached
 [FAILED]

What is going on? As far as I know, I performed the installation correctly. In fact, it was running fine but must have randomly stopped...? Im running RedHat x86_64 es5.
EDIT: maybe I am doing this wrong. What command do I need to run to check if memcached is running?
Answer: first make sure you have the memcache user
id memcached

you have an error in your config.. looks like a dos line breaks.. Run the following command over the memcache sysconfig script
dos2unix /etc/sysconfig/memcached

Comment: dos2unix resolved my problem
Answer: How did you install memcached?
You should be able to run:
service memcached status

or
lsof -i :11211

or
ps -ef | grep memcache

to see if it's running.
Cheers

Memcached is not launching


Linux high memory usage (top total mismatch)

Question: I havea poor mans vps - 256MB dedicated RAM.  I have installed LAMP. No website is currently UP on the server yet.
The memory usage is still 225MB (only 31 MB free).
I have measured using top and another method. Top says around 225mb used, but if I sum up the processes, it comes to be only 20%.
Another script I am using to measure the memory:
<code>#!/bin/bash
bean=`cat /proc/user_beancounters`
guar=`echo "$bean" | grep vmguar | awk '{ print $4;}'`
priv=`echo "$bean" | grep privvm | awk '{ print $2;}'`
let totl=guar/256
let used=priv/256
let free=$totl-$used
echo "VPS Memory:"
echo "  total: $totl mb   used: $used mb   free: $free mb"
</code>
gives same result (225MB used).
I have rebooted the server, but still 225MB memory is being used. How can I find the culprit process. please help!
============
Output of ps efax -o command,vsize,rss,%mem,size indicates that only 20% (aournd 50MB) is actually used by processes.
(apt-get install imagemagick is failing because of low RAM. I guess I need to go for higher memory like 512 MB. I thought the failure might be due to this "spurious" memory usage).
Is there any way to know if the memory is indeed available as cache (top shows buffer/cach as 0 - I heard that if the RAM was available as cache, it would appear as "bufffers or cache).
Output of free -m:
<code>free -m
             total       used       free     shared    buffers     cached
Mem:           256        226         29          0          0          0
-/+ buffers/cache:        226         29
Swap:            0          0          0
</code>
Its showing free buffers/cache  also as on 29 MB :(
Comment: what does free -l tell you?
Comment: xyz@pqr:~$ free -l
             total       used       free     shared    buffers     cached
Mem:        262144     232056      30088          0          0          0
Low:        262144     232056      30088
High:            0          0          0
-/+ buffers/cache:     232056      30088
Swap:            0          0          0
Answer: Linux will use as much ram as it can as cache which will be given up if other processes require more memory. Have a look here for some more information.
Comment: That site says it better than I ever could have.  Thanks for posting it.
Comment: Is there any way to know if the memory is indeed available as cache (top shows buffer/cach as 0 - I heard that if the RAM was available as cache, it would appear as bufffers or cache).
Comment: As I added in the question, "free -m" shows that even buffer/cache free memory is 29 MB. According to http://www.linuxatemyram.com/, if RAM was really available, it would show as free in the buffer/cache line. Am I missing something?
Answer: try using from following link how is use by which process and update back
http://studyhat.blogspot.com/2010/09/memory-use-by-which-process-centos-rhel.html
Answer: Try these commands

top -n 1

or

ps efax -o command,vsize,rss,%mem,size

The answers to this question on superuser.com also can be of help
"How can I display the memory usage of each process if I do a ps ef"
Comment: Its giving a list of about 20 processes (cant add as comment due to msg limit). However, the sum of the memory usage is around 20% (same with output of top). I am now thinking that it is indeed that linux is using the ram as "cache".
Answer: Guys, thanks to all for responding. Turned out mysql was using 139MB of "virtual memory". As my VPS does not have SWAP enabled, virtual memory was being taken from the RAM.
(And TOP doesnt display virtual memory in the % usage column -so  missed it completely!).
Did two good things to reduce the memory requirement :
1) skipd-innodb in /etc/mysql/my.cnf
2) systemwise ulimit of 256  in /etc/rc
(it was unlimited earlier on causing huge memory footprint).
cheers,
JP


Why can I only view content published to current domain?

Question: I'm using the Administration Views modules and Domain Access. When I'm logged in as the Administrator (user 1) I can view any content across all domains at /admin/content no matter what domain I'm on.
When I'm logged in as another role (Role X), who has permission to edit any content on any domain I can only see content published to the current domain. What permission or view setting or other setting do I need to apply to allow Role X to see content published on any domain no matter what domain they're on?
The only way Role X can see everything is if I give them the "Bypass content access control" permission, which I'd rather not.
Answer: After researching the api and reading up on how the permissions work (here) it looks as if the Node Access module limits a user (who is not user 1) to only be able to see content of the domain of which they belong, regardless of their editing permissions. You could, however, play around with grants (specifically grant_edit) to try and override the active domain. I would suggest some custom script to allow Role X grant_edit, or bite the bullet and use the "Bypass content access control" permission.
I understand this probably isn't the answer you wanted, however hopefully it helps in some way!


How to Audio Classification in Android give input Audio file?

Question: I Classify a audio file in android use live recording. But I want to classification get a Audio file from android internal or external storage. How do this work? Please help me.
My mainActivity code is given below, that are->
MainActivity.kt
package com.example.mysoundclassification

import android.Manifest
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.tensorflow.lite.task.audio.classifier.AudioClassifier
import java.util.*
import kotlin.concurrent.scheduleAtFixedRate

class MainActivity : AppCompatActivity() {

    var probabilityThreshold: Float = 0.3f

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val showResult = findViewById<TextView>(R.id.output)

        //Permission For Record
        val REQUEST_RECORD_AUDIO = 1337
        requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), REQUEST_RECORD_AUDIO)

        //Load TFLite model
        val audioClassifier = AudioClassifier.createFromFile(this, "my_birds_model.tflite")

        //Real Time Audio Record
        val audioRecord = audioClassifier.createAudioRecord()
        audioRecord.startRecording()

        //Use Thread
        Timer().scheduleAtFixedRate(1, 1000) {
            //Classify Sound
            val  tensorAudio= audioClassifier.createInputTensorAudio()
            tensorAudio.load(audioRecord)/** Here,Pass live Record audio data.But,
            ** I want pass here my audio file.
            ** How do this work??
            ** Please help me.
            */
            //Result
            val output = audioClassifier.classify(tensorAudio)

            //*** Start Specifying output....
            //  Check if it's a bird sound.
            var filteredModelOutput = output[0].categories.filter {
                it.label.contains("Bird") && it.score > probabilityThreshold
            }
            //  given there's a bird sound, which one is it?
            if (filteredModelOutput.isNotEmpty()) {
                Log.i("Yamnet", "bird sound detected!")
                filteredModelOutput = output[1].categories.filter {
                    it.score > probabilityThreshold
                }
            }
            val outputStr = filteredModelOutput.sortedBy { -it.score }
                .joinToString(separator = "\n") { "${it.label} -> ${it.score} " }
            if (outputStr.isNotEmpty())
                runOnUiThread {
                    showResult.text = outputStr
                }
            Log.i("output", ""+output[0])
            //*** End Specifying output
        }//End thread

    }//End onCreate method

}//End MainActivity

Now the next code is xml file that are->
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/output"
        android:layout_width="299dp"
        android:layout_height="105dp"
        android:gravity="center"
        android:lines="5"
        android:text="Play your audio!"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.424" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Recording"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toTopOf="@+id/output"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.194" />

</androidx.constraintlayout.widget.ConstraintLayout>

Need for permission for this work is audio record->
permission
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Thanks..please Help, This problem solve is very important for me!!!
Answer: Instead of using tensorAudio.load(audioRecord: AudioRecord), you can similarly use tensorAudio.load(data: FloatArray). You would load the data from internal/external storage into the data variable by reading a file as you would normally in Android.
Keep in mind that, in such a case, your recorded files should be encoded using ENCODING_PCM_FLOAT, so you might need to adjust your input data to fit this format. In case you are obtaining the data via MediaRecorder or AudioRecord you should be able to specify the output file format as ENCODING_PCM_FLOAT when you initialize the object. In case you are not, maybe you could browse for sound processing libraries for your specific use case, as I'm afraid I haven't found any options to help you.
Please consider writing your concrete steps in a separate answer if you manage to  solve the problem. Thanks!
Answer: use google's audio task lib: https://www.tensorflow.org/lite/inference_with_metadata/task_library/audio_classifier
// Initialization
AudioClassifierOptions options =
    AudioClassifierOptions.builder()
        .setBaseOptions(BaseOptions.builder().useGpu().build())
        .setMaxResults(1)
        .build();
AudioClassifier classifier =
    AudioClassifier.createFromFileAndOptions(context, modelFile, options);

// Start recording
AudioRecord record = classifier.createAudioRecord();
record.startRecording();

// Load latest audio samples
TensorAudio audioTensor = classifier.createInputTensorAudio();
audioTensor.load(record);

// Run inference
List<Classifications> results = audioClassifier.classify(audioTensor);

Comment: `audioClassifier.classify` should be changed to `classifier.classify`
Comment: How to pass model metadata like input output shapes? Any way with AudioClassifierOptions ?
Comment: @SazzadHissainKhan, audio task is for realtime AudioRecord input, you can implementation 'org.tensorflow:tensorflow-lite:2.8.0' for file input. And th input is fixed like this doc says: # Input: 0.975 seconds of silence as mono 16 kHz waveform samples. (https://www.kaggle.com/models/google/yamnet/frameworks/tfLite)
Comment: I am getting error. Could you please help in this regards, https://stackoverflow.com/q/77578234/1084174


How to generate a unique object hash based on the class attributes?

Question: I have a model with different attributes. Not every instance has a value for each attribute.
class Location

  attr_accessible :name,     # string, default => :null
                  :size,     # integer, default => 0
                  :latitude, # float, default => 0
                  :longitude # float, default => 0

  # Returns a unique hash for the instance.
  def hash
   # ...
  end

end

How can I implement a hash function which returns a unique id for an instance? It should be the same every time I invoke the hash function on the object. I do not want a random unique id. It should be possible to store the hash in a sqlite3 database without modification.

As you can read in an answer by MetaSkills it is not a good idea to overwrite the hash method since it "is used by a ton of ruby objects for comparison and equality". I will therefore rename it to custom_attributes_hash.
Answer: require 'digest/md5'

class Location

  attr_accessor :name,     # string, default => :null
                  :size,     # integer, default => 0
                  :latitude, # float, default => 0
                  :longitude # float, default => 0

  # Returns a unique hash for the instance.
  def hash
    Digest::MD5.hexdigest(Marshal::dump(self))
  end

end

test with pry
[1] pry(main)> foo = Location.new;
[2] pry(main)> foo.name = 'foo';
[3] pry(main)> foo.size = 1;
[4] pry(main)> foo.latitude = 12345;
[5] pry(main)> foo.longitude = 54321;
[6] pry(main)>
[7] pry(main)> foo.hash
=> "2044fd3756152f629fb92707cb9441ba"
[8] pry(main)>
[9] pry(main)> foo.size = 2
=> 2
[10] pry(main)> foo.hash
=> "c600666b44eebe72510cc5133d8b4afb"

Or you could also create your customize function for serializing the properties. for example to use all of the instance variable
def hash
  variables = instance_variables.map {|ivar| instance_variable_get(ivar)}.join("|separator|")
  Digest::MD5.hexdigest(variables)
end

or to select the one you need
def hash
  variables = [name, size].join("|separator|")
  Digest::MD5.hexdigest(variables)
end

Comment: Nice. Is there a way I can define which attributes are involved to build the hash?


What are the effects of having the TLS certificate and private key in same file?

Question: I have noticed that a number of different web and mail server software allow or require you to provide the TLS certificate (including server certificate, CA intermediate certificate, and CA root certificate) and private key in a single .pem file.
So, the server sends the certificate(s) to every client attempting to connect, but, of course, you want to keep your private key secure and secret. So, how does this work when they are all in the same file? Does the software know to only send the certificate parts and never send the private key, even though they are in the same file?
Thank you.
Answer:
Does the software know to only send the certificate parts and never send the private key, even though they are in the same file?

Yes.
Comment: In the same way you put several things into one file, the server can open the file and take the things out separately. A PEM file is one way of many to give information to the server (see http://serverfault.com/a/9717/57144 ). When you make an SSL connection, you are not transferring 'files' from web server to browser, but SSL connection data. Files only exist on filesystems and file sharing connections like NFS. When a file is opened, the content can be used and split and processed any way the software wants, it doesn't all have to stay together in one lump.
Comment: Almost certainly yes. http://stackoverflow.com/a/7539644
Comment: Thanks. Is there a simple way for you to elaborate on how this works?
Comment: Thanks again. Maybe it uses the -----Begin ...----- and -----End ...----- declarations to help it determine what parts to send what parts not to send?
Answer:
So, the server sends the certificate(s) to every client attempting to connect, but, of course, you want to keep your private key secure and secret.

If you don't trust the software which you are providing your PEM file to, you can encrypt the key before writing it to the PEM file.  This will prevent anyone from using it without the passphrase.
The OpenSSL rsa command uses the -in to designate the input file, and -out to designate the encrypted output file.  You need to also pass it the cipher.  A sample command looks like this:
openssl rsa -AES256 -in key.pem -out encryptedKey.pem

You will be prompted for the passphrase.  Now you can append encryptedKey.pem to your public certificate PEM, and be fairly confident that it will be safe from all bu the most determined attackers.
Note that this uses the AES256 cipher.  It is your responsibility to use a cipher that is modern and secure.
When you need to use that key at the command line, OpenSSL will prompt you for the passphrase.  Libraries like pyOpenSSL have overridden signatures that take a cipher and passphrase for encrypting the key, and which take only a passphrase for decrypting the encrypted key.


Docker unable to copy files to mounted volume

Question: I am unable to run this command on jenkins, but i am able to run this same command on the windows powershell
16:13:55  + docker run -v /opt/jenkins/workspace/tas/zigbee-gateway/hostoutput/:/home/jenkins/output_to_host tas-gateway cp -a /home/jenkins/output/. /home/jenkins/output_to_host
16:13:55  cp: cannot create regular file '/home/jenkins/output_to_host/./Gateway_INTL_1.0.4-10_ramips_24kec.ipk': Permission denied
16:13:55  cp: cannot create regular file '/home/jenkins/output_to_host/./Gateway_CN_1.0.4-10_ramips_24kec.ipk': Permission denied
16:13:55  cp: cannot create regular file '/home/jenkins/output_to_host/./Gateway_TEST_1.0.4-10_ramips_24kec.ipk': Permission denied
16:13:55  cp: preserving times for '/home/jenkins/output_to_host/.': Operation not permitted

What am I missing out? the jenkins is run on amazon linux
Answer: It looks like Jenkins' user does not have write permission to the specified folder.
edit: please try
sudo usermod -aG docker jenkins

Comment: If they are using PowerShell probably they don't have `sudo` or `usermod`.
Comment: no @tripleee my local is windows, the remote jenkins is linux
Comment: Yeah so your local computer probably doesn't have `sudo` or `usermod`, does it?
Comment: @MosesLiaoGZ - information which should be in the question, as the solution will be different on a Windows host.


Duplicate rows based on quantity value

Question: I'm using Microsoft's Access as a platform to run SQL and I'm attempting to get the following output based on a query:
For example, take the following row:
A | B | C | 3

From that row, I would like to get 3 rows, as the following:
A | B | C | 1
A | B | C | 1
A | B | C | 1

"3" is the quantity in the example above.
Thanks in advance!
Comment: @Luuk - I don't think that this will work for the OP, as I think that what is being asked for is repeat A/B/C with a quantity of 1 for however many times indicated in the original data.
Comment: What have you got so far?
Comment: I have an existing table with many fields that only a few of which interest me.
I need to "break" the line to x lines (based on the quantity) in order to run a different query which will allow me to create a relation between a deliveries table to a sales table
Comment: I might by wrong, but I guess you don't need to have those lines split up. Maybe a normal `INNER` or `LEFT JOIN` will do the job. Better post your original tables and tell the required relation.
Comment: `SELECT 'A','B','C',quantity/3 UNION ALL SELECT 'A','B','C',quantity/3 UNION ALL SELECT 'A','B','C',quantity/3`
Comment: @Luuk the value 3 was just an example, I have different Quantities by which I'm interested in duplicating the rows
Comment: @AppsBoss7 - is a VBA solution that takes the original data and spits it out to a separate table for further processing acceptable?
Comment: @Applecore Yeah, if it does the job it will be great
Answer: Below is a VBA solution that opens a recordset based on the original table ("tblData"), and then loops each record as many times as needed inserting the required information into a temp table ("tblTempData"):

Sub sSplitData()
    On Error GoTo E_Handle
    Dim db As DAO.Database
    Dim rsSteer As DAO.Recordset
    Dim rsData As DAO.Recordset
    Dim lngLoop As Long
    Set db = DBEngine(0)(0)
    Set rsSteer = db.OpenRecordset("SELECT * FROM tblData;")
    If Not (rsSteer.BOF And rsSteer.EOF) Then
        db.Execute "DELETE * FROM tblTempData;"
        Set rsData = db.OpenRecordset("SELECT * FROM tblTempData WHERE 1=2;")
        Do
            For lngLoop = 1 To rsSteer!Quantity
                With rsData
                    .AddNew
                    !Field1 = rsSteer!Field1
                    !Field2 = rsSteer!Field2
                    !Field3 = rsSteer!Field3
                    !Quantity = 1
                    .Update
                End With
            Next lngLoop
            rsSteer.MoveNext
        Loop Until rsSteer.EOF
    End If
sExit:
    On Error Resume Next
    rsData.Close
    rsSteer.Close
    Set rsData = Nothing
    Set rsSteer = Nothing
    Set db = Nothing
    Exit Sub
E_Handle:
    MsgBox Err.Description & vbCrLf & vbCrLf & "sSplitData", vbOKOnly + vbCritical, "Error: " & Err.Number
    Resume sExit
End Sub

Regards,
Comment: Thanks for the answer.
However, the VBA isn't working for me, I keep getting an error saying
"User-defined type not defined" over the DAO.DataBase line.
I changed the tblData in the " " to Deliveries (the name of the table) but it isn't working.
Do you have any idea in regards to what I should do?
Thanks in advance.
Comment: You need to add a reference to DAO. From a module, select Tools|References, and then select "Microsoft DAO" from the list of available references.
Comment: Ok, I added that.
What else should I change? Because it says that it can't find sSplitData, and when I change it (in the quotes) to "Quantity", the name of the column to split, it isn't working
Comment: "Quantity" is the field in table "Deliveries" that has how many times you want the records to be repeated. `rsSteer!Field1` is the first piece of data in "Deliveries" to be repeated.
Comment: I created a new question with what I specifically need, if you can answer it instead since this probably won't entirely solve my problem I will really appreciate it.
Thanks either way for the attempt to help!
https://stackoverflow.com/questions/61546279/combine-two-tables-into-one
Answer: If you have a separate table of numbers -- which can be quite helpful under many circumstances -- you can use:
select t.a, t.b, t.c, 1
from t inner join
     numbers as n
     on n.n <= t.cnt;

Unfortunately, there is no really efficient way to create such a table in the same SQL statement.  You can create such a table using an identity column (I don't think MS Access has gaps in identity columns).

Duplicate rows based on quantity value


Do I need FIS-based switching for Linux software RAID when *not* using a port multiplier?

Question: I'm planning to build a home NAS with an ASRock AM1H-ITX with four S-ATA disks.
According to the manual the board features two S-ATA controllers:
<code>2 x SATA3 6.0 Gb/s Connectors by AMD AM1 Series Socket 25W Quad-Core APU, support NCQ, AHCI and Hot Plug
2 x SATA3 6.0 Gb/s Connectors by ASMedia ASM1061, support NCQ, AHCI and Hot Plug
</code>
It seems the ASMedia ASM1061 controller doesn't support "FIS-based switching", but I don't fully understand if this is a problem if I'm not using a port multiplier?
I will connect four WD RED WD30EFRX 3TB S-ATA 6 drives to those ports and use them with a Linux software RAID.
Answer: You are correct in your assumption that, if you are not using a port multiplier, then lack of support for FIS-based switching is not applicable to your scenario.


The limit of locally integrable functions

Question: If ${f_i} \in L_{\rm loc}^1(\Omega )$ with $\Omega $ an open set in ${\mathbb R^n}$ , and ${f_i}$ are uniformly bounded in ${L^1}$ for every compact set, is it necessarily true that there is a subsequece of ${f_i}$ converging weakly to a regular Borel measure?
Comment: Isn't the second condition the same as the first?
Answer: Take $K_j$ a sequence of compact sets such that their interior grows to $\Omega$.
That is, $\mathrm{int}(K_j) \uparrow \Omega$.
Let $f_i^0$ be a sub-sequence of $f_i$ such that $f_i^0|_{K_0}$
converges to a Borel measure $\mu_0$ over $K_0$.
For each $j > 0$, take a sub-sequence $f_i^j$ of $f_i^{j-1}$ converging
to a Borel measure $\mu_j$ over $K_j$.
It is evident, from the concept of convergence, that for $k \leq j$,
and any Borel set $A \subset K_k$,
$\mu_j(A) = \mu_k(A)$.
Now, define $\mu(A) = \lim \mu(A \cap K_j)$. And take the sequence $f_j^j$.
For any continuous $g$ with compact support $K$, there exists $k$ such that $K \subset \mathrm{int}(K_k)$ (why?). Then, since for $j \geq k$, $f_j^j|_{K_k}$ is a sequence that converges to $\mu_k$,
$$
  \int_{K_k} g f_j^j \mathrm{d}x
  \rightarrow
  \int_{K_k} g f_j^j \mathrm{d}\mu_k
  =
  \int g f_j^j \mathrm{d}\mu.
$$
That is, $f_j^j \rightarrow \mu$.
Comment: I have thought like this too, but how can you say μ is a measure? Moreover, how can you prove that μ is a regular Borel measure.
Comment: @Adterram: What is a regular measure? I guess that every measure over Borel sets of $\mathbb{R}^n$ is regular.
Comment: @Adterram: I guess the only trouble is showing that $\mu$ is $\sigma$-additive. Just take a sequence of disjoint measurable $A_n$. Now, $\mu(\bigcup_n A_n) = \lim_j \mu_j(K_j \cap \bigcup_n A_n) = \lim_j \sum_n \mu_j(A_n \cap K_j)$. Now, since we have only positive terms, we can exchange $\sum$ and $\lim$ (monotone convergence!) and get $\mu(\bigcup_n A_n) = \sum_n \lim_j \mu(K_j \cap A_n) = \sum_n \mu(A_n)$.


Find a row and its index then delete this row using index

Question: I would looking for a way to basically delete, step by step, a specific row.
      categorie     note    nbavis  taille      nbdll       type    prix    genre
10  ART_AND_DESIGN  4.1     159     19000000    10000       Free    0       Art & Design
15  ART_AND_DESIGN  3.9     967     14000000    500000      Free    0       Art & Design
16  ART_AND_DESIGN  4.7     87510   8.7000000   5000000     Free    0       Art & Design
17  ART_AND_DESIGN  4.5     215644  25000000    50000000    Free    0       Art & Design
28  ART_AND_DESIGN  4.3     967     2.8000000   100000      Free    Everyone Art & Design

After deleting some row because of NaN, id's are different than index.
So, I used :
app.loc[app['prix']=='Everyone',:]

To learn more about which row contains "Everyone" in the column "prix".
Now I would like to find the index of this row which is different from 28 (On this example, it's 4, python count from 0 right ?)
I tried :
app.index[app['prix'] == 'Everyone'].tolist()

But the result give me [28].
Then I tried
app.loc[app.index==28]

Same result.
app.index[28] will told me :
IndexError: index 28 is out of bounds for axis 0 with size 5

I'm pretty sure I have missed something. There are many ways to do it, but I would like to do it with this approach. For exemple .drop , del , ...
There are many topics, but none fits with these conditions. Maybe it's not possible. How would you do this with few code lines?
Thanks
EDIT :
There are the solutions I was looking for :
♣ Reset the Index
app = app.reset_index()

♣ Find the rows (and the index)
app.loc[app['prix']=='Everyone',:]

♣ Delete this row using the index
app = app.drop(4795)

◘ Other solution was : app.drop([28])
Thanks to this community. And thanks for the Edit of my topic, my english is horrible ahah.
Comment: Do you want to delete the rows that has value "Everyone" for column "prix?"
Comment: @iamchoosinganame yes !
And I would like to do it by using row's index wich is different than delete a row with a condition. But I'm interrested in this too ahah
My problem is that I can't find the good index, and I don't know how to delete a row using inded
Comment: does `df.drop(28)` work? also are you sure the index is a number not a string `'28'`?
Comment: it worked !
Thanks. I had to reset the index to find the good row, then drop it worked !
Answer: Assuming you want to exclude the rows where prix equals "Everyone."
new_df = app.loc[app['prix']!='Everyone']

new_df is a slice of app. You can make it a new object by using copy
new_df = app.loc[app['prix']!='Everyone'].copy()

Comment: Hi Thanks for your comment ! That's the easiest way, so that's good. But there, just to form myself, I would like to do this without creating a new data
Answer: To drop the row inplace:
app.drop(app[app['prix']=='Everyone'].index, inplace=True)

Answer: Try this:
for r in app.iterrows():
     if r[1]['prix']=='Everyone':
           print(r[0])

With iterrows() method you can print the index by r[0], and the columns will be in r[1],
if yoy want to set a column as a index you can use:
app.set_index("Column Name")

Answer: The 28 is the row identifier of the dataframe. It was originally (before you removed NA) the 28th row (29th I suppose because of the zero-based indexing). You can drop the row based on that id.
app.drop([28])

Comment: Aaah that slove my problem ! Thanks !


JPQL Many-to-many Dto select failure

Question: I want to write JPQL query for selecting a DoctorDto from my  AppUserRepository. There is a many-to-many relationship between AppUser and Specialization entity. The two entities are presented below:
@Entity
@Table(name = "app_user")
public class AppUser  {

    @ManyToMany
    @JoinTable(name = "doctor_specialization", joinColumns = {@JoinColumn(name = "app_user_id")}, inverseJoinColumns = {@JoinColumn(name = "specialization_id")})
    private Set<Specialization> specializations;

}

@Entity
@Table(name="specialization")
@NoArgsConstructor
public class Specialization {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

}

I have created a DoctorDto object:
@Getter
@Setter
@NoArgsConstructor
public class DoctorDto {

   private Set<Specialization> specializations;

   public DoctorDto(Set<Specialization> specializations){
      this.specializations = specializations;
   }

}

I would like to select all the doctors with their specializations from my AppUserRepository. In order to do that, I have written the following JPQL query:
 @Query("select new com.my-package.DoctorDto(u.specializations) from AppUser u")
 List<DoctorDto> getDoctors();

However, I am receiving an error:
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'as'.

The Hibernate query looks as follows:
Hibernate: select . as col_0_0_ from app_user appuser0_ inner join doctor_specialization specializa1_ on appuser0_.id=specializa1_.app_user_id inner join specialization specializa2_ on specializa1_.specialization_id=specializa2_.id

As you can see, it seems that specializations are not detected by Hibernate. Everything works perfectly fine without Dto mapping. What is the reason for this error? How can I fix it? Thanks in advance.
Comment: I think you cannot get collections like that. You will have to explicity join tables in your query
Comment: Can you specify how you would implement this? When it comes to non-Dto examples such as: "select u.specializations from AppUser u", it works fine. I have tried joining tables in my query, but without success.
Comment: Try one these work arounds.
https://stackoverflow.com/questions/52452550/load-child-collection-dtos-in-jpa-dto-projection-query
Answer: That's not possible out of the box like bluelurker answered already, but I think this is a perfect use case for Blaze-Persistence Entity Views.
I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.
A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:
@EntityView(AppUser.class)
public interface DoctorDto {
    @IdMapping
    Long getId();
    Set<SpecializationDto> getSpecializations();

    @EntityView(Specialization.class)
    interface SpecializationDto {
        @IdMapping
        Long getId();
        String getName();
    }
}

Querying is a matter of applying the entity view to a query, the simplest being just a query by id.
DoctorDto a = entityViewManager.find(entityManager, DoctorDto.class, id);
The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
Page<DoctorDto> findAll(Pageable pageable);

The best part is, it will only fetch the state that is actually necessary!

JPQL Many-to-many Dto select failure


How do I retain extras in an Intent, when the appliction is not loaded on the device

Question: I have an application that receives notifications from MyFirebaseMessagingService. The intent for the notification is set to the Login activity which also the Launcher/Main activity from the manifest. I am doing this so that if the user is not logged in, it requires a login before viewing the content/result of the notification.
When the application is running, everything works fine (the extras are attached to the intent) and I forward it to the destination activity using another intent.
When the application is NOT running, it launches the application, without the extras. A bundle object for the extras exists but does not have any of the original extras in it.
The following is my code for the generation of the intent from MyFirebaseMessagingService.
public void sendCheckInNotification(Context context, String messageBody, String messageTypeIn, String messageIdIn) {
        generateRequestCode(messageIdIn);
        Log.i(TAG, "MyFirebaseMessagingService: " + messageTypeIn + " " + messageIdIn + " sendCheckInNotification: ");
        sendingActivity = "NewCheckInNotification";
        Log.i(TAG, "MyFirebaseMessagingService sendCheckInNotification: sendingActivity= " + sendingActivity);
        Intent intent = new Intent (context,  Login.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("checkInTablePrimaryKey", assignedCheckInTablePrimaryKey);
        intent.putExtra("checkInTableFirebaseKey", checkInTableFirebaseKey);
        intent.putExtra("sendingActivity", sendingActivity);
        Log.i(TAG, "MyFirebaseMessagingService sendCheckInNotification: extras added=  " + sendingActivity);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            pendingIntent = PendingIntent.getActivity(context, requestCode, intent,
                    PendingIntent.FLAG_IMMUTABLE); }
        else {
            pendingIntent = PendingIntent.getActivity(context, requestCode, intent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

        String channelId = context.getResources().getString(R.string.new_check_in_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(context, channelId)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle(context.getResources().getString(R.string.check_in_notifications_header))
                        .setContentText(messageBody)
                        .setStyle(new NotificationCompat.InboxStyle())
                        .setAutoCancel(true)
                        .setContentIntent(pendingIntent)
                        .setGroup(NEW_CHECK_IN_NOTIFICATION_GROUP)
                        .setSound(defaultSoundUri);

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

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "New CheckingIn Notification",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(requestCode /* ID of notification */, notificationBuilder.build());
}

The following is the code for the receipt of the notification.  It finds a bundle for the object, but the extras are missing.
 extras = getIntent().getExtras();
        Log.i(TAG, "Login onCreate: extras= " + extras);
        if (extras != null) {
            sendingActivity = extras.getString("sendingActivity");
            Log.i(TAG, "Login onCreate: sendingActivity = " + sendingActivity);
            if (user != null) {
                Log.i(TAG, "Login onCreate: user is not logged in for notification");
                if ((sendingActivity.equals("NewCheckInNotification")) ||
                   (sendingActivity.equals("PeepsWatcherUpdateNotification")) ||
                   (sendingActivity.equals("CheckInUpdateNotification")) ||
                   (sendingActivity.equals("CheckInLocationProvidedNotification")) ||
                   (sendingActivity.equals("NewCheckInLocationRequestNotification")) ||
                   (sendingActivity.equals("NewCheckInRequestNotification")) ||
                   (sendingActivity.equals("NewCheckInRequestUpdateNotification")) ||
                   (sendingActivity.equals("NewCheckInChatMessageNotification")) ||
                   (sendingActivity.equals("NewCheckInPicturesNotification"))) {
                    Log.i(TAG, "Login onCreate: extras exist ");
                    setIntentForNextActivity();
                }
                else {
                        Log.e(TAG, "Login onCreate: unknown sendingActivity for Intent " + sendingActivity);
                    }
            }
            else {
                Log.i(TAG, "Login: user not logged in"  );
                String message = "You will be directed to your notification after logging in";
                CustomToast newtoast = new CustomToast(context,message);
                newtoast.show();
            }
        }

The following is the manifest entry for the launcher activity
 <activity
            android:name="Login"
            android:exported="true"
            android:label="Peeps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Comment: You can use ```BroadcastReceiver``` for this purpose.
Comment: Where does `requestCode` come from, and is it always unique?
Comment: Also, you might want to add some debug logging to log the extras that are in the `Intent`. It is interesting that there is a `Bundle`, but it doesn't have the extras you are expecting. If you log the extras, that may help figure out where they come from. You can do this by iterating over all the extras in the `Bundle` and log them to logcat.
Answer: Modify the intent flags in your sendCheckInNotification, method to include Intent.FLAG_ACTIVITY_CLEAR_TOP as below-
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

In the receiving activity's onCreate method, override the onNewIntent method and call setIntent with the new intent
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}

Retrieve the extras in the receiving activity's onCreate method after calling setIntent
extras = getIntent().getExtras();

Make your receiving activity singletop as below-
<activity
    android:name="Login"
    android:exported="true"
    android:label="Peeps"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Comment: I tested with what you recommended. The onNewIntent never gets called.    @Override
    protected void onNewIntent(Intent intent) {
        Log.i(TAG, "Login onNewIntent: ");
        super.onNewIntent(intent);
        setIntent(intent);
        extras = intent.getExtras();
        Log.i(TAG, "Login onNewIntent: extras= " + extras);
        if (extras != null) {
            sendingActivity = extras.getString("sendingActivity");
............. more code
Comment: I changed it to force the call to onNewIntent from within the onCreate for the launcher activity.  The extras are null on the intent.
Comment: The extras exist on the intent when sending from MyFirebaseMessaging serivce, but when it gets to the receiving activity (launcher activity), the extras are gone.
Comment: try to make activity singleTop
Comment: It is single top
Comment: I think you doing mistake  in your code. try to debug step by step.


Delphi 11.2 Bluetooth permision not granted

Question: Running on an Android 12 device.
Worked fine in Delphi 11.1.
I have two apps in use.
In only one of the two, I can not seem to get Bluetooth permision granted.
I have set the Fine Location, which is accepted on initial install.
I only require basic Bluetooth, and Bluetooth Admin.
When going through the requests one at the time (instead of all in one go) this fails permanently:
PermissionsService.RequestPermissions([cPermissionBluetooth], TakeBluetoothPermissionsResultHandler, DisplayRationale);

And, the DisplayRationale never works at all.
During startup, there is no other User request from the system.
In Setup>Apps there is no specific reference to Bluetooth.
It does not tell me why it fails.
According to
https://developer.android.com/guide/topics/connectivity/bluetooth/permissions
I have got all related settings okay (including the Location).
Targeting 'android:maxSdkVersion="30"' which is set by the compiler as default.
In my other App, which is much more complicated, with the same Bluetooth/Location settings, it works normally.
What could I have missed?
UPDATE:
I now changed the code to this:
const
cPermissionBluetooth = 'android.permission.BLUETOOTH';
  cPermissionBluetoothAdmin = 'android.permission.BLUETOOTH_ADMIN';
  cPermissionBluetoothConnect = 'android.permission.BLUETOOTH_CONNECT';
  cPermissionBluetoothScan = 'android.permission.BLUETOOTH_SCAN';

procedure TMainForm.TakeBluetoothPermissionsResultHandler(Sender: TObject; const APermissions: TClassicStringDynArray; const AGrantResults: TClassicPermissionStatusDynArray);
begin
  // if TGrantResults(AGrantResults).AreAllGranted then
  if PermissionsService.IsPermissionGranted(cPermissionBluetooth) then
  begin
    DoLog('cPermissionBluetooth: Granted');
  end else
  begin
    DoLog('cPermissionBluetooth: NOT Granted!',d_error);
  end;

  if PermissionsService.IsPermissionGranted(cPermissionBluetoothConnect) then
  begin
    DoLog('cPermissionBluetoothConnect: Granted');
  end else
  begin
    DoLog('cPermissionBluetoothConnect: NOT Granted!',d_error);
  end;

  if PermissionsService.IsPermissionGranted(cPermissionBluetoothScan) then
  begin
    DoLog('cPermissionBluetoothScan: Granted');
  end else
  begin
    DoLog('cPermissionBluetoothScan: NOT Granted!',d_error);
  end;
end;

And what happens is that the basic android.permission.BLUETOOTH is NOT granted, but the other two are. And Bluetooth actually works.
Does this mean that I am NOT allowed to call android.permission.BLUETOOTH if running on Android 12 or higher? And that I now must specifically look at the Android version, and NOT call that when 12 or higher??
Why does it work normally in my primary App then..?
Right now, I cannot call 'Are all Permissionas Granted' because one fails all the time.
PS: Why can I not use the build-in "TPermissionsService.IsEveryPermissionGranted"? It is imcompatible with its own Android code!
UPDATE2:
The final is like this:
   <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

The one which permanently is NOT granted (in Android 12) is: "android.permission.BLUETOOTH".
(I made a mistake in one of my comments about this).
If I ignore this, the Bluetooth does work normally.
Comment: Android 12 requires additional permissions: https://developer.android.com/guide/topics/connectivity/bluetooth/permissions
Comment: android.permission.BLUETOOTH is not applicable to Android 12, as per the documentation you linked to, so it will not grant it. You need to have a check for the version, e.g. `if TOSVersion.Check(12) then` to exclude that permission when requesting
Comment: It looks that has to be done then.
Comment: That is the link I also have in my question. I do not use any of the options link 'SCAN'. I did try to add the 'BLUETOOTH_CONNECT' but it made no difference. My primary SARTrack App does not have any of these either; I cannot see any difference between the two; But one works and the other keeps failing in Bluetooth, and without any specific warning or action from the OS. I get exactrly the same three questions on install: Access photos & Media; Take pictures; Location (fine). All okay. Then Bluetooth Permision keeps  failing...
Comment: This code: `PermissionsService.RequestPermissions([cPermissionBluetooth]` is requesting only *one* permission.
Comment: Yes, only because of the testing. To be able to detect *which* one is failing. And that is the very one, in Android 12. And I have now changed it again to do them all at the same time; but *excluding* 'BLUETOOTH_CONNECT' because that keeps sayting NO GRANTED. (While the Bluetooth system itself works fine if I ignore it).
Comment: "While the Bluetooth system itself works fine if I ignore it" Does this mean the issue is solved? If not, please check that you have `Bluetooth connect` checked in the Use Permissions list in the Project Options
Comment: I updated the question agin, Update2. The problem is with "android.permission.BLUETOOTH" (NOT with 'CONNECT' as I earlier posted, that was a typo).
Comment: Again, does this mean the issue is solved?
Answer: I had to change my code like this:
if TOSVersion.Major < 12 then
          begin
            LogClient('TOSVersion.Major < 12');
            PermissionsService.RequestPermissions([cPermissionReadExternalStorage,
              cPermissionWriteExternalStorage, cPermissionLocation, cPermissionBluetooth, cPermissionCamera],
              TakeGeneralPermissionsResultHandler, DisplayRationale);
          end else
          begin
            LogClient('TOSVersion.Major >= 12');
            PermissionsService.RequestPermissions([cPermissionReadExternalStorage,
              cPermissionWriteExternalStorage, cPermissionLocation, cPermissionBluetoothConnect, cPermissionBluetoothScan, cPermissionCamera],
              TakeGeneralPermissionsResultHandler, DisplayRationale);
          end;


AWS route 53 database hostname best practice

Question: So I have 3 components all connecting to same db. Should I use:
comp1.domain.io
comp1db.domain.io

comp2.domain.io
comp2db.domain.io

comp3.domain.io
comp3db.domain.io

Or:
comp1.domain.io
comp2.domain.io
comp3.domain.io
db.domain.io

EDIT: I am wondering if the ease of API accessible Route 53 hostnames makes it more beneficial to create hostnames for the db server per application. This means if I need to transfer the DB of a particular application off to a different server, I just have to modify the hostname.
Traditionally it's usually db.domain.io, but that's because DNS entries is just not easily accessible and editable.
Answer: Your question has very little to do with Amazon Web Services but is connected to an overall server infrastructure layout. With that in mind I would recommend you structure your servers like this:
comp1.domain.io
comp2.domain.io
comp3.domain.io
db.domain.io

While you say:

So I have 3 components all connecting to same db.

It's not clear if you mean DB host or database itself. If for some reason each of the hosts needed their own DB, you could just come up with a database naming scheme such as:
comp1_db
comp2_db
comp3_db

And all of those DBs could be hosted at db.domain.io.
EDIT: This is in response to the original poster's edit.  If you have to transfer the DB, the process is never seamless & will take effort.  A hostname change for something like this is fairly radical & is out of your control. Amazon Route 53 is one thing, but DNS behavior outside of the Amazon hosting ecosystem is another. It's better for you in the long run to just use a common hostname but different DBs & perhaps related credentials.
Comment: Apology, please see edit.
Comment: @SleeperSmith I saw you edit & I think you are overthinking the issue. See my edit in response.


Activiti BPM: How can I get list of deleted process instance (task)

Question: How can I get list of deleted process instances (tasks). One way is to get the information for method getDeletedReason. However, do you have any other ways?
Answer: This sql query should give you all non completed historic instances without an active execution:
select h.proc_inst_id_ from act_hi_procinst h
left join act_ru_execution x on x.proc_inst_id_ = h.proc_inst_id_
where h.end_act_id_ is null and x.proc_inst_id_ is null


PHP fast way to replace content within string between characters

Question: In creating automatic emails certain parts of the email need to be replaced with stored data.
eg. Dear %first_name% %surname%, Thanks for attending the %place_name%.
This could be done with a string replace for each of them, but there must be a faster method.
Assuming that the variable name is identical to what we want from the system eg. %first_name% should be replaced with $user['first_name'] etc....
Answer: You can utilise preg_replace_callback to replace keys between %'s with array values:
$fields = array('first_name' => 'Tim', 'place_name' => 'Canada');

$string = preg_replace_callback('/%(.+?)%/', function($arr) use($fields)
{
    $key = $arr[1];
    return array_key_exists($key, $fields) ? $fields[$key] : $arr[0];
}, $string);

Comment: clever use of closures, which requires the newer versions of PHP
Comment: @Kristian:  PHP 5.3, the version which the anonymous function syntax was introduced, was released 3 years ago.  I wouldn't consider it newer, and I would hope everyone is upgraded to at least that version.
Comment: never underestimate the power of code / version requirements to forcefully slow down upgrades from happening
Answer: One option:
$vars = array(
  'firstname' = 'Bob',
  'surname' = 'Dole',
  'place' = 'Las Vegas',
  // ...
);
extract($vars);
include('my_template.phtml');

And in my_template.phtml:
<?php
echo <<<EOF
    Dear $firstname $surname,

    Thank you for attending the Viagra and Plantains Expo in $place.
EOF;
?>

If you're worried about name collisions while using extract(), you can always use the EXTR_PREFIX_ALL option, or one of the other extraction methods.
Or, better yet, don't reinvent the wheel. Just use Smarty or mustache.php.
See also this question: PHP template class with variables?
Comment: +1 this is what I do with outputting views, and I recommend it
Comment: @Kristian: Yea, CakePHP and probably a lot of other frameworks/libraries do it this way, albeit usually with additional features like output buffering and, in Cake 2.0, view blocks and view inheritance.


Ajustando o site para qualquer tela

Question: Bom galera, to tentando aprender melhor sobre o redimensionamento do site aplicado a qualquer tela. Já li alguns tutoriais na internet e pelo jeito não consegui fazer tudo direito, porque aqui no meu teste eu aplico as @medias só que ao entrar no site em questao por um dispositivo de tela pequena o site não redimensiona, ele abre com as configurações de uma tela maior doq a dele de fato.
O codigo que to usando é esse dai

<title>nada</title>

<meta name="viewport" content="width=device-width">

Como podem ver eu criei apenas uma unica div chamada de box, essa div é só pra teste, e se tudo ocorresse bem essa div ia mudar de cor conforme o tamanho do navegador. Quando testo isso em um navegador normal se eu diminuir o browse a div muda sua cor de acordo com o tamanho, porem no celular ele não obedece essa regra. O que está errado? ou o que está faltando?
Comment: Sugiro uma lida no link abaixo pois tem material bem legal relacionado ao que você precisa fazer (mais do que um monte de tutorial de media querie, aqui tem conteúdo conceitual e outras dicas indo além meramente de css e js). Link sugerido: http://www.smashingmagazine.com/responsive-web-design-guidelines-tutorials/#b1
Answer: Isso deve-se ao fato de você não estar indicando de que se deve checar o tamanho mínimo, para checar o tamanho da tela o código correto é esse:
@media only screen and (...)

Ajustando o site para qualquer tela


Select Multiple rows then join for each row

Question: I have a table that stores each location a user is watching. the table is called usercity and is pictured below an example row.

I need to SELECT all rows WHERE user_id='1', and then retrieve each location_id's record from the location table, which is pictured below:

I am not really sure where to start here, but here's my lame attempt:
   SELECT b.* FROM usercity a JOIN location b ON a.location_id=b.id WHERE user_id='1'

Edit My query Works with one record. not sure if it will work with multiple rows.
Answer: try below-
select a.*, b.*
from usercity a JOIN location b ON a.location_id=b.id
WHERE user_id=:uid

Answer: If its one-to-one relation then you can use inner join
select
uc.*,
l.* from usercity uc
join location l on l.location_id = uc.location_id
where l.user_id=:uid

Comment: Here is a nice tutorials on JOIN have a look http://www.sitepoint.com/understanding-sql-joins-mysql-database/
Comment: i don't know what that means. my knowledge of SQL is very basic to below average
Comment: What I meant for each entry in `usercity` there is one entry in `location` connected by `location_id` thats called `one-to-one`, if you have multiple records for the same `location_id` in `location` then its `one-to-many`, so in the 2nd case when you do join it will return multiple rows matching the 2 tables, and in case of one-to-one you just get one row.
Comment: Then just simple join is good, if you remove the where condition then you will get all the matching records from both tables, right now it will return only for supplied `user_id`
Comment: i understand basic SQL, just not JOINS and stuff. they confuse me
Answer: well, i kept playing with it and got what i want:
SELECT b.* FROM usercity a JOIN location b ON a.location_id=b.id WHERE user_id='1'
I guess SQL is one of those things you learn through practice.


Add easing to variable calculation based on scroll position

Question: I have some text elements that should move in their x-axis based on the scroll position.
Please see this pen for reference:
https://codepen.io/magglomag/pen/GRZwRNB
HTML

Lorem

ipsum

sonsetetur

sit

amet

CSS
html {
  height: 300vh;
}

.moving-text-wrapper {
  margin-top: 100vh;
  text-align: center;
}

jQuery
$.fn.moveIt = function(){
  var $window = $(window);
  var instances = [];

  $(this).each(function(){
    instances.push(new moveItItem($(this)));
  });

  window.addEventListener('scroll', function(){
    var scrollTop = $window.scrollTop();
    var elemOffsetTop = $( '.moving-text-wrapper' ).offset().top;
    var translateX = elemOffsetTop - scrollTop - $( window ).height()/2;

    instances.forEach(function(inst){
      inst.update(translateX);
    });
  }, {passive: true});
}

var moveItItem = function(el){
  this.el = $(el);
  this.speed = parseInt(this.el.attr('data-scroll-speed'));
};

moveItItem.prototype.update = function(translateX){
  this.el.css('transform', 'translateX(' + -(translateX / this.speed) + 'px)');
};

$(function(){
  $('[data-scroll-speed]').moveIt();
});

What I'd like to add is a little easing to the variable translateX, so when the scrolling stops the text will move a little bit longer and does not stop directly like in the current pen.
Any hints how to solve that?
Many thanks!
Answer: Actually this was quite easy to solve with CSS transitions:
I just added a transition to the elements like this:
.moving-text {
  transition-property: transform;
  transition-duration: 1s;
  transition-timing-function: ease-out;
}

See updated Codepen for reference:
https://codepen.io/magglomag/pen/YzqRPoX


every parent in the tree for each child with level for grand parent as 1

Question: Lets say we have the following data set.
PARENT     CHILD
---------- -----------
S1         S2
S2         S3
S3         S4
S4         S5
S5

I'd like list every parent in the tree for each child.
For example,
CHILD      PARENT        LEVEL
---------- -----------  ------
S5         S4              4
S5         S3              3
S5         S2              2
S5         S1              1
S4         S3              3
S4         S2              2
S4         S1              1
etc......

Answer: with
    tbl as (select 'S1' as parent,'S2'  as child from dual union all
                    select 'S2' as parent,'S3'  as child from dual union all
                    select 'S3' as parent,'S4'  as child from dual union all
                    select 'S4' as parent,'S5'  as child from dual union all
                    select 'S5' as parent, null as child from dual)
    ,tree as (select connect_by_root(t.child) r
                                    ,t.child,t.parent
                                    ,level l from tbl t
                        where child is not null
                        connect by  prior parent =child)
select r as "CHILD"
            ,parent  as "PARENT"
            ,max(l) over (partition by r) - l + 1 as "LEVEL"
from tree
where r is not null
order by r desc, l

SQL Fiddle


How to add a target to a Network Load Balancer in CloudFormation

Question: I've got some CloudFormation for a Network Load Balancer.
  PrivateNetworkLoadBalancerSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Access to the internal network load balancer
      VpcId: !Ref 'VPC'
  PrivateNetworkLoadBalancerIngressFromECS:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      Description: Only accept traffic from a container in the container host security group
      GroupId: !Ref 'PrivateNetworkLoadBalancerSG'
      IpProtocol: -1
      SourceSecurityGroupId: !Ref 'EcsHostSecurityGroup'
  PrivateNetworkLoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Type: network
      Scheme: internal
      Subnets:
        - !Ref PrivateSubnetOne
        - !Ref PrivateSubnetTwo
  DummyTargetGroupPrivateNetwork:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Name: !Join ['-', [!Ref 'AWS::StackName', 'drop-3']]
      Port: 6379
      Protocol: TCP
      # UnhealthyThresholdCount: 2
      VpcId: !Ref 'VPC'

And some for setting up a Redis docker container in ECS.
  RedisService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: !ImportValue "privatevpc:ClusterName"
      DesiredCount: 1
      TaskDefinition: !Ref RedisTaskDefinition

  RedisTaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      Family: redis
      ContainerDefinitions:
        - Name: redis
          Essential: true
          Image: "redis:latest"
          Memory: 512
          PortMappings:
            - ContainerPort: 6379
              HostPort: 6379
          LogConfiguration:
            LogDriver: awslogs
            Options:
              awslogs-group: !Ref CloudWatchLogsGroup
              awslogs-region: !Ref AWS::Region

  RedisTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      VpcId: !ImportValue "privatevpc:VPCId"
      Port: 6379
      Protocol: TCP
      HealthCheckProtocol: TCP

  RedisLoadBalancerListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
      - Type: forward
        TargetGroupArn: !Ref RedisTargetGroup
      LoadBalancerArn: !ImportValue "privatevpc:PrivateNetworkLoadBalancer"
      Port: 6379
      Protocol: TCP

But I'm manually having to add the EC2 instance that my RedisService is deployed to as a target for the RedisTargetGroup through the AWS web console. Any idea how I can have CloudFormation do that for me?
Comment: I think you can be guided by some examples where they create several Cloudformation resources like the ones you need: [link1](https://github.com/aws-samples/ecs-refarch-cloudformation) [link2](https://github.com/awslabs/aws-cloudformation-templates/tree/master/aws/services/ECS) [link3](https://templates.cloudonaut.io/en/stable/ecs/)
Comment: That's where I started.
Comment: You need to add autoscaling. Have you tried that?
Answer: I think you need to add the LoadBalancers property to RedisService. ECS should add the right EC2 instances to the specified target group automatically.
For example:
  RedisService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: !ImportValue "privatevpc:ClusterName"
      DesiredCount: 1
      TaskDefinition: !Ref RedisTaskDefinition
      LoadBalancers:
        - ContainerName: redis
          ContainerPort: 6379
          TargetGroupArn: !Ref RedisTargetGroup

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-loadbalancers.html


Problem with json serialization and fetch values

Question: I have data in JSON and I want to fetch data from structure like below - I want to get time value, in this case String: "04:35:00" and append all this time-values to my Hours model.
{
"result": [
    {
        "values": [
            {
                "value":"null",
                "key":"symbol_2"

            },
            {
                "value":"null",
                "key":"symbol_1"},
            {
                "value":"016",
                "key":"company"

            },
            {
                "value":"QUW12DO",
                "key":"direction"

            },
            {
                "value":"TD-4WYS",
                "key":"road"

            },
            {
                "value":"04:35:00",
                "key":"time"

}]},

//by code like this:
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in

        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {

            print(jsonObj!.value(forKey: "result")!)

            if let stopsArray = jsonObj!.value(forKey: "result") as? NSArray {

                    for stop in stopsArray{

                        if let stopDict = stop as? NSDictionary {

                            let hours = stopDict.value(forKey: "time")

                            let myModel = Hours(hours: hours as? String)
                            self.list.append(myModel)
                            print("LIST: \(self.list)")

                            DispatchQueue.main.async {
                                self.actInd.stopAnimating()
                                self.actInd.isHidden = true
                                self.containerLittle.isHidden = true
                                self.loadingView.isHidden = true
                            }
                        }
                    }

            }
        }
    }).resume()

On this moment when I append my code to model I have nill everywhere. How to fetch time value to model?
Comment: First - don't use `NSDictionary` or `NSArray` in Swift. Use a proper Swift dictionary and array. Fix that first and things will be a lot easier.
Comment: There is no `"time"` key in your response.
Answer: You have more complicated structure of JSON. Your JSON is Array of Dictionaries that contain Array of Dictionaries. Try this code:

    typealias JSONDict = Dictionary<String, Any>
    typealias JSONArray = Array<Any>

    if let result = jsonObj?["result"] as? JSONArray {
        for case let value as JSONDict in result {
            if let values = value["values"] as? JSONArray {
                for case let value as [String : String] in values {
                    if let timeString = value["value"], value["key"] == "time" {
                        // Create your Hours model
                        print(timeString)

                        // Use break only if you have single "time" member in "values" array
                        //break
                    }
                }

                // Use break only if you have single "values" member in "result" array
                //break
            }
        }
    }

Comment: @Moritz you are right about value(forKey:) method. It's just a typo from my side. I've replaced it with object(forKey:) method, thanks. What else errors do you see? This code works fine in Playground and provides the correct result.
Comment: @Moritz I've done some refactor, now it looks more like Swift way.
Comment: Yeah men, you made my day!  I only remove `break` and myModel contains all what i need. Thanks!


Use a mixins to change variable value

Question: I am generally quite new to sass and just wondered if it possible to define a new variable value, using mixins?
I thought it would be good to use a variable to define the padding size throughout the website I am building. The idea being that I could then use a mixin and media queries to define a new value.
An example might make more sense:
$site-padding:  40px;

@include media-over-767 {
    $site-padding: 20px;
}

I think this would be super useful but cannot get it to work... is there a method that works?
Comment: Even if @JinuKurian already answered, I think you should take a look at scoped variables in sass which may put you on another path to solve these sort of issues. Also, see the answer of [this thread](http://stackoverflow.com/questions/5469931/sass-variable-default-scope) for more details about how variables works (mixins and scoped variables).
Answer: You can't set a sass variable inside a breakpoint.
refer this issue - https://github.com/sass/sass/issues/1227
You could simply do
$site-padding:  40px;
$site-padding-sm:  20px;

@include media-over-767 {
    padding: $site-padding-sm;
}

refer this too - Using Sass Variables with CSS3 Media Queries
Answer: @mixin site-padding{
   $site-padding: 20px;
}

@include media-over-767 {
    @include site-padding;
}

Comment: The padding question is irrelevant to the answer, but if you need a mixin you could use to set the padding, here you go.

@mixin padding-all($top, $right, $bottom, $left) {
  padding-top: $top;
  padding-right: $right;
  padding-bottom: $bottom;
  padding-left: $left;
}
Comment: How does site-padding translate to padding? Is there another mixin that breaks this down to adding a `padding: 20px`?

I have not run into this previously with sass.
Comment: Thank you for the clarification and example.
Answer: I'm not sure if this is exactly what your looking for, but hopefully it gets you on the right path. Declare the mixin:
@mixin site-padding($padding:40px) {
    padding: $padding;
}

In that example, I set the mixin site-padding with a default value of 40px.
Your SASS would look something like this:
.element {
     // Small screens
     @include site-padding(20px);

     // Over 767px
     @media screen and (min-width: 768px) {
        // Defaults to 40px.
        @include site-padding();
     }
}

Use a mixins to change variable value


Android Service stop by itself?

Question: I am trying to create my own clock or timer using android CountdownTimer. So , i want that , even if , i closed my application , the android service should run and which will update my clock. So when i will be opening my application , i can see the latest time.
My code is working fine , but sometime after long time , the service stop by itself. So , the timer stops and i am seeing time in the application.
So , please let me know , how to restrict the service to stop by itself.
Comment: Yes i got some hint. But how startForeground will handle the memory low issue. but may which tablet is i am using , that is brand new one how can it possible to have memory low issue.
Comment: is the following answer worked for you?
Answer: It's achievable through START_REDELIVER_INTENT,START_STICKY
<code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    // START_REDELIVER_INTENT
    return START_STICKY;
}
</code>
Answer: The Android system will force-stop a service only when memory is low and it must recover system resources for the activity that has user focus.
But you can use startForeground(int, Notification). http://developer.android.com/reference/android/app/Service.html#startForeground(int, android.app.Notification).
Here you can find a lot of useful information:  http://developer.android.com/guide/components/services.html

Android Service stop by itself?


Prove that if $D$ is a digraph such that $od(v) \geq k \geq 1$ for every $v \in V(D)$ then $D$ contain a cycle of length at least $k+1$

Question: Prove that if $D$ is a digraph such that $od(v) \geq k \geq 1$ for every $v \in V(D)$ then $D$ contain a cycle of length at least $k+1$
I tried to prove this by induction. So here is what I got so far
Base: $od(v)=k=1$, then I got a digraph with a bunch of symmetric arcs, which contain a lot of cycle length 2. So the base case is good.
Inductive: Suppose that the statement is true for some $k$, meaning  $od(v) \geq k \geq 1$ for every $v \in V(D)$ then $D$ contain a cycle of length at least $k+1$. And I want to show $od(v) \geq k+1 \geq 2$ for every $v \in V(D)$ then $D$ contain a cycle of length at least $k+2$.
I add one vertex called $w$, since every vertex must have out degree at least $1$, connect $w \to v$, but it doesn't say that the in degree must be at least 1, so I don't know if this new vertex will increase the length of the cyle.
Answer: We consider the longest path $v_0 \to  v_1 \to \cdots \to v_n$ where the $v_i \neq v_j$ for $i \neq j$. If there is a vertex $u \notin \{v_0, \cdots, v_n \}$, then $v_0 \to \cdots \to v_n \to u$ becomes a longer path. Hence for all $v_n \to u$, there exists an $i$ such that $u = v_i$.
Now because $od(v_n) \ge k$, there should exist at least $k$ vertices $v_{a_1}, \cdots, v_{a_k}$ such that $v_n \to v_{a_i}$ for all $i = 1, \cdots, k$ and $a_1 < \cdots < a_k < n$. Since $a_1 \le n-k$, we now have a cycle $v_{a_1} \to v_{a_1+1} \to \cdots \to v_n \to v_{a_1}$ which is of length at least $k+1$.
Comment: just want to make sure, you started over with a direct proof, right?
Comment: Yes, and I don't see a proof based on induction right now.
Comment: So I can do the same if $id(v) \geq k\geq 1$, just changing the direction of the edges, right?
Comment: Yes I suppose you can.


How to include js file in a module which depend on jquery?

Question: I have a module called catalog_menu
I included a js file within this module in this way:
drupal_add_js(drupal_get_path('module', 'catalog_menu') . '/js/catalog_menu.js');

Now in the browser I get this error message:
Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function

I think that the problem is that catalogo_menu.js is loaded before jquery.js (the jquery library)
What is the right way to load a js file which depends on jquery library?
Comment: Are you using Drupal 7?
Answer: I actually think it is pretty unlikely that you have a weight problem, unless you redefined your module to have a extremely low weight.  Make sure you have JS optimization turned off, and then do a view source and make sure jQuery is the first script loaded (nearly always is).
My two guesses are

You have a JS error somewhere else, and this is a weird side effect.
You have a JS error in your catalog_menu.js (or another file) that is nuking the $ object by accident.

Also, you should you use an anonymous closure or JS module pattern for code, because Drupa 7 defaults jQuery no-conflict mode.
(function ($, Drupal) {
  function init () {
    $("body").addClass("catalog-menu");
  }

  Drupal.behaviors.catalog_menu = {
    attach: init
  };
}(jQuery, Drupal));

Comment: I tried just leaving these lines: (but not working at all, not error message neither)
Comment: (function ($, Drupal) {

 function init () {
   $('.logo-img').hide();
  }

  Drupal.behaviors.catalog_menu = {
    attach: init
  };

}(jQuery, Drupal));
Answer: You can change your module's weight to ensure it gets loaded after everything else.
Several ways :

SQL the system table (update system set weight=9999 where name = 'mymodule')
use the Module Weight submodule from the Util module.


Number of solutions to a differential equation

Question: The number of solutions of $$\frac{dy}{dx} = \frac{y+1}{x-1}$$ when $y(1) = 2$ is
Options are a) none   b) one   c) two   d) infinite
Now this can be solved via variable separable method which gives me
$$\frac{dy}{y+1} = \frac{dx}{x-1}$$
And on integrating both sides I got,
$\log (y + 1) = \log(x - 1) + \log c$
which gave me
$y + 1 = c(x - 1)$
On putting the given values as $x = 1$ and $y = 2$ gives
$3 = 0$ or $c = \frac{3}{0}$ which means no solution.
I just want to ask if my solution is correct because the book gave the answer as one solution. I checked few other places and they for some reason are solving by integrating as
$\log (y + 1) = \log(x - 1) - \log c$
which of course would give them the desired one solution as $x = 1$.
I am confused.
Comment: How did you get $\log c$
Comment: How changing it to $-\ln c$ gives one answer? $y=\frac1c(x-1)-1$ don't have a solution for the initial condition
Comment: @AndrewLi arbitrary constant, if we have $c$, because $\ln$ is one to one we can set $\ln c_0=c$
Comment: In what class of functions you are looking for a solution? Obviously if $x=1$ and $y$ is not $-1$ we have a discontinuity in the first derivative.
Answer: The problem is ill-posed since $x=1$ is a singular point. But even if you consider the given point to be a limit, you can see from the general solution that
$$ \lim_{x\to 1} y(x) = \lim_{x\to1} \big[c(x-1)-1 \big] = -1 $$
Clearly, there are no such functions where $\lim_{x\to1} y(x) = 2$
Answer: Your general solution $y=c(x-1)-1$ is correct by direct check
$$\frac{dy}{dx} =\frac{y+1}{x-1}=\frac{c(x-1)-1+1}{x-1}=cx$$
but since the equation is defined for $x\neq 1$ we have no solution for this particular initial condition.
Comment: I think you mean $c$, instead of $cx$.
Comment: If he considers functions that have infitine derivatives there is a solution.
Answer: If you consider $x(y)$ not $y(x)$ you'll get $x = 1 + (1 + y)\cdot c$, and therefore substituting $y=2$ you'll get $c=0$ if you want $x=1$. The solutions is therefore $x(y)=1$.
Edit: also mind that $\int dx/x=\ln|x|$.
Comment: I disagree. $dy/dx$ clearly means $y$ is the dependent variable. You can flip it only if the function $y(x)$ is invertible.
Comment: That function is not invertible and therefore does not solve the original equation.
Comment: @Dylan original equation is not written in a form that uniquely  prescribes function and independent variable. You can flip it and be absolutely fine.
Comment: @Dylan what's the difference from $1/(dx/dy)$? It doesn't matter whether function is invertable or not, differentials are not aware of those matters. If you had $d^{2}y/dx^{2}$ then yes, function and independent variables are clearly distinct.
Comment: $dy/dx$ is not a fraction. It's a first derivative of $y$ w.r.t $x$. Differentials are not involved here. The relation $dx/dy = (dy/dx)^{-1}$ only holds if and only if $y(x)$ is an invertible function.
Comment: Also, let's not forget that the initial condition clearly states $y(1) = 2$, *not* $x(2)=1$
Comment: @Dylan since he's interested in extensive search for solutions this is quite obvious approach.
Comment: The method is valid. The solution isn't.
Comment: @Dylan that's not how it works.
Comment: Why not? Correct methods do not always lead to a solution. In this case, what you obtained cannot be expressed as a function of $x$, therefore it's not a valid solution. That *should* be your conclusion here.
Comment: @Dylan that's only if you discard this solution on purpose. Relation between differentials and initial condition holds.
Comment: The equation isn't written in the form of differentials. It's a derivative, implying a function of $x$.
Comment: Just to be clear, we *should* discard this solution because it is not a function. It's just an extraneous solution you get when turning $dy/dx$ into $dx/dy$. It's like when you square the equation $x=2$ to $x^2=4$ to get an extraneous solution of $x=-2$
Comment: @Dylan flipping equation is not squaring one. And since initial condition is defined in $x=-1$ there's clearly no issues with zeroes in denominator so you can just multiply by it.


Analytic functions close to $\bar{z}$

Question: Is there an analytic function $f\colon\Bbb{C}\longrightarrow \Bbb{C}$ such that for any $z$ on the unit circle $\lvert f(z) - \overline{z}\rvert < 1 $?
Answer: No, there is no such function, because if there were, we would have
$$1 = \left\lvert\frac{1}{2\pi i}\int_{\lvert z\rvert = 1} \overline{z}\, dz\right\rvert = \left\lvert\frac{1}{2\pi i} \int_{\lvert z\rvert = 1} \bigl(\overline{z} - f(z)\bigr)\, dz \right\rvert \leqslant \frac{1}{2\pi} \int_0^{2\pi} \lvert \overline{z} - f(z)\rvert \, dt < 1$$
by Cauchy's integral theorem and the standard estimate.
We find $\frac{1}{2\pi i}\int_{\lvert z\rvert = 1} \overline{z}\,dz = \frac{1}{2\pi i}\int_0^{2\pi} e^{-it} ie^{it}\,dt = 1$ by direct evaluation, or by observing that $\overline{z} = 1/z$ on the unit circle. Cauchy's integral theorem asserts that $\int_{\lvert z\rvert = 1} f(z)\, dz = 0$, from which we get the second equality.

A more geometric argument:
The condition $\lvert \overline{z} - f(z)\rvert < 1$ on the unit circle implies that, as mappings of the unit circle to $\mathbb{C}^\ast$, $f$ is homotopic to $\overline{z}$, in particular, both have the same winding number around $0$, namely $-1$. But the winding number of $f$ (restricted to the unit circle) around $0$ is
$$\frac{1}{2\pi i} \int_{\lvert z\rvert = 1} \frac{f'(z)}{f(z)}\, dz$$
which is the number of zeros of $f$ in the unit disk (counted with multiplicity): a non-negative integer.
Comment: I'll ad a fuller explanation to the answer, have a few minutes patience.
Comment: Would you please explain why the first equality above is correct ?
Comment: what do you mean by $f$ is homotopic to $\bar{z}$ and why it is true?
Comment: There is a homotopy between $f\lvert_{S^1}$ and $\overline{z}\lvert_{S^1}$, that is, a continuous map $H\colon[0,\,1]\times S^1\to\mathbb{C}^\ast$ with $H(0,z)=f(z)$ and $H(1,z)=\overline{z}$. We can choose $H(t,z)=(1-t)\cdot f(z)+t\cdot\overline{z}$. The condition $\lvert f(z)-\overline{z}\rvert<1$ on $S^1$ implies that the line segment connecting $f(z)$ and $\overline{z}$ does not contain the origin, hence indeed $H\colon[0,\,1]\times S^1\to\mathbb{C}^\ast$. Then $n(t)=\frac{1}{2\pi}\int_0^{2\pi} \frac{\partial H(t,e^{is})/\partial s}{H(t,e^{is})}\,ds$ is continuous.
Comment: Since $n(t) \in \mathbb{Z}$ for all $t$ (it is the winding number around $0$ of the closed path $H(t,\,\cdot\,)$), $n(t)$ is constant, in particular $n(0) = n(1)$.
Answer: Let me give an alternative proof. Suppose $f$ is the desired function. Then for $z\bar{z} = 1$:
$$ |z f(z) - 1| = |z| |f(z) - \bar{z}| < 1 $$
so $g(z) = zf(z) - 1$ is an analytic function satisfying $|g(z)| < 1$ whenever $|z| = 1$. By the maximum modulus principle
$$ 1 =  |0 \cdot f(0) - 1| = |g(0)| < 1$$
which gives a contradiction.
Comment: Note that also if the inequality were not strict, then $f(z) = 0$ is a solution.
Comment: Yes, your interpretation is fine.

Analytic functions close to $\bar{z}$


How to include the build date and version number in Sandcastle builds

Question: I'd like the date when the doc was built and a version number to be appended to the footer of all Sandcastle builds.
I use the SHFB gui to create the project file and then automate the build using TeamCity.  Is there a way to get the build date and the TeamCity build # into the output?
Update:
I tried entering the footer text like Jeff suggested, but it does not add that to any page that I've seen.
Answer: Not sure about the TeamCity build number, but I was able to get the build date by adding this nonsense to the "Additional footer content" field in the Help File properties:
<code>Documentation built {@BuildDate:yyyy\-MM\-dd}.
</code>
Answer: You can add replacement tags for the build date and time, like Jeff indicated. See
Customizing the build process for more options.
The documentation itself has no version, but you can display the Framework version, but that's probably not what you want.


connection between $x\otimes f$ and rank-one operators

Question: Let $X$ be a Banach space.Then for every nonzero $x\in X$, and nonzero $f\in X^*$, I'm told that the tensor product $x\otimes f: X\rightarrow X$ defined by $(x\otimes f)y=f(y)\,x$ is a rank-one operator and every rank-one operator can be written in this way.
I have showed that such nonzero linear functional $f$ must be surjective and thus the range of $x\otimes f$ is $\mathrm {span}(x)$. But why is every rank one operator of the form $x\otimes f$? Could anyone please tell me a solution or reference?
Comment: What's a nonzero element of $X^*$ that isn't surjective?
Comment: @Zackkenyon Thanks for your comment. I have already proved that f is surjective.
Answer: Let $\ell$ be a bounded rank-one linear functional. Then by definition, its range is of dimension $1$, so there exists $x\neq 0$ such that it is $\mathrm{span}(x)$. Hence for any $y\in X$, there exists a scalar (say $f(y)$) such that $\ell(y) = f(y)\,x$. Since $\ell$ is linear and bounded, so is $f$, which proves $f\in X^*$.


migration erorr in asp.net mvc

Question: [why this erorr[enter image description here](https://i.stack.imgur.com/ntWwk.png)](https://i.stack.imgur.com/Hpxgh.png)
i want to add migration
Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Comment: [Design-time DbContext Creation](https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli)
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: For a better description of the error you are getting add the following parameter -verbose to the add-migration command. Full command: add-migration Initial -verbose
That should give you a more detailed error description of what the problem is.
Answer: Try these steps:
1- Make sure setting your project as Startup Project.
2- In Package Manager Console, set your data access layer (if any) as a default project
Now try agian and see what happens. Besides, you can read the given link from the message and check what's wrong with your code.
In fact, we need more detailed information about your issue, like what happened while you tried to run the command and what troubleshooting step you have already done. Showing some codes will be helpful here.

migration erorr in asp.net mvc


Prove that if $[a]_n = [r]_n$, then $[a^k]_n = [r^k]_n$

Question: Let $a, r, n \in \mathbb{Z}$ with $n>0$. Prove that if $[a]_n = [r]_n$, then for all $k \in \mathbb{N}$, $[a^k]_n = [r^k]_n$.
So far this is what I have:
Proof: Let $a, r, n \in \mathbb{Z}$ with $n>0$. Assume $[a]_n = [r]_n$. Note that then $n| a-r$, i.e., $a-r=nx$ for some $x\in \mathbb{Z}$. Our proof strategy will be by induction on $k$. Base Case: Let $k=1$. Then $[a^1]_n = [r^1]_n$ since $[a^1]_n=[a]_n$ and $[r^1]_n=[r]_n$. Induction Step: Let $k>1$. Assume by induction that $[a^{k-1}]_n = [r^{k-1}]_n$. Then $n|a^{k-1}-r^{k-1}$, i.e., $a^{k-1}-r^{k-1}=nz$ for some $z\in \mathbb{Z}$.
From there I have trouble. I know I need to get to $a^k-r^k=ny$ for some $y\in \mathbb{Z}$ since then $[a^k]_n = [r^k]_n$. I am not sure how to get there from the information that I have.
Comment: $[a]_n$ is the congruence class of $a$ modulo $n$
Comment: I'm trying to prove this for fun, but I'm not sure what square brackets here mean [ ] in this context. Is it a series of some sort? Thanks!
Comment: Great, I've used that info and the hint provided by Brian to complete the proof (Don't peak if you want to do it yourself).
Answer: Proof by induction, using the hint given by Brian.
By taking two base cases we see:
$$k=0 \implies [a^0]_n = [r^0]_n = [1]_n$$
and by our hypothesis
$$k = 1 \implies [a^1]_n = [r^1]_n$$
Therefore our base case is established for some $k-1$ and $k-2$. Now let us show the case for $k$:
By the definition of congruence, for $z \in \mathbb{Z}$, we have
$$a^{k-1} - r^{k-1} = nz $$
and therefore by some algebra we get
$$a^k - ar^{k-1} = n(az)$$
$$ra^{k-1} - r^k = n(rz)$$
The addition of these equations yields
$$a^k - r^k + ra^{k-1} - ar^{k-1} = n(za + zr)$$
bringing some terms to the RHS and factoring yields
$$a^k - r^k = ar(r^{k-2} - a^{k-2}) + n(za + zr)$$
But notice that the term containing powers of $k-2$ has been shown in the base case to be a congruence relation and therefore we can rewrite again (for $x \in \mathbb{Z}$):
$$\begin{align}a^k - r^k &= ar(nx) + n(za + zr) \\ &= n(rnx + za + zr) \end{align}$$
Where we see that $n$ is multiplied by a factor which is the sum of integers and is therefore also an integer. Thus, because congruence is an equivalence relation, $a^k \equiv r^k$ (mod $n$) and $r^k \equiv a^k$ (mod $n$). So finally we have that $[r^k]_n = [a^k]_n$.
Answer: Multiply both sides of $a^{k-1} - r^{k-1} = nz$ by $a$ and $r$ to get two equations
$$a^k - ar^{k-1} = n(az) \\ ra^{k-1} - r^k = n(rz)$$
Now add them and solve for $a^k - r^k$:
$$a^k-r^k = n(az+rz) - ra(a^{k-2} - r^{k-2})$$
Can you think of how to proceed from here? (hint: you may want to go back to your base case and show the equation is true for $k=0$, or maybe $k=2,$ to use a slightly stronger induction)
Answer: 1)
$[r]_n = [a]_n \iff a = r+ nm$ for some integer $m$.
So $a^k = (r+nm)^k = \sum_{j=0}^k{k\choose j}r^{k-j}(nm)^j$
$= r^k + \sum_{j=1}^k{k\choose j}r^{k-j}(nm)^j=r^k + n(\sum_{j=1}^k{k\choose j}r^{k-j}n^{j-1}m^j)$
And so $a^k - r^k =  n(\sum_{j=1}^k{k\choose j}r^{k-j}n^{j-1}m^j)$ and $[a^k]_n= [r^k]_n$
2)
You've probably already proven if $[a]_n=[r]_n$ and $[b]_n=[s]_n$ then $[ab]_n= [rs]_n$.  (If not prove it now[1]).
And clearly by induction if you have any number of $[a_i]_n=[r_i]_n$ and  then
$[a_1a_2]=[r_1r_2]$ so $[(a_1a_2)a_3]=[(r_1r_2)r_3]$ and so on so $[\prod a_i]=[\prod r_i]$.
And so $ [a^k]=[a\cdot a\cdot a\cdot ......\cdot a]=[r\cdot r\cdot r\cdot ......\cdot r]=[r^k] $.
.......
[1] $a= r + mn$ and $b =s + jn$ for some $m,j$ so $a+b=(r+s) + n(m+j)$


Search Taxonomy Term pages containing entity referenced nodes

Question: So, I've got myself into a bit of a pickle here and was hoping that could point out a way through.

Drupal 7
Views
Display Suite
Entity Reference
Inline Entity Reference
Search API
Database Search

I have been building a sort of hybrid traditional multi-page and single-page site within the Bootstrap framework. In order to meet these requirements I have used an inline entity reference field to group multiple different nodes (each representing a Display Suite layout, such as 50%-50%, 33%-33%-33% etc) into a content type called 'Subject'. These 'Subjects' are to form each distinct row in a single-page style layout.
This has worked well, and I now need to compile these 'Subjects' into pages.
Because I want to avoid too much complexity in the workflow I decided against nesting these 'Subjects' into yet another content type called 'Page' using more entity references. Instead I went for a taxonomy vocabulary called 'Sitemap' with a term for each page, which could be selected from a term reference field in the 'Subject' content type. I then use a view to spit out all of the referenced 'Subject' nodes associated with that term as rendered entities.
TL;DR - I have a series of taxonomy term pages full of referenced rendered entity nodes.
When looking at implementing search I just can't get my head around how to index and display results. I obviously need the contents of these term pages to be indexed, but I also need to ensure that results will only point to term pages (preferably deep linked) and not any of the original nodes referenced on the term page. Granted, I'm not very familiar with it, but looking at Search API I can't see how I could achieve that.
Is this just a really silly way to achieve this kind of structure?
Answer: I stumbled upon a module called Search by Page Paths which swerves the above issue by indexing the front end of the site. This approach means that regardless of the source of my data and where it is placed, it will see anything rendered out onto a page as part of that page.
The main caveat is that one must specify paths to index, but in terms of my particular build this isn't a bad thing and means I have complete control over where a user ends up after searching.


Display popup textbox

Question: I need some help here. I need to display a popup textbox. For example, there is a quantity that the user need to insert to display textbox :
Quantity : 3

If the user insert 3, then 3 textbox will be display.
ID : (Textbox)
     (Textbox)
     (Textbox)

Comment: Is this a homework question? If so, please flag as such.
Comment: Thanks for letting us know what you are doing. If you have any questions feel free to ask.
Answer: html:
<input type="text" name="qty" id="qty" />
<input type="button" name="btn" id="btn" />

js:
$(function() {
    $('#btn').click(function() {
        var qty = $('#qty').val();
        if (qty > 0) {
            for (var i = 0; i < qty; i++) {
                $('body').append('<input type="text" />');
            }
        }
    });
});

Answer:     for(var i=0; i<quantity; i++)
        Alert("your message");

Comment: "your message"?For example?I'm sorry, I'm not really good in html or javascript.
Comment: @20151012 am assuming the message you want to display? Anything you want displayed on the screen
Comment: It looks like 20151012 needs the dialog to accept three user inputs (in this case) rather than display a static message three times.

Display popup textbox


Ruby association: has one through many - Is it possible?

Question: I want to have a strange kind of an association. Lets say I have a the following classes:
class Kid < ActiveRecord::Base
    belongs_to :parent
    has_one :friend
end

class Friend < ActiveRecord::Base
    belongs_to :kid
end

class Parent < ActiveRecord::Base
    has_many :kids
    has_one :friend, :through => :kid #This is the "problematic line"
end

I know the last relation(has_one :friend) is not possible and doesn't make sense. But lets say that I know that the Friend of the first Kid always has enough information for my Parent instance, so I want to get it like 'parent.friend' instead of parent.kids.first.friend
Answer: No, that doesn't make any sense.  if a parent has many kids, then they can't have just one friend, they would have as many friends as they had kids.
Parent.friend doesn't make any sense - the friend of which kid?
If it's always the first, make a function:
def first_friend
  kids.first.friend
end

If you want a list of friends...
def friends
  kids.map(&:friend)  # note this queries immediately, it is not a named scope
end

If you want to go the other direction to get a list of friends for a parent, use a named scope in the Friend model:
named_scope :for_parent, lambda {|p| joins(:kids).where('kids.parent_id = ?', p)}

Comment: I agree with this approach, I just had to work on a weird code where the scenario I described seemed logical :\ ... just wanted to make sure I was not missing something. Thanks anyway....


Hide tabs on all pages

Question: On every page on my site, there are always these tabs on display:

News, Events, Grant.

I have been able to hide them on specific pages using CSS Injector however I want to disable these tabs from appearing.
How can I do this?
I have added a screenshot for reference:
Comment: Do the tabs persist if you log out of the site? They seem like standard tabs for administrative users who have relevant permissions. If they appear then you're logged out then I'd wager your issue is actually with permissions and not the tabs displaying.
Comment: Please add screenshot here instead of adding link. I see some porn images there (may be ads).That would be too bad for your post. Sometimes may consider your post as SPAM :) I can't dare to open that ilnk again and paste that image here for you :)
Comment: I tried adding the image here in not allowed.
Comment: Don't add image from the web (from link). upload that image from your computer instead.
Comment: I agree with the above comment by Chapabu. But if you really want to hide them do it with css or your page.tpl.php ($tabs)
Answer: Are those tabs menu entries? Check the menus you have listed in structure > menus. I'm not sure what menu it would be in because it may depend on the theme so click through them all.
Those could also be potentially generated by a View so check entries in structure > views as well.
Answer: Try the Tab Tammer module

Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.

Hide tabs on all pages